From cbf09319488928298b51f1a65d6378547d4a9da1 Mon Sep 17 00:00:00 2001 From: William Escande Date: Fri, 31 May 2024 11:54:50 -0700 Subject: [PATCH] Reformat java file in android/app/tests Bug: 311772251 Flag: Exempt refactor Test: None Change-Id: I9d280c4e5ad8c7362f6dff440b27180ee0e230b1 --- .../bluetooth/FileSystemWriteTest.java | 5 +- .../bluetooth/ObexAppParametersTest.java | 12 +- .../android/bluetooth/SignedLongLongTest.java | 10 +- .../src/com/android/bluetooth/TestUtils.java | 114 +- .../src/com/android/bluetooth/UtilsTest.java | 15 +- .../bluetooth/a2dp/A2dpCodecConfigTest.java | 830 +++++---- .../bluetooth/a2dp/A2dpServiceBinderTest.java | 2 +- .../bluetooth/a2dp/A2dpStateMachineTest.java | 197 +- .../a2dpsink/A2dpSinkServiceBinderTest.java | 2 +- .../a2dpsink/A2dpSinkServiceTest.java | 178 +- .../a2dpsink/A2dpSinkStateMachineTest.java | 6 +- .../a2dpsink/A2dpSinkStreamHandlerTest.java | 40 +- .../BrowsablePlayerConnectorTest.java | 40 +- .../audio_util/BrowserPlayerWrapperTest.java | 67 +- .../bluetooth/audio_util/GPMWrapperTest.java | 42 +- .../bluetooth/audio_util/ImageTest.java | 199 +- .../audio_util/MediaPlayerListTest.java | 46 +- .../audio_util/MediaPlayerWrapperTest.java | 62 +- .../bluetooth/audio_util/MetadataTest.java | 1058 +++++++---- .../bluetooth/audio_util/UtilTest.java | 39 +- .../avrcp/AvrcpBipObexServerTest.java | 161 +- .../avrcp/AvrcpCoverArtStorageTest.java | 20 +- .../bluetooth/avrcp/AvrcpPassthroughTest.java | 227 ++- .../avrcp/AvrcpVolumeManagerTest.java | 6 +- .../android/bluetooth/avrcp/CoverArtTest.java | 60 +- .../avrcpcontroller/AvrcpBipClientTest.java | 24 +- .../AvrcpControllerServiceBinderTest.java | 3 +- .../AvrcpControllerServiceTest.java | 57 +- .../AvrcpControllerStateMachineTest.java | 468 +++-- .../AvrcpCoverArtProviderTest.java | 13 +- .../AvrcpCoverArtStorageTest.java | 23 +- .../avrcpcontroller/AvrcpItemTest.java | 313 ++-- .../avrcpcontroller/AvrcpPlayerTest.java | 48 +- .../avrcpcontroller/BrowseNodeTest.java | 121 +- .../avrcpcontroller/BrowseTreeTest.java | 55 +- .../PlayerApplicationSettingsTest.java | 162 +- .../avrcpcontroller/StackEventTest.java | 10 +- .../bip/BipAttachmentFormatTest.java | 301 ++- .../avrcpcontroller/bip/BipDatetimeTest.java | 81 +- .../avrcpcontroller/bip/BipEncodingTest.java | 43 +- .../bip/BipImageDescriptorTest.java | 95 +- .../bip/BipImageFormatTest.java | 110 +- .../bip/BipImagePropertiesTest.java | 272 +-- .../avrcpcontroller/bip/BipImageTest.java | 32 +- .../avrcpcontroller/bip/BipPixelTest.java | 87 +- .../bip/BipTransformationTest.java | 31 +- .../bip/RequestGetImagePropertiesTest.java | 14 +- .../bip/RequestGetImageTest.java | 10 +- .../bas/BatteryServiceBinderTest.java | 5 +- .../bluetooth/bas/BatteryServiceTest.java | 175 +- .../bas/BatteryStateMachineTest.java | 48 +- .../bluetooth/bass_client/BaseDataTest.java | 2 +- .../bass_client/BassClientServiceTest.java | 881 +++++---- .../BassClientStateMachineTest.java | 633 ++++--- .../BleBroadcastAssistantBinderTest.java | 15 +- .../PeriodicAdvertisementResultTest.java | 51 +- .../bass_client/PublicBroadcastDataTest.java | 51 +- .../btservice/ActiveDeviceManagerTest.java | 275 ++- .../btservice/AdapterServiceBinderTest.java | 2 +- .../btservice/AdapterServiceRestartTest.java | 29 +- .../btservice/AdapterServiceTest.java | 85 +- .../btservice/BondStateMachineTest.java | 565 +++--- .../btservice/CompanionManagerTest.java | 41 +- .../btservice/DataMigrationTest.java | 112 +- .../bluetooth/btservice/PhonePolicyTest.java | 437 +++-- .../btservice/ProfileServiceTest.java | 1 - .../btservice/RemoteDevicesTest.java | 422 +++-- .../btservice/SilenceDeviceManagerTest.java | 48 +- .../BluetoothKeystoreServiceTest.java | 159 +- .../storage/DatabaseManagerTest.java | 802 ++++---- .../csip/BluetoothCsisBinderTest.java | 5 +- .../csip/CsipSetCoordinatorServiceTest.java | 277 +-- .../CsipSetCoordinatorStateMachineTest.java | 230 ++- .../bluetooth/gatt/AdvertiseHelperTest.java | 53 +- .../bluetooth/gatt/AdvertiseManagerTest.java | 36 +- .../bluetooth/gatt/AppAdvertiseStatsTest.java | 91 +- .../bluetooth/gatt/CallbackInfoTest.java | 10 +- .../bluetooth/gatt/ContextMapTest.java | 10 +- .../gatt/DistanceMeasurementManagerTest.java | 177 +- .../gatt/DistanceMeasurementTrackerTest.java | 51 +- .../bluetooth/gatt/FilterParamsTest.java | 32 +- .../bluetooth/gatt/GattDebugUtilsTest.java | 11 +- .../bluetooth/gatt/GattServiceBinderTest.java | 106 +- .../bluetooth/gatt/GattServiceTest.java | 139 +- .../hap/HapClientNativeInterfaceTest.java | 77 +- .../hap/HapClientStackEventTest.java | 279 +-- .../hap/HapClientStateMachineTest.java | 175 +- .../android/bluetooth/hap/HapClientTest.java | 605 +++--- .../HearingAidNativeInterfaceTest.java | 24 +- .../HearingAidStateMachineTest.java | 122 +- .../bluetooth/hfp/AtPhonebookTest.java | 174 +- .../hfp/BluetoothHeadsetBinderTest.java | 9 +- .../HeadsetAgIndicatorEnableStateTest.java | 4 +- .../hfp/HeadsetClccResponseTest.java | 73 +- .../bluetooth/hfp/HeadsetPhoneStateTest.java | 161 +- .../bluetooth/hfp/HeadsetStackEventTest.java | 10 +- .../hfp/HeadsetStateMachineTest.java | 1604 +++++++++------- .../bluetooth/hfp/HeadsetTestUtils.java | 62 +- .../HeadsetVendorSpecificResultCodeTest.java | 18 +- .../HeadsetClientServiceBinderTest.java | 3 +- .../hfpclient/HeadsetClientServiceTest.java | 10 +- .../HeadsetClientStateMachineTest.java | 785 ++++---- .../hfpclient/HfpNativeInterfaceTest.java | 8 +- .../bluetooth/hfpclient/StackEventTest.java | 25 +- .../VendorCommandResponseProcessorTest.java | 41 +- .../HeadsetClientServiceInterfaceTest.java | 40 +- .../hfpclient/connserv/HfpClientCallTest.java | 407 ++-- .../HfpClientConnectionServiceTest.java | 242 ++- .../connserv/HfpClientConnectionTest.java | 186 +- .../connserv/HfpClientDeviceBlockTest.java | 80 +- .../hid/BluetoothHidDeviceBinderTest.java | 36 +- .../hid/HidDeviceNativeInterfaceTest.java | 16 +- .../android/bluetooth/hid/HidDeviceTest.java | 280 ++- .../hid/HidHostServiceBinderTest.java | 7 +- .../bluetooth/hid/HidHostServiceTest.java | 95 +- .../le_audio/ContentControlIdKeeperTest.java | 35 +- .../bluetooth/le_audio/LeAudioBinderTest.java | 15 +- .../le_audio/LeAudioBroadcastServiceTest.java | 83 +- ...LeAudioBroadcasterNativeInterfaceTest.java | 29 +- .../le_audio/LeAudioNativeInterfaceTest.java | 61 +- .../le_audio/LeAudioServiceTest.java | 797 ++++---- .../le_audio/LeAudioStateMachineTest.java | 42 +- .../le_audio/LeAudioTmapGattServerTest.java | 3 +- .../AdvtFilterOnFoundOnLostInfoTest.java | 40 +- .../bluetooth/le_scan/AppScanStatsTest.java | 10 +- .../le_scan/ScanFilterQueueTest.java | 49 +- .../bluetooth/le_scan/ScanManagerTest.java | 299 ++- .../map/BluetoothMapAccountItemTest.java | 398 +++- .../map/BluetoothMapAppParamsTest.java | 117 +- .../map/BluetoothMapContentObserverTest.java | 1659 +++++++++++------ .../map/BluetoothMapContentTest.java | 1521 +++++++++------ .../BluetoothMapConvoContactElementTest.java | 125 +- .../BluetoothMapConvoListingElementTest.java | 44 +- .../map/BluetoothMapConvoListingTest.java | 14 +- .../map/BluetoothMapFolderElementTest.java | 57 +- .../map/BluetoothMapMasInstanceTest.java | 32 +- ...BluetoothMapMessageListingElementTest.java | 34 +- .../map/BluetoothMapMessageListingTest.java | 12 +- .../map/BluetoothMapObexServerTest.java | 176 +- .../map/BluetoothMapServiceBinderTest.java | 3 +- .../map/BluetoothMapServiceTest.java | 17 +- .../map/BluetoothMapSettingsTest.java | 15 +- .../bluetooth/map/BluetoothMapSmsPduTest.java | 107 +- .../bluetooth/map/BluetoothMapUtilsTest.java | 11 +- .../map/BluetoothMapbMessageEmailTest.java | 10 +- .../map/BluetoothMapbMessageMimeTest.java | 87 +- .../map/BluetoothMapbMessageSmsTest.java | 14 +- .../map/BluetoothMapbMessageTest.java | 78 +- .../map/BluetoothMapbMessageVCardTest.java | 63 +- .../bluetooth/map/ConvoContactInfoTest.java | 27 +- .../com/android/bluetooth/map/EventTest.java | 85 +- .../android/bluetooth/map/FilterInfoTest.java | 125 +- .../android/bluetooth/map/MapContactTest.java | 4 +- .../com/android/bluetooth/map/MsgTest.java | 36 +- .../bluetooth/map/SmsMmsContactsTest.java | 114 +- .../mapapi/BluetoothMapContractTest.java | 92 +- .../mapapi/BluetoothMapEmailProviderTest.java | 328 ++-- .../mapapi/BluetoothMapIMProviderTest.java | 446 +++-- .../bluetooth/mapclient/BmessageTest.java | 26 +- .../bluetooth/mapclient/EventReportTest.java | 4 +- .../mapclient/MapClientContentTest.java | 293 ++- .../mapclient/MapClientServiceBinderTest.java | 6 +- .../mapclient/MapClientServiceTest.java | 12 +- .../mapclient/MapClientStateMachineTest.java | 819 ++++---- .../bluetooth/mapclient/MapClientTest.java | 17 +- .../mapclient/MnsObexServerTest.java | 22 +- .../bluetooth/mapclient/ObexTimeTest.java | 48 +- ...estGetMessagesListingForOwnNumberTest.java | 309 +-- .../bluetooth/mapclient/RequestTest.java | 49 +- .../android/bluetooth/mcp/McpServiceTest.java | 13 +- .../mcp/MediaControlGattServiceTest.java | 709 ++++--- .../mcp/MediaControlProfileTest.java | 127 +- .../bluetooth/obex/FakeObexServer.java | 19 +- .../bluetooth/obex/FakeObexTransport.java | 21 +- .../bluetooth/opp/BluetoothOppBatchTest.java | 66 +- .../opp/BluetoothOppBtEnableActivityTest.java | 10 +- .../BluetoothOppBtEnablingActivityTest.java | 53 +- .../opp/BluetoothOppHandoverReceiverTest.java | 53 +- .../opp/BluetoothOppLauncherActivityTest.java | 62 +- .../opp/BluetoothOppManagerTest.java | 157 +- .../opp/BluetoothOppNotificationTest.java | 303 ++- .../BluetoothOppObexClientSessionTest.java | 77 +- .../BluetoothOppObexServerSessionTest.java | 110 +- .../opp/BluetoothOppPreferenceTest.java | 32 +- .../opp/BluetoothOppReceiveFileInfoTest.java | 151 +- .../opp/BluetoothOppReceiverTest.java | 209 ++- .../opp/BluetoothOppSendFileInfoTest.java | 69 +- .../opp/BluetoothOppShareInfoTest.java | 19 +- .../bluetooth/opp/BluetoothOppTestUtils.java | 91 +- .../opp/BluetoothOppTransferActivityTest.java | 138 +- .../opp/BluetoothOppTransferHistoryTest.java | 129 +- .../opp/BluetoothOppTransferTest.java | 232 ++- .../opp/BluetoothOppUtilityTest.java | 304 +-- .../opp/IncomingFileConfirmActivityTest.java | 149 +- .../android/bluetooth/opp/TestActivity.java | 405 ++-- .../BluetoothTetheringNetworkFactoryTest.java | 10 +- .../bluetooth/pan/PanServiceBinderTest.java | 3 +- .../android/bluetooth/pan/PanServiceTest.java | 28 +- .../pbap/BluetoothPbapActivityTest.java | 47 +- .../pbap/BluetoothPbapAuthenticatorTest.java | 49 +- .../BluetoothPbapCallLogComposerTest.java | 32 +- .../pbap/BluetoothPbapConfigTest.java | 20 +- .../pbap/BluetoothPbapObexServerTest.java | 185 +- .../pbap/BluetoothPbapServiceBinderTest.java | 3 +- .../pbap/BluetoothPbapServiceTest.java | 6 +- .../BluetoothPbapSimVcardManagerTest.java | 298 +-- .../pbap/BluetoothPbapUtilsTest.java | 116 +- ...oothPbapVcardManagerNestedClassesTest.java | 110 +- .../pbap/BluetoothPbapVcardManagerTest.java | 324 ++-- .../pbap/HandlerForStringBufferTest.java | 11 +- .../bluetooth/pbap/PbapStateMachineTest.java | 51 +- .../pbapclient/AuthenticationServiceTest.java | 15 +- .../pbapclient/AuthenticatorTest.java | 17 +- .../BluetoothPbapObexAuthenticatorTest.java | 7 +- ...toothPbapRequestPullPhoneBookSizeTest.java | 4 +- ...BluetoothPbapRequestPullPhoneBookTest.java | 71 +- .../pbapclient/BluetoothPbapRequestTest.java | 3 +- .../BluetoothPbapVcardListTest.java | 87 +- .../pbapclient/CallLogPullRequestTest.java | 40 +- .../PbapClientConnectionHandlerTest.java | 25 +- .../pbapclient/PbapClientServiceTest.java | 27 +- .../PbapClientStateMachineTest.java | 38 +- .../bluetooth/pbapclient/PbapParserTest.java | 98 +- .../android/bluetooth/sap/SapMessageTest.java | 22 +- .../bluetooth/sap/SapRilReceiverHidlTest.java | 359 ++-- .../bluetooth/sap/SapRilReceiverTest.java | 359 ++-- .../android/bluetooth/sap/SapServerTest.java | 99 +- .../android/bluetooth/sap/SapServiceTest.java | 10 +- .../com/android/bluetooth/sdp/DipTest.java | 59 +- .../android/bluetooth/tbs/TbsGattTest.java | 718 ++++--- .../android/bluetooth/tbs/TbsGenericTest.java | 274 ++- .../telephony/BluetoothCallTest.java | 22 +- .../telephony/BluetoothInCallServiceTest.java | 843 ++++++--- .../bluetooth/telephony/CallInfoTest.java | 16 +- .../bluetooth/util/GsmAlphabetTest.java | 325 ++-- .../vc/VolumeControlNativeInterfaceTest.java | 44 +- .../vc/VolumeControlServiceTest.java | 574 +++--- .../vc/VolumeControlStateMachineTest.java | 201 +- 238 files changed, 21007 insertions(+), 14806 deletions(-) diff --git a/android/app/tests/unit/src/com/android/bluetooth/FileSystemWriteTest.java b/android/app/tests/unit/src/com/android/bluetooth/FileSystemWriteTest.java index a0215a8a243..d04d2c2026e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/FileSystemWriteTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/FileSystemWriteTest.java @@ -25,10 +25,7 @@ import org.junit.runner.RunWith; import java.io.File; import java.io.IOException; -/** - * Test Bluetooth's ability to write to the different directories that it - * is supposed to own - */ +/** Test Bluetooth's ability to write to the different directories that it is supposed to own */ @MediumTest @RunWith(AndroidJUnit4.class) public class FileSystemWriteTest { diff --git a/android/app/tests/unit/src/com/android/bluetooth/ObexAppParametersTest.java b/android/app/tests/unit/src/com/android/bluetooth/ObexAppParametersTest.java index 4e8459168aa..c7bb30475e3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/ObexAppParametersTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/ObexAppParametersTest.java @@ -40,8 +40,10 @@ public class ObexAppParametersTest { public void constructorWithByteArrays_withOneInvalidElement() { final int length = 4; - byte[] byteArray = new byte[] {KEY, length, 0x12, 0x34, 0x56, 0x78, - 0x66}; // Last one is invalid. It will be filtered out. + byte[] byteArray = + new byte[] { + KEY, length, 0x12, 0x34, 0x56, 0x78, 0x66 + }; // Last one is invalid. It will be filtered out. ObexAppParameters params = new ObexAppParameters(byteArray); assertThat(params.exists(KEY)).isTrue(); @@ -53,8 +55,10 @@ public class ObexAppParametersTest { @Test public void constructorWithByteArrays_withTwoInvalidElements() { final int length = 4; - byte[] byteArray = new byte[] {KEY, length, 0x12, 0x34, 0x56, 0x78, - 0x66, 0x77}; // Last two are invalid. It will be filtered out. + byte[] byteArray = + new byte[] { + KEY, length, 0x12, 0x34, 0x56, 0x78, 0x66, 0x77 + }; // Last two are invalid. It will be filtered out. ObexAppParameters params = new ObexAppParameters(byteArray); assertThat(params.exists(KEY)).isTrue(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/SignedLongLongTest.java b/android/app/tests/unit/src/com/android/bluetooth/SignedLongLongTest.java index 0a4b682a42f..8a887b71eb7 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/SignedLongLongTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/SignedLongLongTest.java @@ -25,9 +25,7 @@ import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; -/** - * Test for SignedLongLong.java - */ +/** Test for SignedLongLong.java */ @SmallTest @RunWith(AndroidJUnit4.class) public class SignedLongLongTest { @@ -125,15 +123,13 @@ public class SignedLongLongTest { public void fromString_whenLengthIsNotGreaterThan16() throws Exception { String strValue = "1"; - assertThat(SignedLongLong.fromString(strValue)) - .isEqualTo(new SignedLongLong(1, 0)); + assertThat(SignedLongLong.fromString(strValue)).isEqualTo(new SignedLongLong(1, 0)); } @Test public void fromString_whenLengthIsGreaterThan16() throws Exception { String strValue = "B0000000000000002"; - assertThat(SignedLongLong.fromString(strValue)) - .isEqualTo(new SignedLongLong(2, 11)); + assertThat(SignedLongLong.fromString(strValue)).isEqualTo(new SignedLongLong(2, 11)); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java b/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java index e954a5cbccc..0821b7cd78c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java +++ b/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java @@ -54,11 +54,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; -/** - * A set of methods useful in Bluetooth instrumentation tests - */ +/** A set of methods useful in Bluetooth instrumentation tests */ public class TestUtils { - private static final int SERVICE_TOGGLE_TIMEOUT_MS = 1000; // 1s + private static final int SERVICE_TOGGLE_TIMEOUT_MS = 1000; // 1s private static String sSystemScreenOffTimeout = "10000"; @@ -67,17 +65,18 @@ public class TestUtils { /** * Utility method to replace obj.fieldName with newValue where obj is of type c * - * @param c type of obj + * @param c type of obj * @param fieldName field name to be replaced - * @param obj instance of type c whose fieldName is to be replaced, null for static fields - * @param newValue object used to replace fieldName - * @return the old value of fieldName that got replaced, caller is responsible for restoring - * it back to obj - * @throws NoSuchFieldException when fieldName is not found in type c + * @param obj instance of type c whose fieldName is to be replaced, null for static fields + * @param newValue object used to replace fieldName + * @return the old value of fieldName that got replaced, caller is responsible for restoring it + * back to obj + * @throws NoSuchFieldException when fieldName is not found in type c * @throws IllegalAccessException when fieldName cannot be accessed in type c */ - public static Object replaceField(final Class c, final String fieldName, final Object obj, - final Object newValue) throws NoSuchFieldException, IllegalAccessException { + public static Object replaceField( + final Class c, final String fieldName, final Object obj, final Object newValue) + throws NoSuchFieldException, IllegalAccessException { Field field = c.getDeclaredField(fieldName); field.setAccessible(true); @@ -93,8 +92,10 @@ public class TestUtils { * mocked or spied */ public static void setAdapterService(AdapterService adapterService) { - Assert.assertNull("AdapterService.getAdapterService() must be null before setting another" - + " AdapterService", AdapterService.getAdapterService()); + Assert.assertNull( + "AdapterService.getAdapterService() must be null before setting another" + + " AdapterService", + AdapterService.getAdapterService()); Assert.assertNotNull("Adapter service should not be null", adapterService); // We cannot mock AdapterService.getAdapterService() with Mockito. // Hence we need to set AdapterService.sAdapterService field. @@ -108,8 +109,10 @@ public class TestUtils { * TestUtils#setAdapterService(AdapterService)} */ public static void clearAdapterService(AdapterService adapterService) { - Assert.assertSame("AdapterService.getAdapterService() must return the same object as the" - + " supplied adapterService in this method", adapterService, + Assert.assertSame( + "AdapterService.getAdapterService() must return the same object as the" + + " supplied adapterService in this method", + adapterService, AdapterService.getAdapterService()); Assert.assertNotNull("Adapter service should not be null", adapterService); AdapterService.clearAdapterService(adapterService); @@ -134,7 +137,7 @@ public class TestUtils { * Create a test device. * * @param bluetoothAdapter the Bluetooth adapter to use - * @param id the test device ID. It must be an integer in the interval [0, 0xFF]. + * @param id the test device ID. It must be an integer in the interval [0, 0xFF]. * @return {@link BluetoothDevice} test device for the device ID */ public static BluetoothDevice getTestDevice(BluetoothAdapter bluetoothAdapter, int id) { @@ -148,11 +151,13 @@ public class TestUtils { public static Resources getTestApplicationResources(Context context) { try { - return context.getPackageManager().getResourcesForApplication( - "com.android.bluetooth.tests"); + return context.getPackageManager() + .getResourcesForApplication("com.android.bluetooth.tests"); } catch (PackageManager.NameNotFoundException e) { - assertWithMessage("Setup Failure: Unable to get test application resources" - + e.toString()).fail(); + assertWithMessage( + "Setup Failure: Unable to get test application resources" + + e.toString()) + .fail(); return null; } } @@ -161,7 +166,7 @@ public class TestUtils { * Wait and verify that an intent has been received. * * @param timeoutMs the time (in milliseconds) to wait for the intent - * @param queue the queue for the intent + * @param queue the queue for the intent * @return the received intent */ public static Intent waitForIntent(int timeoutMs, BlockingQueue queue) { @@ -178,9 +183,8 @@ public class TestUtils { /** * Wait and verify that no intent has been received. * - * @param timeoutMs the time (in milliseconds) to wait and verify no intent - * has been received - * @param queue the queue for the intent + * @param timeoutMs the time (in milliseconds) to wait and verify no intent has been received + * @param queue the queue for the intent * @return the received intent. Should be null under normal circumstances */ public static Intent waitForNoIntent(int timeoutMs, BlockingQueue queue) { @@ -200,9 +204,11 @@ public class TestUtils { * @param looper looper of interest */ public static void waitForLooperToFinishScheduledTask(Looper looper) { - runOnLooperSync(looper, () -> { - // do nothing, just need to make sure looper finishes current task - }); + runOnLooperSync( + looper, + () -> { + // do nothing, just need to make sure looper finishes current task + }); } /** @@ -263,19 +269,18 @@ public class TestUtils { } /** - * Run synchronously a runnable action on a looper. - * The method will return after the action has been execution to completion. + * Run synchronously a runnable action on a looper. The method will return after the action has + * been execution to completion. + * + *

Example: * - * Example: - *

-     * {@code
+     * 
{@code
      * TestUtils.runOnMainSync(new Runnable() {
      *       public void run() {
      *           Assert.assertTrue(mA2dpService.stop());
      *       }
      *   });
-     * }
-     * 
+ * }
* * @param looper the looper used to run the action * @param action the action to run @@ -295,15 +300,13 @@ public class TestUtils { /** * Read Bluetooth adapter configuration from the filesystem * - * @return A {@link HashMap} of Bluetooth configs in the format: - * section -> key1 -> value1 - * -> key2 -> value2 - * Assume no empty section name, no duplicate keys in the same section + * @return A {@link HashMap} of Bluetooth configs in the format: section -> key1 -> value1 -> + * key2 -> value2 Assume no empty section name, no duplicate keys in the same section */ public static HashMap> readAdapterConfig() { HashMap> adapterConfig = new HashMap<>(); try (BufferedReader reader = - new BufferedReader(new FileReader("/data/misc/bluedroid/bt_config.conf"))) { + new BufferedReader(new FileReader("/data/misc/bluedroid/bt_config.conf"))) { String section = ""; for (String line; (line = reader.readLine()) != null; ) { line = line.trim(); @@ -319,8 +322,11 @@ public class TestUtils { adapterConfig.put(section, new HashMap<>()); } else { String[] keyValue = line.split("="); - adapterConfig.get(section).put(keyValue[0].trim(), - keyValue.length == 1 ? "" : keyValue[1].trim()); + adapterConfig + .get(section) + .put( + keyValue[0].trim(), + keyValue.length == 1 ? "" : keyValue[1].trim()); } } } catch (IOException e) { @@ -336,15 +342,18 @@ public class TestUtils { * @return intent with the appropriate component & action set. */ public static Intent prepareIntentToStartBluetoothBrowserMediaService() { - final Intent intent = new Intent(InstrumentationRegistry.getTargetContext(), - BluetoothMediaBrowserService.class); + final Intent intent = + new Intent( + InstrumentationRegistry.getTargetContext(), + BluetoothMediaBrowserService.class); intent.setAction(MediaBrowserService.SERVICE_INTERFACE); return intent; } public static void setUpUiTest() throws Exception { - final UiDevice device = UiDevice.getInstance( - androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); + final UiDevice device = + UiDevice.getInstance( + androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); // Disable animation device.executeShellCommand("settings put global window_animation_scale 0.0"); device.executeShellCommand("settings put global transition_animation_scale 0.0"); @@ -364,8 +373,9 @@ public class TestUtils { } public static void tearDownUiTest() throws Exception { - final UiDevice device = UiDevice.getInstance( - androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); + final UiDevice device = + UiDevice.getInstance( + androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); device.executeShellCommand("wm dismiss-keyguard"); // Re-enable animation @@ -374,8 +384,8 @@ public class TestUtils { device.executeShellCommand("settings put global animator_duration_scale 1.0"); // restore screen_off_timeout - device.executeShellCommand("settings put system screen_off_timeout " - + sSystemScreenOffTimeout); + device.executeShellCommand( + "settings put system screen_off_timeout " + sSystemScreenOffTimeout); } public static class RetryTestRule implements TestRule { @@ -420,9 +430,7 @@ public class TestUtils { } } - /** - * Helper class used to run synchronously a runnable action on a looper. - */ + /** Helper class used to run synchronously a runnable action on a looper. */ private static final class SyncRunnable implements Runnable { private final Runnable mTarget; private volatile boolean mComplete = false; diff --git a/android/app/tests/unit/src/com/android/bluetooth/UtilsTest.java b/android/app/tests/unit/src/com/android/bluetooth/UtilsTest.java index b4d73bc5c18..ded05bfd841 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/UtilsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/UtilsTest.java @@ -50,9 +50,7 @@ import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.UUID; -/** - * Test for Utils.java - */ +/** Test for Utils.java */ @SmallTest @RunWith(AndroidJUnit4.class) public class UtilsTest { @@ -72,10 +70,10 @@ public class UtilsTest { @Test public void uuidsToByteArray() { - ParcelUuid[] uuids = new ParcelUuid[] { - new ParcelUuid(new UUID(10, 20)), - new ParcelUuid(new UUID(30, 40)) - }; + ParcelUuid[] uuids = + new ParcelUuid[] { + new ParcelUuid(new UUID(10, 20)), new ParcelUuid(new UUID(30, 40)) + }; ByteBuffer converter = ByteBuffer.allocate(uuids.length * 16); converter.order(ByteOrder.BIG_ENDIAN); converter.putLong(0, 10); @@ -211,8 +209,7 @@ public class UtilsTest { .isEqualTo("STATE_TURNING_ON"); assertThat(Utils.debugGetAdapterStateString(BluetoothAdapter.STATE_TURNING_OFF)) .isEqualTo("STATE_TURNING_OFF"); - assertThat(Utils.debugGetAdapterStateString(-124)) - .isEqualTo("UNKNOWN"); + assertThat(Utils.debugGetAdapterStateString(-124)).isEqualTo("UNKNOWN"); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java index 97cf8e0f865..ebfddc6c49b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java @@ -57,13 +57,14 @@ public class A2dpCodecConfigTest { @Mock private Resources mMockResources; @Mock private A2dpNativeInterface mA2dpNativeInterface; - private static final int[] sOptionalCodecTypes = new int[] { - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS - }; + private static final int[] sOptionalCodecTypes = + new int[] { + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS + }; // Not use the default value to make sure it reads from config private static final int SBC_PRIORITY_DEFAULT = 1001; @@ -75,91 +76,141 @@ public class A2dpCodecConfigTest { private static final int OPUS_PRIORITY_DEFAULT = 13001; private static final int PRIORITY_HIGH = 1000000; - private static final BluetoothCodecConfig[] sCodecCapabilities = new BluetoothCodecConfig[] { - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, - SBC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_44100, - BluetoothCodecConfig.BITS_PER_SAMPLE_16, - BluetoothCodecConfig.CHANNEL_MODE_MONO - | BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, - AAC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_44100, - BluetoothCodecConfig.BITS_PER_SAMPLE_16, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, - APTX_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_44100 - | BluetoothCodecConfig.SAMPLE_RATE_48000, - BluetoothCodecConfig.BITS_PER_SAMPLE_16, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, - APTX_HD_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_44100 - | BluetoothCodecConfig.SAMPLE_RATE_48000, - BluetoothCodecConfig.BITS_PER_SAMPLE_24, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, - LDAC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_44100 - | BluetoothCodecConfig.SAMPLE_RATE_48000 - | BluetoothCodecConfig.SAMPLE_RATE_88200 - | BluetoothCodecConfig.SAMPLE_RATE_96000, - BluetoothCodecConfig.BITS_PER_SAMPLE_16 - | BluetoothCodecConfig.BITS_PER_SAMPLE_24 - | BluetoothCodecConfig.BITS_PER_SAMPLE_32, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, - OPUS_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_48000, - BluetoothCodecConfig.BITS_PER_SAMPLE_16, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0) // Codec-specific fields - }; - - private static final BluetoothCodecConfig[] sDefaultCodecConfigs = new BluetoothCodecConfig[] { - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, - SBC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_44100, - BluetoothCodecConfig.BITS_PER_SAMPLE_16, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, - AAC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_44100, - BluetoothCodecConfig.BITS_PER_SAMPLE_16, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, - APTX_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_48000, - BluetoothCodecConfig.BITS_PER_SAMPLE_16, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, - APTX_HD_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_48000, - BluetoothCodecConfig.BITS_PER_SAMPLE_24, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, - LDAC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_96000, - BluetoothCodecConfig.BITS_PER_SAMPLE_32, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0), // Codec-specific fields - buildBluetoothCodecConfig(BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, - OPUS_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_48000, - BluetoothCodecConfig.BITS_PER_SAMPLE_16, - BluetoothCodecConfig.CHANNEL_MODE_STEREO, - 0, 0, 0, 0) // Codec-specific fields - }; + private static final BluetoothCodecConfig[] sCodecCapabilities = + new BluetoothCodecConfig[] { + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + SBC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_44100, + BluetoothCodecConfig.BITS_PER_SAMPLE_16, + BluetoothCodecConfig.CHANNEL_MODE_MONO + | BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + AAC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_44100, + BluetoothCodecConfig.BITS_PER_SAMPLE_16, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, + APTX_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_44100 + | BluetoothCodecConfig.SAMPLE_RATE_48000, + BluetoothCodecConfig.BITS_PER_SAMPLE_16, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, + APTX_HD_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_44100 + | BluetoothCodecConfig.SAMPLE_RATE_48000, + BluetoothCodecConfig.BITS_PER_SAMPLE_24, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, + LDAC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_44100 + | BluetoothCodecConfig.SAMPLE_RATE_48000 + | BluetoothCodecConfig.SAMPLE_RATE_88200 + | BluetoothCodecConfig.SAMPLE_RATE_96000, + BluetoothCodecConfig.BITS_PER_SAMPLE_16 + | BluetoothCodecConfig.BITS_PER_SAMPLE_24 + | BluetoothCodecConfig.BITS_PER_SAMPLE_32, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_48000, + BluetoothCodecConfig.BITS_PER_SAMPLE_16, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0) // Codec-specific fields + }; + + private static final BluetoothCodecConfig[] sDefaultCodecConfigs = + new BluetoothCodecConfig[] { + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + SBC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_44100, + BluetoothCodecConfig.BITS_PER_SAMPLE_16, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + AAC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_44100, + BluetoothCodecConfig.BITS_PER_SAMPLE_16, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, + APTX_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_48000, + BluetoothCodecConfig.BITS_PER_SAMPLE_16, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, + APTX_HD_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_48000, + BluetoothCodecConfig.BITS_PER_SAMPLE_24, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, + LDAC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_96000, + BluetoothCodecConfig.BITS_PER_SAMPLE_32, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0), // Codec-specific fields + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_48000, + BluetoothCodecConfig.BITS_PER_SAMPLE_16, + BluetoothCodecConfig.CHANNEL_MODE_STEREO, + 0, + 0, + 0, + 0) // Codec-specific fields + }; @Before public void setUp() throws Exception { @@ -182,20 +233,20 @@ public class A2dpCodecConfigTest { mA2dpCodecConfig = new A2dpCodecConfig(mMockContext, mA2dpNativeInterface); mTestDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:01:02:03:04:05"); - doReturn(true).when(mA2dpNativeInterface).setCodecConfigPreference( - any(BluetoothDevice.class), - any(BluetoothCodecConfig[].class)); + doReturn(true) + .when(mA2dpNativeInterface) + .setCodecConfigPreference( + any(BluetoothDevice.class), any(BluetoothCodecConfig[].class)); } @After - public void tearDown() throws Exception { - } + public void tearDown() throws Exception {} @Test public void testAssignCodecConfigPriorities() { BluetoothCodecConfig[] codecConfigs = mA2dpCodecConfig.codecConfigPriorities(); for (BluetoothCodecConfig config : codecConfigs) { - switch(config.getCodecType()) { + switch (config.getCodecType()) { case BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC: Assert.assertEquals(config.getCodecPriority(), SBC_PRIORITY_DEFAULT); break; @@ -218,122 +269,168 @@ public class A2dpCodecConfigTest { } } - /** - * Test that we can fallback to default codec by lower the codec priority we changed before. - */ + /** Test that we can fallback to default codec by lower the codec priority we changed before. */ @Test public void testSetCodecPreference_priorityHighToDefault() { testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, SBC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + SBC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, AAC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + AAC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, APTX_PRIORITY_DEFAULT, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, + APTX_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, APTX_HD_PRIORITY_DEFAULT, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, + APTX_HD_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, LDAC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, + LDAC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, OPUS_PRIORITY_DEFAULT, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + PRIORITY_HIGH, false); } /** - * Test that we can change the default codec to another by raising the codec priority. - * LDAC is the default highest codec, so no need to test others. + * Test that we can change the default codec to another by raising the codec priority. LDAC is + * the default highest codec, so no need to test others. */ @Test public void testSetCodecPreference_priorityDefaultToRaiseHigh() { testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, OPUS_PRIORITY_DEFAULT, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + OPUS_PRIORITY_DEFAULT, false); } @Test public void testSetCodecPreference_prioritySbcHighToOthersHigh() { testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, false); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, true); } @Test public void testSetCodecPreference_priorityAacHighToOthersHigh() { testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, false); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, true); testCodecPriorityChangeHelper( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, PRIORITY_HIGH, - BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS, + PRIORITY_HIGH, + BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC, + PRIORITY_HIGH, true); } @@ -608,15 +705,18 @@ public class A2dpCodecConfigTest { @Test public void testDisableOptionalCodecs() { - BluetoothCodecConfig[] codecConfigsArray = - new BluetoothCodecConfig[6]; - codecConfigsArray[0] = buildBluetoothCodecConfig( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, - BluetoothCodecConfig.CODEC_PRIORITY_HIGHEST, - BluetoothCodecConfig.SAMPLE_RATE_NONE, - BluetoothCodecConfig.BITS_PER_SAMPLE_NONE, - BluetoothCodecConfig.CHANNEL_MODE_NONE, - 0, 0, 0, 0); // Codec-specific fields + BluetoothCodecConfig[] codecConfigsArray = new BluetoothCodecConfig[6]; + codecConfigsArray[0] = + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + BluetoothCodecConfig.CODEC_PRIORITY_HIGHEST, + BluetoothCodecConfig.SAMPLE_RATE_NONE, + BluetoothCodecConfig.BITS_PER_SAMPLE_NONE, + BluetoothCodecConfig.CHANNEL_MODE_NONE, + 0, + 0, + 0, + 0); // Codec-specific fields // shouldn't invoke to native when current codec is SBC mA2dpCodecConfig.disableOptionalCodecs( @@ -624,16 +724,16 @@ public class A2dpCodecConfigTest { getDefaultCodecConfigByType( BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT)); - verify(mA2dpNativeInterface, times(0)).setCodecConfigPreference(mTestDevice, - codecConfigsArray); + verify(mA2dpNativeInterface, times(0)) + .setCodecConfigPreference(mTestDevice, codecConfigsArray); // should invoke to native when current codec is an optional codec int invokedCounter = 0; for (int codecType : sOptionalCodecTypes) { mA2dpCodecConfig.disableOptionalCodecs( mTestDevice, - getDefaultCodecConfigByType(codecType, - BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT)); + getDefaultCodecConfigByType( + codecType, BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT)); verify(mA2dpNativeInterface, times(++invokedCounter)) .setCodecConfigPreference(mTestDevice, codecConfigsArray); } @@ -641,21 +741,25 @@ public class A2dpCodecConfigTest { @Test public void testEnableOptionalCodecs() { - BluetoothCodecConfig[] codecConfigsArray = - new BluetoothCodecConfig[6]; - codecConfigsArray[0] = buildBluetoothCodecConfig( - BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, - SBC_PRIORITY_DEFAULT, - BluetoothCodecConfig.SAMPLE_RATE_NONE, - BluetoothCodecConfig.BITS_PER_SAMPLE_NONE, - BluetoothCodecConfig.CHANNEL_MODE_NONE, - 0, 0, 0, 0); // Codec-specific fields + BluetoothCodecConfig[] codecConfigsArray = new BluetoothCodecConfig[6]; + codecConfigsArray[0] = + buildBluetoothCodecConfig( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + SBC_PRIORITY_DEFAULT, + BluetoothCodecConfig.SAMPLE_RATE_NONE, + BluetoothCodecConfig.BITS_PER_SAMPLE_NONE, + BluetoothCodecConfig.CHANNEL_MODE_NONE, + 0, + 0, + 0, + 0); // Codec-specific fields // should invoke to native when current codec is SBC mA2dpCodecConfig.enableOptionalCodecs( mTestDevice, - getDefaultCodecConfigByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, - BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT)); + getDefaultCodecConfigByType( + BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC, + BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT)); verify(mA2dpNativeInterface, times(1)) .setCodecConfigPreference(mTestDevice, codecConfigsArray); @@ -663,8 +767,8 @@ public class A2dpCodecConfigTest { for (int codecType : sOptionalCodecTypes) { mA2dpCodecConfig.enableOptionalCodecs( mTestDevice, - getDefaultCodecConfigByType(codecType, - BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT)); + getDefaultCodecConfigByType( + codecType, BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT)); verify(mA2dpNativeInterface, times(1)) .setCodecConfigPreference(mTestDevice, codecConfigsArray); } @@ -678,14 +782,20 @@ public class A2dpCodecConfigTest { return buildBluetoothCodecConfig( codecConfig.getCodecType(), (codecPriority != BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT - ? codecPriority : codecConfig.getCodecPriority()), - codecConfig.getSampleRate(), codecConfig.getBitsPerSample(), - codecConfig.getChannelMode(), codecConfig.getCodecSpecific1(), - codecConfig.getCodecSpecific2(), codecConfig.getCodecSpecific3(), + ? codecPriority + : codecConfig.getCodecPriority()), + codecConfig.getSampleRate(), + codecConfig.getBitsPerSample(), + codecConfig.getChannelMode(), + codecConfig.getCodecSpecific1(), + codecConfig.getCodecSpecific2(), + codecConfig.getCodecSpecific3(), codecConfig.getCodecSpecific4()); } - Assert.fail("getDefaultCodecConfigByType: No such codecType=" + codecType - + " in sDefaultCodecConfigs"); + Assert.fail( + "getDefaultCodecConfigByType: No such codecType=" + + codecType + + " in sDefaultCodecConfigs"); return null; } @@ -695,135 +805,177 @@ public class A2dpCodecConfigTest { continue; } return buildBluetoothCodecConfig( - codecCapabilities.getCodecType(), codecCapabilities.getCodecPriority(), - codecCapabilities.getSampleRate(), codecCapabilities.getBitsPerSample(), - codecCapabilities.getChannelMode(), codecCapabilities.getCodecSpecific1(), - codecCapabilities.getCodecSpecific2(), codecCapabilities.getCodecSpecific3(), + codecCapabilities.getCodecType(), + codecCapabilities.getCodecPriority(), + codecCapabilities.getSampleRate(), + codecCapabilities.getBitsPerSample(), + codecCapabilities.getChannelMode(), + codecCapabilities.getCodecSpecific1(), + codecCapabilities.getCodecSpecific2(), + codecCapabilities.getCodecSpecific3(), codecCapabilities.getCodecSpecific4()); } - Assert.fail("getCodecCapabilitiesByType: No such codecType=" + codecType - + " in sCodecCapabilities"); + Assert.fail( + "getCodecCapabilitiesByType: No such codecType=" + + codecType + + " in sCodecCapabilities"); return null; } - private void testCodecParametersChangeHelper(int newCodecType, int oldCodecType, - int sampleRate, int bitsPerSample, int channelMode, boolean invokeNative) { + private void testCodecParametersChangeHelper( + int newCodecType, + int oldCodecType, + int sampleRate, + int bitsPerSample, + int channelMode, + boolean invokeNative) { BluetoothCodecConfig oldCodecConfig = getDefaultCodecConfigByType(oldCodecType, PRIORITY_HIGH); - BluetoothCodecConfig[] newCodecConfigsArray = new BluetoothCodecConfig[] { - buildBluetoothCodecConfig(newCodecType, - PRIORITY_HIGH, - sampleRate, bitsPerSample, channelMode, - 0, 0, 0, 0) // Codec-specific fields - }; + BluetoothCodecConfig[] newCodecConfigsArray = + new BluetoothCodecConfig[] { + buildBluetoothCodecConfig( + newCodecType, + PRIORITY_HIGH, + sampleRate, + bitsPerSample, + channelMode, + 0, + 0, + 0, + 0) // Codec-specific fields + }; // Test cases: 1. no mandatory; 2. mandatory + old + new; 3. all codecs BluetoothCodecConfig[] minimumCodecsArray; if (!oldCodecConfig.isMandatoryCodec() && !newCodecConfigsArray[0].isMandatoryCodec()) { BluetoothCodecConfig[] optionalCodecsArray; if (oldCodecType != newCodecType) { - optionalCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(oldCodecType), - getCodecCapabilitiesByType(newCodecType) - }; - minimumCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), - getCodecCapabilitiesByType(oldCodecType), - getCodecCapabilitiesByType(newCodecType) - }; + optionalCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(oldCodecType), + getCodecCapabilitiesByType(newCodecType) + }; + minimumCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), + getCodecCapabilitiesByType(oldCodecType), + getCodecCapabilitiesByType(newCodecType) + }; } else { - optionalCodecsArray = new BluetoothCodecConfig[] - {getCodecCapabilitiesByType(oldCodecType)}; - minimumCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), - getCodecCapabilitiesByType(oldCodecType) - }; + optionalCodecsArray = + new BluetoothCodecConfig[] {getCodecCapabilitiesByType(oldCodecType)}; + minimumCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), + getCodecCapabilitiesByType(oldCodecType) + }; } - BluetoothCodecStatus codecStatus = new BluetoothCodecStatus(oldCodecConfig, - Arrays.asList(sCodecCapabilities), - Arrays.asList(optionalCodecsArray)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + BluetoothCodecStatus codecStatus = + new BluetoothCodecStatus( + oldCodecConfig, + Arrays.asList(sCodecCapabilities), + Arrays.asList(optionalCodecsArray)); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); // no mandatory codec in selectable, and should not apply - verify(mA2dpNativeInterface, times(0)).setCodecConfigPreference(mTestDevice, - newCodecConfigsArray); - + verify(mA2dpNativeInterface, times(0)) + .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); } else { if (oldCodecType != newCodecType) { - minimumCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(oldCodecType), - getCodecCapabilitiesByType(newCodecType) - }; + minimumCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(oldCodecType), + getCodecCapabilitiesByType(newCodecType) + }; } else { - minimumCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(oldCodecType), - }; + minimumCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(oldCodecType), + }; } } // 2. mandatory + old + new codecs only BluetoothCodecStatus codecStatus = - new BluetoothCodecStatus(oldCodecConfig, + new BluetoothCodecStatus( + oldCodecConfig, Arrays.asList(sCodecCapabilities), Arrays.asList(minimumCodecsArray)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); verify(mA2dpNativeInterface, times(invokeNative ? 1 : 0)) .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); // 3. all codecs were selectable - codecStatus = new BluetoothCodecStatus(oldCodecConfig, + codecStatus = + new BluetoothCodecStatus( + oldCodecConfig, Arrays.asList(sCodecCapabilities), Arrays.asList(sCodecCapabilities)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); verify(mA2dpNativeInterface, times(invokeNative ? 2 : 0)) .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); } - private void testCodecSpecificParametersChangeHelper(int newCodecType, int newCodecSpecific, - int oldCodecType, int oldCodecSpecific, boolean invokeNative) { + private void testCodecSpecificParametersChangeHelper( + int newCodecType, + int newCodecSpecific, + int oldCodecType, + int oldCodecSpecific, + boolean invokeNative) { BluetoothCodecConfig codecDefaultTemp = getDefaultCodecConfigByType(oldCodecType, PRIORITY_HIGH); BluetoothCodecConfig oldCodecConfig = - buildBluetoothCodecConfig(codecDefaultTemp.getCodecType(), - codecDefaultTemp.getCodecPriority(), - codecDefaultTemp.getSampleRate(), - codecDefaultTemp.getBitsPerSample(), - codecDefaultTemp.getChannelMode(), - oldCodecSpecific, 0, 0, 0); // Codec-specific fields + buildBluetoothCodecConfig( + codecDefaultTemp.getCodecType(), + codecDefaultTemp.getCodecPriority(), + codecDefaultTemp.getSampleRate(), + codecDefaultTemp.getBitsPerSample(), + codecDefaultTemp.getChannelMode(), + oldCodecSpecific, + 0, + 0, + 0); // Codec-specific fields codecDefaultTemp = getDefaultCodecConfigByType(newCodecType, PRIORITY_HIGH); - BluetoothCodecConfig[] newCodecConfigsArray = new BluetoothCodecConfig[] { - buildBluetoothCodecConfig(codecDefaultTemp.getCodecType(), - codecDefaultTemp.getCodecPriority(), - codecDefaultTemp.getSampleRate(), - codecDefaultTemp.getBitsPerSample(), - codecDefaultTemp.getChannelMode(), - newCodecSpecific, 0, 0, 0) // Codec-specific fields - }; - BluetoothCodecStatus codecStatus = new BluetoothCodecStatus(oldCodecConfig, + BluetoothCodecConfig[] newCodecConfigsArray = + new BluetoothCodecConfig[] { + buildBluetoothCodecConfig( + codecDefaultTemp.getCodecType(), + codecDefaultTemp.getCodecPriority(), + codecDefaultTemp.getSampleRate(), + codecDefaultTemp.getBitsPerSample(), + codecDefaultTemp.getChannelMode(), + newCodecSpecific, + 0, + 0, + 0) // Codec-specific fields + }; + BluetoothCodecStatus codecStatus = + new BluetoothCodecStatus( + oldCodecConfig, Arrays.asList(sCodecCapabilities), Arrays.asList(sCodecCapabilities)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); verify(mA2dpNativeInterface, times(invokeNative ? 1 : 0)) .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); } - private void testCodecPriorityChangeHelper(int newCodecType, int newCodecPriority, - int oldCodecType, int oldCodecPriority, boolean shouldApplyWhenAllSelectable) { + private void testCodecPriorityChangeHelper( + int newCodecType, + int newCodecPriority, + int oldCodecType, + int oldCodecPriority, + boolean shouldApplyWhenAllSelectable) { BluetoothCodecConfig[] newCodecConfigsArray = new BluetoothCodecConfig[] { - getDefaultCodecConfigByType(newCodecType, newCodecPriority) + getDefaultCodecConfigByType(newCodecType, newCodecPriority) }; - BluetoothCodecConfig oldCodecConfig = getDefaultCodecConfigByType(oldCodecType, - oldCodecPriority); + BluetoothCodecConfig oldCodecConfig = + getDefaultCodecConfigByType(oldCodecType, oldCodecPriority); // Test cases: 1. no mandatory; 2. no new codec; 3. mandatory + old + new; 4. all codecs BluetoothCodecConfig[] minimumCodecsArray; @@ -832,30 +984,35 @@ public class A2dpCodecConfigTest { if (oldCodecType == newCodecType || newCodecConfigsArray[0].isMandatoryCodec()) { // selectable: {-mandatory, +oldCodec = newCodec}, or // selectable: {-mandatory = newCodec, +oldCodec}. Not applied - BluetoothCodecConfig[] poorCodecsArray = new BluetoothCodecConfig[] - {getCodecCapabilitiesByType(oldCodecType)}; - BluetoothCodecStatus codecStatus = new BluetoothCodecStatus(oldCodecConfig, + BluetoothCodecConfig[] poorCodecsArray = + new BluetoothCodecConfig[] {getCodecCapabilitiesByType(oldCodecType)}; + BluetoothCodecStatus codecStatus = + new BluetoothCodecStatus( + oldCodecConfig, Arrays.asList(sCodecCapabilities), Arrays.asList(poorCodecsArray)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); verify(mA2dpNativeInterface, times(0)) .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); // selectable: {+mandatory, +oldCodec = newCodec}, or // selectable: {+mandatory = newCodec, +oldCodec}. - minimumCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), - getCodecCapabilitiesByType(oldCodecType) - }; + minimumCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), + getCodecCapabilitiesByType(oldCodecType) + }; } else { // selectable: {-mandatory, +oldCodec, +newCodec}. Not applied - BluetoothCodecConfig[] poorCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(oldCodecType), - getCodecCapabilitiesByType(newCodecType) - }; - BluetoothCodecStatus codecStatus = new BluetoothCodecStatus(oldCodecConfig, + BluetoothCodecConfig[] poorCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(oldCodecType), + getCodecCapabilitiesByType(newCodecType) + }; + BluetoothCodecStatus codecStatus = + new BluetoothCodecStatus( + oldCodecConfig, Arrays.asList(sCodecCapabilities), Arrays.asList(poorCodecsArray)); mA2dpCodecConfig.setCodecConfigPreference( @@ -864,31 +1021,35 @@ public class A2dpCodecConfigTest { .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); // selectable: {+mandatory, +oldCodec, -newCodec}. Not applied - poorCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), - getCodecCapabilitiesByType(oldCodecType) - }; - codecStatus = new BluetoothCodecStatus(oldCodecConfig, + poorCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), + getCodecCapabilitiesByType(oldCodecType) + }; + codecStatus = + new BluetoothCodecStatus( + oldCodecConfig, Arrays.asList(sCodecCapabilities), Arrays.asList(poorCodecsArray)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); verify(mA2dpNativeInterface, times(0)) .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); // selectable: {+mandatory, +oldCodec, +newCodec}. - minimumCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), - getCodecCapabilitiesByType(oldCodecType), - getCodecCapabilitiesByType(newCodecType) - }; + minimumCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC), + getCodecCapabilitiesByType(oldCodecType), + getCodecCapabilitiesByType(newCodecType) + }; } // oldCodec priority should be reset to default, so compare with the default if (newCodecConfigsArray[0].getCodecPriority() - > getDefaultCodecConfigByType( - oldCodecType, - BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT).getCodecPriority() + > getDefaultCodecConfigByType( + oldCodecType, + BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT) + .getCodecPriority() && oldCodecType != newCodecType) { isMinimumCodecsArraySelectable = true; } else { @@ -897,68 +1058,79 @@ public class A2dpCodecConfigTest { } } else if (oldCodecType != newCodecType) { // selectable: {+mandatory = oldCodec, -newCodec}. Not applied - BluetoothCodecConfig[] poorCodecsArray = new BluetoothCodecConfig[] - {getCodecCapabilitiesByType(oldCodecType)}; + BluetoothCodecConfig[] poorCodecsArray = + new BluetoothCodecConfig[] {getCodecCapabilitiesByType(oldCodecType)}; BluetoothCodecStatus codecStatus = - new BluetoothCodecStatus(oldCodecConfig, - Arrays.asList(sCodecCapabilities), - Arrays.asList(poorCodecsArray)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + new BluetoothCodecStatus( + oldCodecConfig, + Arrays.asList(sCodecCapabilities), + Arrays.asList(poorCodecsArray)); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); verify(mA2dpNativeInterface, times(0)) .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); // selectable: {+mandatory = oldCodec, +newCodec}. - minimumCodecsArray = new BluetoothCodecConfig[] { - getCodecCapabilitiesByType(oldCodecType), - getCodecCapabilitiesByType(newCodecType) - }; + minimumCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(oldCodecType), + getCodecCapabilitiesByType(newCodecType) + }; isMinimumCodecsArraySelectable = true; } else { // selectable: {mandatory = oldCodec = newCodec}. - minimumCodecsArray = new BluetoothCodecConfig[] - {getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC)}; + minimumCodecsArray = + new BluetoothCodecConfig[] { + getCodecCapabilitiesByType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC) + }; isMinimumCodecsArraySelectable = false; } // 3. mandatory + old + new codecs only int invokedCounter = (isMinimumCodecsArraySelectable ? 1 : 0); BluetoothCodecStatus codecStatus = - new BluetoothCodecStatus(oldCodecConfig, + new BluetoothCodecStatus( + oldCodecConfig, Arrays.asList(sCodecCapabilities), Arrays.asList(minimumCodecsArray)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); verify(mA2dpNativeInterface, times(invokedCounter)) .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); // 4. all codecs were selectable invokedCounter += (shouldApplyWhenAllSelectable ? 1 : 0); - codecStatus = new BluetoothCodecStatus(oldCodecConfig, - Arrays.asList(sCodecCapabilities), - Arrays.asList(sCodecCapabilities)); - mA2dpCodecConfig.setCodecConfigPreference(mTestDevice, - codecStatus, - newCodecConfigsArray[0]); + codecStatus = + new BluetoothCodecStatus( + oldCodecConfig, + Arrays.asList(sCodecCapabilities), + Arrays.asList(sCodecCapabilities)); + mA2dpCodecConfig.setCodecConfigPreference( + mTestDevice, codecStatus, newCodecConfigsArray[0]); verify(mA2dpNativeInterface, times(invokedCounter)) .setCodecConfigPreference(mTestDevice, newCodecConfigsArray); } - private static BluetoothCodecConfig buildBluetoothCodecConfig(int sourceCodecType, - int codecPriority, int sampleRate, int bitsPerSample, int channelMode, - long codecSpecific1, long codecSpecific2, long codecSpecific3, long codecSpecific4) { + private static BluetoothCodecConfig buildBluetoothCodecConfig( + int sourceCodecType, + int codecPriority, + int sampleRate, + int bitsPerSample, + int channelMode, + long codecSpecific1, + long codecSpecific2, + long codecSpecific3, + long codecSpecific4) { return new BluetoothCodecConfig.Builder() - .setCodecType(sourceCodecType) - .setCodecPriority(codecPriority) - .setSampleRate(sampleRate) - .setBitsPerSample(bitsPerSample) - .setChannelMode(channelMode) - .setCodecSpecific1(codecSpecific1) - .setCodecSpecific2(codecSpecific2) - .setCodecSpecific3(codecSpecific3) - .setCodecSpecific4(codecSpecific4) - .build(); + .setCodecType(sourceCodecType) + .setCodecPriority(codecPriority) + .setSampleRate(sampleRate) + .setBitsPerSample(bitsPerSample) + .setChannelMode(channelMode) + .setCodecSpecific1(codecSpecific1) + .setCodecSpecific2(codecSpecific2) + .setCodecSpecific3(codecSpecific3) + .setCodecSpecific4(codecSpecific4) + .build(); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java index 054de5c9fba..2f1713ef3c2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java @@ -101,7 +101,7 @@ public class A2dpServiceBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED }; + int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, sSource); verify(mA2dpService).getDevicesMatchingConnectionStates(states); diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java index 56283ce1a22..32a30906ffd 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java @@ -60,7 +60,7 @@ public class A2dpStateMachineTest { private HandlerThread mHandlerThread; private A2dpStateMachine mA2dpStateMachine; private BluetoothDevice mTestDevice; - private static final int TIMEOUT_MS = 1000; // 1s + private static final int TIMEOUT_MS = 1000; // 1s private BluetoothCodecConfig mCodecConfigSbc; private BluetoothCodecConfig mCodecConfigAac; @@ -88,48 +88,55 @@ public class A2dpStateMachineTest { mTestDevice = mAdapter.getRemoteDevice("00:01:02:03:04:05"); // Set up sample codec config - mCodecConfigSbc = new BluetoothCodecConfig.Builder() - .setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC) - .setCodecPriority(BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT) - .setSampleRate(BluetoothCodecConfig.SAMPLE_RATE_44100) - .setBitsPerSample(BluetoothCodecConfig.BITS_PER_SAMPLE_16) - .setChannelMode(BluetoothCodecConfig.CHANNEL_MODE_STEREO) - .setCodecSpecific1(0) - .setCodecSpecific2(0) - .setCodecSpecific3(0) - .setCodecSpecific4(0) - .build(); - mCodecConfigAac = new BluetoothCodecConfig.Builder() - .setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC) - .setCodecPriority(BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT) - .setSampleRate(BluetoothCodecConfig.SAMPLE_RATE_48000) - .setBitsPerSample(BluetoothCodecConfig.BITS_PER_SAMPLE_16) - .setChannelMode(BluetoothCodecConfig.CHANNEL_MODE_STEREO) - .setCodecSpecific1(0) - .setCodecSpecific2(0) - .setCodecSpecific3(0) - .setCodecSpecific4(0) - .build(); - - mCodecConfigOpus = new BluetoothCodecConfig.Builder() - .setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS) - .setCodecPriority(BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT) - .setSampleRate(BluetoothCodecConfig.SAMPLE_RATE_48000) - .setBitsPerSample(BluetoothCodecConfig.BITS_PER_SAMPLE_16) - .setChannelMode(BluetoothCodecConfig.CHANNEL_MODE_STEREO) - .setCodecSpecific1(0) - .setCodecSpecific2(0) - .setCodecSpecific3(0) - .setCodecSpecific4(0) - .build(); + mCodecConfigSbc = + new BluetoothCodecConfig.Builder() + .setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC) + .setCodecPriority(BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT) + .setSampleRate(BluetoothCodecConfig.SAMPLE_RATE_44100) + .setBitsPerSample(BluetoothCodecConfig.BITS_PER_SAMPLE_16) + .setChannelMode(BluetoothCodecConfig.CHANNEL_MODE_STEREO) + .setCodecSpecific1(0) + .setCodecSpecific2(0) + .setCodecSpecific3(0) + .setCodecSpecific4(0) + .build(); + mCodecConfigAac = + new BluetoothCodecConfig.Builder() + .setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC) + .setCodecPriority(BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT) + .setSampleRate(BluetoothCodecConfig.SAMPLE_RATE_48000) + .setBitsPerSample(BluetoothCodecConfig.BITS_PER_SAMPLE_16) + .setChannelMode(BluetoothCodecConfig.CHANNEL_MODE_STEREO) + .setCodecSpecific1(0) + .setCodecSpecific2(0) + .setCodecSpecific3(0) + .setCodecSpecific4(0) + .build(); + + mCodecConfigOpus = + new BluetoothCodecConfig.Builder() + .setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS) + .setCodecPriority(BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT) + .setSampleRate(BluetoothCodecConfig.SAMPLE_RATE_48000) + .setBitsPerSample(BluetoothCodecConfig.BITS_PER_SAMPLE_16) + .setChannelMode(BluetoothCodecConfig.CHANNEL_MODE_STEREO) + .setCodecSpecific1(0) + .setCodecSpecific2(0) + .setCodecSpecific3(0) + .setCodecSpecific4(0) + .build(); // Set up thread and looper mHandlerThread = new HandlerThread("A2dpStateMachineTestHandlerThread"); mHandlerThread.start(); - mA2dpStateMachine = new A2dpStateMachine(mTestDevice, mA2dpService, - mA2dpNativeInterface, mHandlerThread.getLooper()); + mA2dpStateMachine = + new A2dpStateMachine( + mTestDevice, + mA2dpService, + mA2dpNativeInterface, + mHandlerThread.getLooper()); // Override the timeout value to speed up the test - A2dpStateMachine.sConnectTimeoutMs = 1000; // 1s + A2dpStateMachine.sConnectTimeoutMs = 1000; // 1s mA2dpStateMachine.start(); } @@ -141,9 +148,7 @@ public class A2dpStateMachineTest { TestUtils.clearAdapterService(mAdapterService); } - /** - * Test that default state is disconnected - */ + /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { assertThat(mA2dpStateMachine.getConnectionState()) @@ -156,13 +161,10 @@ public class A2dpStateMachineTest { * @param allow if true, connection is allowed */ private void allowConnection(boolean allow) { - doReturn(allow).when(mA2dpService).okToConnect(any(BluetoothDevice.class), - anyBoolean()); + doReturn(allow).when(mA2dpService).okToConnect(any(BluetoothDevice.class), anyBoolean()); } - /** - * Test that an incoming connection with low priority is rejected - */ + /** Test that an incoming connection with low priority is rejected */ @Test public void testIncomingPriorityReject() { allowConnection(false); @@ -175,16 +177,14 @@ public class A2dpStateMachineTest { mA2dpStateMachine.sendMessage(A2dpStateMachine.STACK_EVENT, connStCh); // Verify that no connection state broadcast is executed - verify(mA2dpService, after(TIMEOUT_MS).never()).sendBroadcast(any(Intent.class), - anyString(), any(Bundle.class)); + verify(mA2dpService, after(TIMEOUT_MS).never()) + .sendBroadcast(any(Intent.class), anyString(), any(Bundle.class)); // Check that we are in Disconnected state assertThat(mA2dpStateMachine.getCurrentState()) .isInstanceOf(A2dpStateMachine.Disconnected.class); } - /** - * Test that an incoming connection with high priority is accepted - */ + /** Test that an incoming connection with high priority is accepted */ @Test public void testIncomingPriorityAccept() { allowConnection(true); @@ -198,8 +198,8 @@ public class A2dpStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mA2dpService, timeout(TIMEOUT_MS).times(1)).sendBroadcast(intentArgument1.capture(), - anyString(), any(Bundle.class)); + verify(mA2dpService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString(), any(Bundle.class)); assertThat(intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) .isEqualTo(BluetoothProfile.STATE_CONNECTING); @@ -218,8 +218,8 @@ public class A2dpStateMachineTest { // - two calls to broadcastConnectionState(): Disconnected -> Connecting -> Connected // - one call to broadcastAudioState() when entering Connected state ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mA2dpService, timeout(TIMEOUT_MS).times(3)).sendBroadcast(intentArgument2.capture(), - anyString(), any(Bundle.class)); + verify(mA2dpService, timeout(TIMEOUT_MS).times(3)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); // Verify that the last broadcast was to change the A2DP playing state // to STATE_NOT_PLAYING assertThat(intentArgument2.getValue().getAction()) @@ -231,9 +231,7 @@ public class A2dpStateMachineTest { .isInstanceOf(A2dpStateMachine.Connected.class); } - /** - * Test that an outgoing connection times out - */ + /** Test that an outgoing connection times out */ @Test public void testOutgoingTimeout() { allowConnection(true); @@ -245,8 +243,8 @@ public class A2dpStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mA2dpService, timeout(TIMEOUT_MS).times(1)).sendBroadcast(intentArgument1.capture(), - anyString(), any(Bundle.class)); + verify(mA2dpService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString(), any(Bundle.class)); assertThat(intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) .isEqualTo(BluetoothProfile.STATE_CONNECTING); @@ -256,9 +254,8 @@ public class A2dpStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mA2dpService, timeout(A2dpStateMachine.sConnectTimeoutMs * 2).times( - 2)).sendBroadcast(intentArgument2.capture(), anyString(), - any(Bundle.class)); + verify(mA2dpService, timeout(A2dpStateMachine.sConnectTimeoutMs * 2).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); assertThat(intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); @@ -267,9 +264,7 @@ public class A2dpStateMachineTest { .isInstanceOf(A2dpStateMachine.Disconnected.class); } - /** - * Test that an incoming connection times out - */ + /** Test that an incoming connection times out */ @Test public void testIncomingTimeout() { allowConnection(true); @@ -285,8 +280,8 @@ public class A2dpStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mA2dpService, timeout(TIMEOUT_MS).times(1)).sendBroadcast(intentArgument1.capture(), - anyString(), any(Bundle.class)); + verify(mA2dpService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString(), any(Bundle.class)); assertThat(intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) .isEqualTo(BluetoothProfile.STATE_CONNECTING); @@ -296,9 +291,8 @@ public class A2dpStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mA2dpService, timeout(A2dpStateMachine.sConnectTimeoutMs * 2).times( - 2)).sendBroadcast(intentArgument2.capture(), anyString(), - any(Bundle.class)); + verify(mA2dpService, timeout(A2dpStateMachine.sConnectTimeoutMs * 2).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); assertThat(intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); @@ -307,33 +301,31 @@ public class A2dpStateMachineTest { .isInstanceOf(A2dpStateMachine.Disconnected.class); } - /** - * Test that codec config change been reported to A2dpService properly. - */ + /** Test that codec config change been reported to A2dpService properly. */ @Test public void testProcessCodecConfigEvent() { testProcessCodecConfigEventCase(false); } /** - * Test that codec config change been reported to A2dpService properly when - * A2DP hardware offloading is enabled. + * Test that codec config change been reported to A2dpService properly when A2DP hardware + * offloading is enabled. */ @Test public void testProcessCodecConfigEvent_OffloadEnabled() { testProcessCodecConfigEventCase(true); } - /** - * Helper methold to test processCodecConfigEvent() - */ + /** Helper methold to test processCodecConfigEvent() */ public void testProcessCodecConfigEventCase(boolean offloadEnabled) { if (offloadEnabled) { mA2dpStateMachine.mA2dpOffloadEnabled = true; } - doNothing().when(mA2dpService).codecConfigUpdated(any(BluetoothDevice.class), - any(BluetoothCodecStatus.class), anyBoolean()); + doNothing() + .when(mA2dpService) + .codecConfigUpdated( + any(BluetoothDevice.class), any(BluetoothCodecStatus.class), anyBoolean()); doNothing().when(mA2dpService).updateOptionalCodecsSupport(any(BluetoothDevice.class)); allowConnection(true); @@ -352,15 +344,26 @@ public class A2dpStateMachineTest { codecsSelectableSbcAacOpus[1] = mCodecConfigAac; codecsSelectableSbcAacOpus[2] = mCodecConfigOpus; - BluetoothCodecStatus codecStatusSbcAndSbc = new BluetoothCodecStatus(mCodecConfigSbc, - Arrays.asList(codecsSelectableSbcAac), Arrays.asList(codecsSelectableSbc)); - BluetoothCodecStatus codecStatusSbcAndSbcAac = new BluetoothCodecStatus(mCodecConfigSbc, - Arrays.asList(codecsSelectableSbcAac), Arrays.asList(codecsSelectableSbcAac)); - BluetoothCodecStatus codecStatusAacAndSbcAac = new BluetoothCodecStatus(mCodecConfigAac, - Arrays.asList(codecsSelectableSbcAac), Arrays.asList(codecsSelectableSbcAac)); - BluetoothCodecStatus codecStatusOpusAndSbcAacOpus = new BluetoothCodecStatus( - mCodecConfigOpus, Arrays.asList(codecsSelectableSbcAacOpus), - Arrays.asList(codecsSelectableSbcAacOpus)); + BluetoothCodecStatus codecStatusSbcAndSbc = + new BluetoothCodecStatus( + mCodecConfigSbc, + Arrays.asList(codecsSelectableSbcAac), + Arrays.asList(codecsSelectableSbc)); + BluetoothCodecStatus codecStatusSbcAndSbcAac = + new BluetoothCodecStatus( + mCodecConfigSbc, + Arrays.asList(codecsSelectableSbcAac), + Arrays.asList(codecsSelectableSbcAac)); + BluetoothCodecStatus codecStatusAacAndSbcAac = + new BluetoothCodecStatus( + mCodecConfigAac, + Arrays.asList(codecsSelectableSbcAac), + Arrays.asList(codecsSelectableSbcAac)); + BluetoothCodecStatus codecStatusOpusAndSbcAacOpus = + new BluetoothCodecStatus( + mCodecConfigOpus, + Arrays.asList(codecsSelectableSbcAacOpus), + Arrays.asList(codecsSelectableSbcAacOpus)); // Set default codec status when device disconnected // Selected codec = SBC, selectable codec = SBC @@ -379,8 +382,8 @@ public class A2dpStateMachineTest { // - two calls to broadcastConnectionState(): Disconnected -> Conecting -> Connected // - one call to broadcastAudioState() when entering Connected state ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mA2dpService, timeout(TIMEOUT_MS).times(2)).sendBroadcast(intentArgument2.capture(), - anyString(), any(Bundle.class)); + verify(mA2dpService, timeout(TIMEOUT_MS).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); // Verify that state machine update optional codec when enter connected state verify(mA2dpService, times(1)).updateOptionalCodecsSupport(mTestDevice); @@ -406,7 +409,8 @@ public class A2dpStateMachineTest { // Selected codec = OPUS, selectable codec = SBC+AAC+OPUS mA2dpStateMachine.processCodecConfigEvent(codecStatusOpusAndSbcAacOpus); if (!offloadEnabled) { - verify(mA2dpService).codecConfigUpdated(mTestDevice, codecStatusOpusAndSbcAacOpus, true); + verify(mA2dpService) + .codecConfigUpdated(mTestDevice, codecStatusOpusAndSbcAacOpus, true); } verify(mA2dpService, times(3)).updateOptionalCodecsSupport(mTestDevice); // Check if low latency audio been updated. @@ -433,8 +437,11 @@ public class A2dpStateMachineTest { codecsSelectableSbcAac[0] = mCodecConfigSbc; codecsSelectableSbcAac[1] = mCodecConfigAac; - BluetoothCodecStatus codecStatusSbcAndSbc = new BluetoothCodecStatus(mCodecConfigSbc, - Arrays.asList(codecsSelectableSbcAac), Arrays.asList(codecsSelectableSbc)); + BluetoothCodecStatus codecStatusSbcAndSbc = + new BluetoothCodecStatus( + mCodecConfigSbc, + Arrays.asList(codecsSelectableSbcAac), + Arrays.asList(codecsSelectableSbc)); mA2dpStateMachine.processCodecConfigEvent(codecStatusSbcAndSbc); mA2dpStateMachine.dump(new StringBuilder()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java index 5ed765dbc0e..2d4462d3404 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java @@ -79,7 +79,7 @@ public class A2dpSinkServiceBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED }; + int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; AttributionSource source = new AttributionSource.Builder(0).build(); mBinder.getDevicesMatchingConnectionStates(states, source); diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java index d19e6aa5a98..2503b164d9c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java @@ -90,9 +90,8 @@ public class A2dpSinkServiceTest { mDevice4 = mAdapter.getRemoteDevice("44:44:44:44:44:44"); mDevice5 = mAdapter.getRemoteDevice("55:55:55:55:55:55"); mDevice6 = mAdapter.getRemoteDevice("66:66:66:66:66:66"); - BluetoothDevice[] bondedDevices = new BluetoothDevice[]{ - mDevice1, mDevice2, mDevice3, mDevice4, mDevice5, mDevice6 - }; + BluetoothDevice[] bondedDevices = + new BluetoothDevice[] {mDevice1, mDevice2, mDevice3, mDevice4, mDevice5, mDevice6}; doReturn(true).when(mDatabaseManager).setProfileConnectionPolicy(any(), anyInt(), anyInt()); @@ -124,8 +123,8 @@ public class A2dpSinkServiceTest { private void setupDeviceConnection(BluetoothDevice device) { assertThat(mLooper.nextMessage()).isNull(); - assertThat(mService.getConnectionState(device)).isEqualTo( - BluetoothProfile.STATE_DISCONNECTED); + assertThat(mService.getConnectionState(device)) + .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); assertThat(mLooper.nextMessage()).isNull(); assertThat(mService.connect(device)).isTrue(); @@ -134,8 +133,7 @@ public class A2dpSinkServiceTest { StackEvent.connectionStateChanged(device, StackEvent.CONNECTION_STATE_CONNECTED); mService.messageFromNative(nativeEvent); syncHandler(A2dpSinkStateMachine.STACK_EVENT); - assertThat(mService.getConnectionState(device)).isEqualTo( - BluetoothProfile.STATE_CONNECTED); + assertThat(mService.getConnectionState(device)).isEqualTo(BluetoothProfile.STATE_CONNECTED); } /** @@ -149,54 +147,42 @@ public class A2dpSinkServiceTest { .thenReturn(priority); } - /** - * Test that initialization of the service completes and that we can get a instance - */ + /** Test that initialization of the service completes and that we can get a instance */ @Test public void testInitialize() { assertThat(A2dpSinkService.getA2dpSinkService()).isEqualTo(mService); } - /** - * Test that asking to connect with a null device fails - */ + /** Test that asking to connect with a null device fails */ @Test public void testConnectNullDevice() { assertThrows(IllegalArgumentException.class, () -> mService.connect(null)); } - /** - * Test that a CONNECTION_POLICY_ALLOWED device can connected - */ + /** Test that a CONNECTION_POLICY_ALLOWED device can connected */ @Test public void testConnectPolicyAllowedDevice() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED); setupDeviceConnection(mDevice1); } - /** - * Test that a CONNECTION_POLICY_FORBIDDEN device is not allowed to connect - */ + /** Test that a CONNECTION_POLICY_FORBIDDEN device is not allowed to connect */ @Test public void testConnectPolicyForbiddenDevice() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); assertThat(mService.connect(mDevice1)).isFalse(); - assertThat(mService.getConnectionState(mDevice1)).isEqualTo( - BluetoothProfile.STATE_DISCONNECTED); + assertThat(mService.getConnectionState(mDevice1)) + .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); } - /** - * Test that a CONNECTION_POLICY_UNKNOWN device is allowed to connect - */ + /** Test that a CONNECTION_POLICY_UNKNOWN device is allowed to connect */ @Test public void testConnectPolicyUnknownDevice() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); setupDeviceConnection(mDevice1); } - /** - * Test that we can connect multiple devices - */ + /** Test that we can connect multiple devices */ @Test public void testConnectMultipleDevices() { doReturn(5).when(mAdapterService).getMaxConnectedAudioDevices(); @@ -215,9 +201,7 @@ public class A2dpSinkServiceTest { setupDeviceConnection(mDevice5); } - /** - * Test to make sure we can disconnect a connected device - */ + /** Test to make sure we can disconnect a connected device */ @Test public void testDisconnect() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED); @@ -225,31 +209,25 @@ public class A2dpSinkServiceTest { assertThat(mService.disconnect(mDevice1)).isTrue(); syncHandler(A2dpSinkStateMachine.DISCONNECT); - assertThat(mService.getConnectionState(mDevice1)).isEqualTo( - BluetoothProfile.STATE_DISCONNECTED); + assertThat(mService.getConnectionState(mDevice1)) + .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); syncHandler(A2dpSinkStateMachine.CLEANUP, -1 /* SM_QUIT_CMD */); } - /** - * Assure disconnect() fails with a device that's not connected - */ + /** Assure disconnect() fails with a device that's not connected */ @Test public void testDisconnectDeviceDoesNotExist() { assertThat(mService.disconnect(mDevice1)).isFalse(); } - /** - * Assure disconnect() fails with an invalid device - */ + /** Assure disconnect() fails with an invalid device */ @Test public void testDisconnectNullDevice() { assertThrows(IllegalArgumentException.class, () -> mService.disconnect(null)); } - /** - * Assure dump() returns something and does not crash - */ + /** Assure dump() returns something and does not crash */ @Test public void testDump() { StringBuilder sb = new StringBuilder(); @@ -269,18 +247,14 @@ public class A2dpSinkServiceTest { assertThat(mService.getActiveDevice()).isEqualTo(mDevice1); } - /** - * Test that calls to set a null active device succeed in unsetting the active device - */ + /** Test that calls to set a null active device succeed in unsetting the active device */ @Test public void testSetActiveDeviceNullDevice() { assertThat(mService.setActiveDevice(null)).isTrue(); assertThat(mService.getActiveDevice()).isNull(); } - /** - * Make sure we can receive the set audio configuration - */ + /** Make sure we can receive the set audio configuration */ @Test public void testGetAudioConfiguration() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED); @@ -291,8 +265,9 @@ public class A2dpSinkServiceTest { mService.messageFromNative(audioConfigChanged); syncHandler(A2dpSinkStateMachine.STACK_EVENT); - BluetoothAudioConfig expected = new BluetoothAudioConfig(TEST_SAMPLE_RATE, - TEST_CHANNEL_COUNT, AudioFormat.ENCODING_PCM_16BIT); + BluetoothAudioConfig expected = + new BluetoothAudioConfig( + TEST_SAMPLE_RATE, TEST_CHANNEL_COUNT, AudioFormat.ENCODING_PCM_16BIT); BluetoothAudioConfig config = mService.getAudioConfig(mDevice1); assertThat(config).isEqualTo(expected); } @@ -317,9 +292,7 @@ public class A2dpSinkServiceTest { assertThat(mService.getAudioConfig(mDevice1)).isNull(); } - /** - * Getting an audio config for a device that hasn't received one yet should return null - */ + /** Getting an audio config for a device that hasn't received one yet should return null */ @Test public void testGetAudioConfigWithConfigUnset() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED); @@ -327,18 +300,13 @@ public class A2dpSinkServiceTest { assertThat(mService.getAudioConfig(mDevice1)).isNull(); } - /** - * Getting an audio config for a null device should return null - */ + /** Getting an audio config for a null device should return null */ @Test public void testGetAudioConfigNullDevice() { assertThat(mService.getAudioConfig(null)).isNull(); } - /** - * Test that a newly connected device ends up in the set returned by - * getConnectedDevices - */ + /** Test that a newly connected device ends up in the set returned by getConnectedDevices */ @Test public void testGetConnectedDevices() { ArrayList expected = new ArrayList(); @@ -362,8 +330,9 @@ public class A2dpSinkServiceTest { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED); setupDeviceConnection(mDevice1); - List devices = mService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED}); + List devices = + mService.getDevicesMatchingConnectionStates( + new int[] {BluetoothProfile.STATE_CONNECTED}); assertThat(devices).isEqualTo(expected); } @@ -381,48 +350,43 @@ public class A2dpSinkServiceTest { expected.add(mDevice5); expected.add(mDevice6); - List devices = mService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_DISCONNECTED}); + List devices = + mService.getDevicesMatchingConnectionStates( + new int[] {BluetoothProfile.STATE_DISCONNECTED}); assertThat(devices).isEqualTo(expected); } - /** - * Test that GetConnectionPolicy() can get a device with policy "Allowed" - */ + /** Test that GetConnectionPolicy() can get a device with policy "Allowed" */ @Test public void testGetConnectionPolicyDeviceAllowed() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED); - assertThat(mService.getConnectionPolicy(mDevice1)).isEqualTo( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + assertThat(mService.getConnectionPolicy(mDevice1)) + .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED); } - /** - * Test that GetConnectionPolicy() can get a device with policy "Forbidden" - */ + /** Test that GetConnectionPolicy() can get a device with policy "Forbidden" */ @Test public void testGetConnectionPolicyDeviceForbidden() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - assertThat(mService.getConnectionPolicy(mDevice1)).isEqualTo( - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + assertThat(mService.getConnectionPolicy(mDevice1)) + .isEqualTo(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); } - /** - * Test that GetConnectionPolicy() can get a device with policy "Unknown" - */ + /** Test that GetConnectionPolicy() can get a device with policy "Unknown" */ @Test public void testGetConnectionPolicyDeviceUnknown() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - assertThat(mService.getConnectionPolicy(mDevice1)).isEqualTo( - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + assertThat(mService.getConnectionPolicy(mDevice1)) + .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); } - /** - * Test that SetConnectionPolicy() can change a device's policy to "Allowed" - */ + /** Test that SetConnectionPolicy() can change a device's policy to "Allowed" */ @Test public void testSetConnectionPolicyDeviceAllowed() { - assertThat(mService.setConnectionPolicy(mDevice1, - BluetoothProfile.CONNECTION_POLICY_ALLOWED)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED)) + .isTrue(); verify(mDatabaseManager) .setProfileConnectionPolicy( mDevice1, @@ -430,13 +394,13 @@ public class A2dpSinkServiceTest { BluetoothProfile.CONNECTION_POLICY_ALLOWED); } - /** - * Test that SetConnectionPolicy() can change a device's policy to "Forbidden" - */ + /** Test that SetConnectionPolicy() can change a device's policy to "Forbidden" */ @Test public void testSetConnectionPolicyDeviceForbiddenWhileNotConnected() { - assertThat(mService.setConnectionPolicy(mDevice1, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mDevice1, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + .isTrue(); verify(mDatabaseManager) .setProfileConnectionPolicy( mDevice1, @@ -445,16 +409,18 @@ public class A2dpSinkServiceTest { } /** - * Test that SetConnectionPolicy() can change a connected device's policy to "Forbidden" - * and that the new "Forbidden" policy causes a disconnect of the device. + * Test that SetConnectionPolicy() can change a connected device's policy to "Forbidden" and + * that the new "Forbidden" policy causes a disconnect of the device. */ @Test public void testSetConnectionPolicyDeviceForbiddenWhileConnected() { mockDevicePriority(mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED); setupDeviceConnection(mDevice1); - assertThat(mService.setConnectionPolicy(mDevice1, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mDevice1, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + .isTrue(); verify(mDatabaseManager) .setProfileConnectionPolicy( mDevice1, @@ -463,19 +429,19 @@ public class A2dpSinkServiceTest { syncHandler(A2dpSinkStateMachine.DISCONNECT); verify(mNativeInterface).disconnectA2dpSink(eq(mDevice1)); - assertThat(mService.getConnectionState(mDevice1)).isEqualTo( - BluetoothProfile.STATE_DISCONNECTED); + assertThat(mService.getConnectionState(mDevice1)) + .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); syncHandler(A2dpSinkStateMachine.CLEANUP, -1 /* SM_QUIT_CMD */); } - /** - * Test that SetConnectionPolicy() can change a device's policy to "Unknown" - */ + /** Test that SetConnectionPolicy() can change a device's policy to "Unknown" */ @Test public void testSetConnectionPolicyDeviceUnknown() { - assertThat(mService.setConnectionPolicy(mDevice1, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mDevice1, BluetoothProfile.CONNECTION_POLICY_UNKNOWN)) + .isTrue(); verify(mDatabaseManager) .setProfileConnectionPolicy( mDevice1, @@ -483,15 +449,15 @@ public class A2dpSinkServiceTest { BluetoothProfile.CONNECTION_POLICY_UNKNOWN); } - /** - * Test that SetConnectionPolicy is robust to DatabaseManager failures - */ + /** Test that SetConnectionPolicy is robust to DatabaseManager failures */ @Test public void testSetConnectionPolicyDatabaseWriteFails() { - when(mDatabaseManager.setProfileConnectionPolicy(any(), anyInt(), - anyInt())).thenReturn(false); - assertThat(mService.setConnectionPolicy(mDevice1, - BluetoothProfile.CONNECTION_POLICY_ALLOWED)).isFalse(); + when(mDatabaseManager.setProfileConnectionPolicy(any(), anyInt(), anyInt())) + .thenReturn(false); + assertThat( + mService.setConnectionPolicy( + mDevice1, BluetoothProfile.CONNECTION_POLICY_ALLOWED)) + .isFalse(); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java index aac7f7f6753..6e65d7ee546 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java @@ -101,13 +101,15 @@ public class A2dpSinkStateMachineTest { } private void sendConnectionEvent(int state) { - mStateMachine.sendMessage(A2dpSinkStateMachine.STACK_EVENT, + mStateMachine.sendMessage( + A2dpSinkStateMachine.STACK_EVENT, StackEvent.connectionStateChanged(mDevice, state)); syncHandler(A2dpSinkStateMachine.STACK_EVENT); } private void sendAudioConfigChangedEvent(int sampleRate, int channelCount) { - mStateMachine.sendMessage(A2dpSinkStateMachine.STACK_EVENT, + mStateMachine.sendMessage( + A2dpSinkStateMachine.STACK_EVENT, StackEvent.audioConfigChanged(mDevice, sampleRate, channelCount)); syncHandler(A2dpSinkStateMachine.STACK_EVENT); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java index fe49e05bf6e..c74fd3ef35f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java @@ -73,8 +73,7 @@ public class A2dpSinkStreamHandlerTest { @Rule public final ServiceTestRule mBluetoothBrowserMediaServiceTestRule = new ServiceTestRule(); - @Mock - private AdapterService mAdapterService; + @Mock private AdapterService mAdapterService; @Before public void setUp() throws Exception { @@ -99,10 +98,10 @@ public class A2dpSinkStreamHandlerTest { .thenReturn(Context.AUDIO_SERVICE); when(mMockA2dpSink.getResources()).thenReturn(mMockResources); when(mMockResources.getInteger(anyInt())).thenReturn(DUCK_PERCENT); - when(mMockAudioManager.requestAudioFocus(any())).thenReturn( - AudioManager.AUDIOFOCUS_REQUEST_GRANTED); - when(mMockAudioManager.abandonAudioFocus(any())).thenReturn( - AudioManager.AUDIOFOCUS_REQUEST_GRANTED); + when(mMockAudioManager.requestAudioFocus(any())) + .thenReturn(AudioManager.AUDIOFOCUS_REQUEST_GRANTED); + when(mMockAudioManager.abandonAudioFocus(any())) + .thenReturn(AudioManager.AUDIOFOCUS_REQUEST_GRANTED); when(mMockAudioManager.generateAudioSessionId()).thenReturn(0); when(mMockA2dpSink.getMainLooper()).thenReturn(mHandlerThread.getLooper()); when(mMockA2dpSink.getPackageManager()).thenReturn(mMockPackageManager); @@ -210,8 +209,8 @@ public class A2dpSinkStreamHandlerTest { // Focus was gained, expect streaming to resume. testSnkPlay(); mStreamHandler.handleMessage( - mStreamHandler.obtainMessage(A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, - AudioManager.AUDIOFOCUS_GAIN)); + mStreamHandler.obtainMessage( + A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, AudioManager.AUDIOFOCUS_GAIN)); verify(mMockAudioManager, times(1)).requestAudioFocus(any()); verify(mMockNativeInterface, times(1)).informAudioFocusState(1); verify(mMockNativeInterface, times(1)).informAudioTrackGain(1.0f); @@ -226,13 +225,14 @@ public class A2dpSinkStreamHandlerTest { // TransientMayDuck focus was gained, expect audio stream to duck. testSnkPlay(); mStreamHandler.handleMessage( - mStreamHandler.obtainMessage(A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, + mStreamHandler.obtainMessage( + A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)); verify(mMockNativeInterface, times(1)).informAudioTrackGain(DUCK_PERCENT / 100.0f); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mStreamHandler.getFocusState()).isEqualTo( - AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK); + assertThat(mStreamHandler.getFocusState()) + .isEqualTo(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK); assertThat(BluetoothMediaBrowserService.isActive()).isFalse(); } @@ -241,15 +241,16 @@ public class A2dpSinkStreamHandlerTest { // Focus was lost transiently, expect streaming to stop. testSnkPlay(); mStreamHandler.handleMessage( - mStreamHandler.obtainMessage(A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, + mStreamHandler.obtainMessage( + A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)); verify(mMockAudioManager, times(0)).abandonAudioFocus(any()); verify(mMockNativeInterface, times(0)).informAudioFocusState(0); verify(mMockNativeInterface, times(1)).informAudioTrackGain(0); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mStreamHandler.getFocusState()).isEqualTo( - AudioManager.AUDIOFOCUS_LOSS_TRANSIENT); + assertThat(mStreamHandler.getFocusState()) + .isEqualTo(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT); assertThat(BluetoothMediaBrowserService.isActive()).isFalse(); } @@ -258,7 +259,8 @@ public class A2dpSinkStreamHandlerTest { // Focus was lost transiently, expect streaming to stop. testSnkPlay(); mStreamHandler.handleMessage( - mStreamHandler.obtainMessage(A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, + mStreamHandler.obtainMessage( + A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)); verify(mMockAudioManager, times(0)).abandonAudioFocus(any()); verify(mMockNativeInterface, times(0)).informAudioFocusState(0); @@ -276,8 +278,8 @@ public class A2dpSinkStreamHandlerTest { testFocusLostTransient(); mStreamHandler.handleMessage( - mStreamHandler.obtainMessage(A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, - AudioManager.AUDIOFOCUS_GAIN)); + mStreamHandler.obtainMessage( + A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, AudioManager.AUDIOFOCUS_GAIN)); verify(mMockAudioManager, times(0)).abandonAudioFocus(any()); verify(mMockNativeInterface, times(1)).informAudioTrackGain(1.0f); @@ -291,8 +293,8 @@ public class A2dpSinkStreamHandlerTest { // Focus was lost permanently, expect streaming to stop. testSnkPlay(); mStreamHandler.handleMessage( - mStreamHandler.obtainMessage(A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, - AudioManager.AUDIOFOCUS_LOSS)); + mStreamHandler.obtainMessage( + A2dpSinkStreamHandler.AUDIO_FOCUS_CHANGE, AudioManager.AUDIOFOCUS_LOSS)); verify(mMockAudioManager, times(1)).abandonAudioFocus(any()); verify(mMockNativeInterface, times(1)).informAudioFocusState(0); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowsablePlayerConnectorTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowsablePlayerConnectorTest.java index c2426563b57..2ab0f73311a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowsablePlayerConnectorTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowsablePlayerConnectorTest.java @@ -57,26 +57,36 @@ public final class BrowsablePlayerConnectorTest { @Mock MediaBrowser mMediaBrowser; MediaBrowser.ConnectionCallback mConnectionCallback; + @Before public void setUp() { mContext = InstrumentationRegistry.getTargetContext(); mTestLooper = new TestLooper(); - doAnswer(invocation -> { - mConnectionCallback = invocation.getArgument(2); - return null; - }).when(mMediaBrowser).testInit(any(), any(), any(), any()); - doAnswer(invocation -> { - mConnectionCallback.onConnected(); - return null; - }).when(mMediaBrowser).connect(); - doAnswer(invocation -> { - String id = invocation.getArgument(0); - android.media.browse.MediaBrowser.SubscriptionCallback callback - = invocation.getArgument(1); - callback.onChildrenLoaded(id, Collections.emptyList()); - return null; - }).when(mMediaBrowser).subscribe(any(), any()); + doAnswer( + invocation -> { + mConnectionCallback = invocation.getArgument(2); + return null; + }) + .when(mMediaBrowser) + .testInit(any(), any(), any(), any()); + doAnswer( + invocation -> { + mConnectionCallback.onConnected(); + return null; + }) + .when(mMediaBrowser) + .connect(); + doAnswer( + invocation -> { + String id = invocation.getArgument(0); + android.media.browse.MediaBrowser.SubscriptionCallback callback = + invocation.getArgument(1); + callback.onChildrenLoaded(id, Collections.emptyList()); + return null; + }) + .when(mMediaBrowser) + .subscribe(any(), any()); doReturn("testRoot").when(mMediaBrowser).getRoot(); MediaBrowserFactory.inject(mMediaBrowser); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java index dcf1b069d96..ae23dca6bb2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java @@ -80,15 +80,15 @@ public class BrowserPlayerWrapperTest { private MockContentResolver mTestContentResolver; private static final String TEST_AUTHORITY = "com.android.bluetooth.avrcp.test"; - private static final Uri TEST_CONTENT_URI = new Uri.Builder() - .scheme(ContentResolver.SCHEME_CONTENT) - .authority(TEST_AUTHORITY) - .build(); + private static final Uri TEST_CONTENT_URI = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(TEST_AUTHORITY) + .build(); private static final String IMAGE_HANDLE_1 = "0000001"; - private static final Uri IMAGE_URI_1 = TEST_CONTENT_URI.buildUpon() - .appendQueryParameter("handle", IMAGE_HANDLE_1) - .build(); + private static final Uri IMAGE_URI_1 = + TEST_CONTENT_URI.buildUpon().appendQueryParameter("handle", IMAGE_HANDLE_1).build(); private static final String IMAGE_STRING_1 = IMAGE_URI_1.toString(); private Bitmap mTestBitmap = null; @@ -102,17 +102,20 @@ public class BrowserPlayerWrapperTest { mTestBitmap = loadImage(com.android.bluetooth.tests.R.raw.image_200_200); mTestContentResolver = new MockContentResolver(mTargetContext); - mTestContentResolver.addProvider(TEST_AUTHORITY, new MockContentProvider() { - @Override - public AssetFileDescriptor openTypedAssetFile(Uri url, String mimeType, Bundle opts) { - String handle = url.getQueryParameter("handle"); - if (IMAGE_URI_1.equals(url)) { - return mTestResources.openRawResourceFd( - com.android.bluetooth.tests.R.raw.image_200_200); - } - return null; - } - }); + mTestContentResolver.addProvider( + TEST_AUTHORITY, + new MockContentProvider() { + @Override + public AssetFileDescriptor openTypedAssetFile( + Uri url, String mimeType, Bundle opts) { + String handle = url.getQueryParameter("handle"); + if (IMAGE_URI_1.equals(url)) { + return mTestResources.openRawResourceFd( + com.android.bluetooth.tests.R.raw.image_200_200); + } + return null; + } + }); when(mMockContext.getContentResolver()).thenReturn(mTestContentResolver); when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(true); @@ -144,13 +147,20 @@ public class BrowserPlayerWrapperTest { return BitmapFactory.decodeStream(imageInputStream); } - private MediaDescription getMediaDescription(String id, String title, String artist, - String album, Bitmap bitmap, Uri uri, Bundle extras) { - MediaDescription.Builder builder = new MediaDescription.Builder() - .setMediaId(id) - .setTitle(title) - .setSubtitle(artist) - .setDescription(album); + private MediaDescription getMediaDescription( + String id, + String title, + String artist, + String album, + Bitmap bitmap, + Uri uri, + Bundle extras) { + MediaDescription.Builder builder = + new MediaDescription.Builder() + .setMediaId(id) + .setTitle(title) + .setSubtitle(artist) + .setDescription(album); if (bitmap != null) { builder.setIconBitmap(bitmap); } @@ -372,8 +382,11 @@ public class BrowserPlayerWrapperTest { subscriptionCb.onChildrenLoaded("test_folder", items); verify(mMockBrowser).unsubscribe(eq("test_folder")); - verify(mBrowseCb).run(eq(BrowsedPlayerWrapper.STATUS_SUCCESS), eq("test_folder"), - mWrapperBrowseCb.capture()); + verify(mBrowseCb) + .run( + eq(BrowsedPlayerWrapper.STATUS_SUCCESS), + eq("test_folder"), + mWrapperBrowseCb.capture()); // Verify returned ListItems List item_list = mWrapperBrowseCb.getValue(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/GPMWrapperTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/GPMWrapperTest.java index 7f03b378ec3..f14df9e2ce6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/GPMWrapperTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/GPMWrapperTest.java @@ -62,23 +62,24 @@ public class GPMWrapperTest { @Test public void isMetadataSynced_whenOutOfSync_returnsFalse() { long activeQueueItemId = 3; - PlaybackState state = new PlaybackState.Builder() - .setActiveQueueItemId(activeQueueItemId).build(); + PlaybackState state = + new PlaybackState.Builder().setActiveQueueItemId(activeQueueItemId).build(); when(mMediaController.getPlaybackState()).thenReturn(state); List queue = new ArrayList<>(); - MediaDescription description = new MediaDescription.Builder() - .setTitle("Title from queue item") - .build(); - MediaSession.QueueItem queueItem = new MediaSession.QueueItem( - description, activeQueueItemId); + MediaDescription description = + new MediaDescription.Builder().setTitle("Title from queue item").build(); + MediaSession.QueueItem queueItem = + new MediaSession.QueueItem(description, activeQueueItemId); queue.add(queueItem); when(mMediaController.getQueue()).thenReturn(queue); - MediaMetadata metadata = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_TITLE, - "Different Title from MediaMetadata") - .build(); + MediaMetadata metadata = + new MediaMetadata.Builder() + .putString( + MediaMetadata.METADATA_KEY_TITLE, + "Different Title from MediaMetadata") + .build(); when(mMediaController.getMetadata()).thenReturn(metadata); GPMWrapper wrapper = new GPMWrapper(mContext, mMediaController, null); @@ -91,22 +92,21 @@ public class GPMWrapperTest { String title = "test_title"; long activeQueueItemId = 3; - PlaybackState state = new PlaybackState.Builder() - .setActiveQueueItemId(activeQueueItemId).build(); + PlaybackState state = + new PlaybackState.Builder().setActiveQueueItemId(activeQueueItemId).build(); when(mMediaController.getPlaybackState()).thenReturn(state); List queue = new ArrayList<>(); - MediaDescription description = new MediaDescription.Builder() - .setTitle(title) - .build(); - MediaSession.QueueItem queueItem = new MediaSession.QueueItem( - description, activeQueueItemId); + MediaDescription description = new MediaDescription.Builder().setTitle(title).build(); + MediaSession.QueueItem queueItem = + new MediaSession.QueueItem(description, activeQueueItemId); queue.add(queueItem); when(mMediaController.getQueue()).thenReturn(queue); - MediaMetadata metadata = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_TITLE, title) - .build(); + MediaMetadata metadata = + new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_TITLE, title) + .build(); when(mMediaController.getMetadata()).thenReturn(metadata); GPMWrapper wrapper = new GPMWrapper(mContext, mMediaController, null); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java index 4d7d339d86d..e485d08a16f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java @@ -62,21 +62,23 @@ public class ImageTest { private MockContentResolver mTestContentResolver; private static final String TEST_AUTHORITY = "com.android.bluetooth.avrcp.test"; - private static final Uri TEST_CONTENT_URI = new Uri.Builder() - .scheme(ContentResolver.SCHEME_CONTENT) - .authority(TEST_AUTHORITY) - .build(); + private static final Uri TEST_CONTENT_URI = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(TEST_AUTHORITY) + .build(); private static final String IMAGE_HANDLE_1 = "0000001"; - private static final Uri IMAGE_URI_1 = TEST_CONTENT_URI.buildUpon() - .appendQueryParameter("handle", IMAGE_HANDLE_1) - .build(); + private static final Uri IMAGE_URI_1 = + TEST_CONTENT_URI.buildUpon().appendQueryParameter("handle", IMAGE_HANDLE_1).build(); private static final String IMAGE_STRING_1 = IMAGE_URI_1.toString(); private static final String IMAGE_HANDLE_SECURITY_ERROR = "sec_error"; - private static final Uri IMAGE_URI_SECURITY_ERROR = TEST_CONTENT_URI.buildUpon() - .appendQueryParameter("handle", IMAGE_HANDLE_SECURITY_ERROR) - .build(); + private static final Uri IMAGE_URI_SECURITY_ERROR = + TEST_CONTENT_URI + .buildUpon() + .appendQueryParameter("handle", IMAGE_HANDLE_SECURITY_ERROR) + .build(); private Bitmap mTestBitmap = null; @@ -89,19 +91,22 @@ public class ImageTest { mTestBitmap = loadImage(com.android.bluetooth.tests.R.raw.image_200_200); mTestContentResolver = new MockContentResolver(mTargetContext); - mTestContentResolver.addProvider(TEST_AUTHORITY, new MockContentProvider() { - @Override - public AssetFileDescriptor openTypedAssetFile(Uri url, String mimeType, Bundle opts) { - String handle = url.getQueryParameter("handle"); - if (IMAGE_URI_1.equals(url)) { - return mTestResources.openRawResourceFd( - com.android.bluetooth.tests.R.raw.image_200_200); - } else if (IMAGE_URI_SECURITY_ERROR.equals(url)) { - throw new SecurityException(); - } - return null; - } - }); + mTestContentResolver.addProvider( + TEST_AUTHORITY, + new MockContentProvider() { + @Override + public AssetFileDescriptor openTypedAssetFile( + Uri url, String mimeType, Bundle opts) { + String handle = url.getQueryParameter("handle"); + if (IMAGE_URI_1.equals(url)) { + return mTestResources.openRawResourceFd( + com.android.bluetooth.tests.R.raw.image_200_200); + } else if (IMAGE_URI_SECURITY_ERROR.equals(url)) { + throw new SecurityException(); + } + return null; + } + }); when(mMockContext.getContentResolver()).thenReturn(mTestContentResolver); when(mMockContext.getResources()).thenReturn(mMockResources); @@ -123,54 +128,60 @@ public class ImageTest { } private MediaMetadata getMediaMetadataWithoutArt() { - MediaMetadata.Builder builder = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") - .putString(MediaMetadata.METADATA_KEY_ARTIST, "BT Test Artist") - .putString(MediaMetadata.METADATA_KEY_ALBUM, "BT Test Album") - .putLong(MediaMetadata.METADATA_KEY_DURATION, 5000L); + MediaMetadata.Builder builder = + new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") + .putString(MediaMetadata.METADATA_KEY_ARTIST, "BT Test Artist") + .putString(MediaMetadata.METADATA_KEY_ALBUM, "BT Test Album") + .putLong(MediaMetadata.METADATA_KEY_DURATION, 5000L); return builder.build(); } private MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { - MediaMetadata.Builder builder = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") - .putString(MediaMetadata.METADATA_KEY_ARTIST, "BT Test Artist") - .putString(MediaMetadata.METADATA_KEY_ALBUM, "BT Test Album") - .putLong(MediaMetadata.METADATA_KEY_DURATION, 5000L) - .putBitmap(field, image); + MediaMetadata.Builder builder = + new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") + .putString(MediaMetadata.METADATA_KEY_ARTIST, "BT Test Artist") + .putString(MediaMetadata.METADATA_KEY_ALBUM, "BT Test Album") + .putLong(MediaMetadata.METADATA_KEY_DURATION, 5000L) + .putBitmap(field, image); return builder.build(); } private MediaMetadata getMediaMetadataWithUri(String field, String uri) { - MediaMetadata.Builder builder = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") - .putString(MediaMetadata.METADATA_KEY_ARTIST, "BT Test Artist") - .putString(MediaMetadata.METADATA_KEY_ALBUM, "BT Test Album") - .putLong(MediaMetadata.METADATA_KEY_DURATION, 5000L) - .putString(field, uri); + MediaMetadata.Builder builder = + new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") + .putString(MediaMetadata.METADATA_KEY_ARTIST, "BT Test Artist") + .putString(MediaMetadata.METADATA_KEY_ALBUM, "BT Test Album") + .putLong(MediaMetadata.METADATA_KEY_DURATION, 5000L) + .putString(field, uri); return builder.build(); } private MediaDescription getMediaDescriptionWithoutArt() { - MediaDescription.Builder builder = new MediaDescription.Builder() - .setTitle("BT Test Song") - .setDescription("BT Test Description"); + MediaDescription.Builder builder = + new MediaDescription.Builder() + .setTitle("BT Test Song") + .setDescription("BT Test Description"); return builder.build(); } private MediaDescription getMediaDescriptionWithBitmap(Bitmap image) { - MediaDescription.Builder builder = new MediaDescription.Builder() - .setTitle("BT Test Song") - .setDescription("BT Test Description") - .setIconBitmap(image); + MediaDescription.Builder builder = + new MediaDescription.Builder() + .setTitle("BT Test Song") + .setDescription("BT Test Description") + .setIconBitmap(image); return builder.build(); } private MediaDescription getMediaDescriptionWithUri(Uri uri) { - MediaDescription.Builder builder = new MediaDescription.Builder() - .setTitle("BT Test Song") - .setDescription("BT Test Description") - .setIconUri(uri); + MediaDescription.Builder builder = + new MediaDescription.Builder() + .setTitle("BT Test Song") + .setDescription("BT Test Description") + .setIconUri(uri); return builder.build(); } @@ -187,8 +198,8 @@ public class ImageTest { } /** - * Make sure you can create an Image from a MediaMetadata object that contains cover artwork - * as an Art Bitmap + * Make sure you can create an Image from a MediaMetadata object that contains cover artwork as + * an Art Bitmap */ @Test public void testCreateImageFromMediaMetadataWithArt() { @@ -201,8 +212,8 @@ public class ImageTest { } /** - * Make sure you can create an Image from a MediaMetadata object that contains cover artwork - * as an Album Art Bitmap + * Make sure you can create an Image from a MediaMetadata object that contains cover artwork as + * an Album Art Bitmap */ @Test public void testCreateImageFromMediaMetadataWithAlbumArt() { @@ -215,8 +226,8 @@ public class ImageTest { } /** - * Make sure you can create an Image from a MediaMetadata object that contains cover artwork - * as a Display Icon Bitmap + * Make sure you can create an Image from a MediaMetadata object that contains cover artwork as + * a Display Icon Bitmap */ @Test public void testCreateImageFromMediaMetadataWithDisplayIcon() { @@ -229,8 +240,8 @@ public class ImageTest { } /** - * Make sure you can create an Image from a MediaMetadata object that contains cover artwork - * as an Art Uri + * Make sure you can create an Image from a MediaMetadata object that contains cover artwork as + * an Art Uri */ @Test public void testCreateImageFromMediaMetadataWithArtUri() { @@ -243,8 +254,8 @@ public class ImageTest { } /** - * Make sure you can create an Image from a MediaMetadata object that contains cover artwork - * as an Album Art Uri + * Make sure you can create an Image from a MediaMetadata object that contains cover artwork as + * an Album Art Uri */ @Test public void testCreateImageFromMediaMetadataWithAlbumArtUri() { @@ -257,14 +268,14 @@ public class ImageTest { } /** - * Make sure you can create an Image from a MediaMetadata object that contains cover artwork - * as a Display Icon Uri + * Make sure you can create an Image from a MediaMetadata object that contains cover artwork as + * a Display Icon Uri */ @Test public void testCreateImageFromMediaMetadataWithDisplayIconUri() { MediaMetadata metadata = - getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, - IMAGE_STRING_1); + getMediaMetadataWithUri( + MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, IMAGE_STRING_1); Image artwork = new Image(mMockContext, metadata); assertThat(mTestBitmap.sameAs(artwork.getImage())).isTrue(); assertThat(artwork.getSource()).isEqualTo(Image.SOURCE_URI); @@ -277,8 +288,7 @@ public class ImageTest { */ @Test public void testCreateImageFromMediaMetadataWithArtUriDisabled() { - when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)) - .thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); MediaMetadata metadata = getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_STRING_1); Image artwork = new Image(mMockContext, metadata); @@ -293,8 +303,7 @@ public class ImageTest { */ @Test public void testCreateImageFromMediaMetadataWithAlbumArtUriDisabled() { - when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)) - .thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); MediaMetadata metadata = getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ALBUM_ART_URI, IMAGE_STRING_1); Image artwork = new Image(mMockContext, metadata); @@ -309,11 +318,10 @@ public class ImageTest { */ @Test public void testCreateImageFromMediaMetadataWithDisplayIconUriDisabled() { - when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)) - .thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); MediaMetadata metadata = - getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, - IMAGE_STRING_1); + getMediaMetadataWithUri( + MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, IMAGE_STRING_1); Image artwork = new Image(mMockContext, metadata); assertThat(artwork.getImage()).isNull(); assertThat(artwork.getSource()).isEqualTo(Image.SOURCE_NONE); @@ -397,8 +405,8 @@ public class ImageTest { } /** - * Make sure you can create an Image from a Bundle that contains cover artwork as a Display - * Icon Bitmap + * Make sure you can create an Image from a Bundle that contains cover artwork as a Display Icon + * Bitmap */ @Test public void testCreateImageFromBundleWithDisplayIcon() { @@ -409,9 +417,7 @@ public class ImageTest { assertThat(artwork.getImageHandle()).isNull(); } - /** - * Make sure you can create an Image from a Bundle that contains cover artwork as an Art Uri - */ + /** Make sure you can create an Image from a Bundle that contains cover artwork as an Art Uri */ @Test public void testCreateImageFromBundleWithArtUri() { Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_STRING_1); @@ -435,8 +441,8 @@ public class ImageTest { } /** - * Make sure you can create an Image from a Bundle that contains cover artwork as a Display - * Icon Uri + * Make sure you can create an Image from a Bundle that contains cover artwork as a Display Icon + * Uri */ @Test public void testCreateImageFromBundleWithDisplayIconUri() { @@ -454,8 +460,7 @@ public class ImageTest { */ @Test public void testCreateImageFromBundleWithArtUriDisabled() { - when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)) - .thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_STRING_1); Image artwork = new Image(mMockContext, bundle); assertThat(artwork.getImage()).isNull(); @@ -469,8 +474,7 @@ public class ImageTest { */ @Test public void testCreateImageFromBundleWithAlbumArtUriDisabled() { - when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)) - .thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_ALBUM_ART_URI, IMAGE_STRING_1); Image artwork = new Image(mMockContext, bundle); assertThat(artwork.getImage()).isNull(); @@ -484,8 +488,7 @@ public class ImageTest { */ @Test public void testCreateImageFromBundleWithDisplayIconUriDisabled() { - when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)) - .thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, IMAGE_STRING_1); Image artwork = new Image(mMockContext, bundle); @@ -494,9 +497,7 @@ public class ImageTest { assertThat(artwork.getImageHandle()).isNull(); } - /** - * Make sure you can create an Image from a Bundle that contains no cover artwork - */ + /** Make sure you can create an Image from a Bundle that contains no cover artwork */ @Test public void testCreateImageFromBundleWithoutArtwork() { Bundle bundle = new Bundle(); @@ -506,9 +507,7 @@ public class ImageTest { assertThat(artwork.getImageHandle()).isNull(); } - /** - * Make sure you can create an image from a simple Uri - */ + /** Make sure you can create an image from a simple Uri */ @Test public void testCreateImageFromUri() { Image artwork = new Image(mMockContext, IMAGE_URI_1); @@ -517,9 +516,7 @@ public class ImageTest { assertThat(artwork.getImageHandle()).isNull(); } - /** - * Make sure you can create an image from a simple Bitmap Image - */ + /** Make sure you can create an image from a simple Bitmap Image */ @Test public void testCreateImageFromBitmap() { Image artwork = new Image(mMockContext, mTestBitmap); @@ -528,18 +525,14 @@ public class ImageTest { assertThat(artwork.getImageHandle()).isNull(); } - /** - * Make sure you can get the image handle associated with this object when there is none set - */ + /** Make sure you can get the image handle associated with this object when there is none set */ @Test public void testGetImageHandleWithEmptyHandle() { Image artwork = new Image(mMockContext, mTestBitmap); assertThat(artwork.getImageHandle()).isNull(); } - /** - * Make sure you can get and set the image handle associated with this object - */ + /** Make sure you can get and set the image handle associated with this object */ @Test public void testSetAndGetImageHandle() { Image artwork = new Image(mMockContext, mTestBitmap); @@ -559,9 +552,7 @@ public class ImageTest { assertThat(artwork.getImage()).isNull(); } - /** - * Make sure you can get a string representation of this Image - */ + /** Make sure you can get a string representation of this Image */ @Test public void testToString() { Image artwork = new Image(mMockContext, mTestBitmap); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java index 6b7af24254a..0cfc114f579 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java @@ -74,22 +74,22 @@ public class MediaPlayerListTest { } Assert.assertNotNull(Looper.myLooper()); - AudioManager mockAudioManager = mock(AudioManager.class); when(mMockContext.getSystemService(Context.AUDIO_SERVICE)).thenReturn(mockAudioManager); when(mMockContext.getSystemServiceName(AudioManager.class)) - .thenReturn(Context.AUDIO_SERVICE); + .thenReturn(Context.AUDIO_SERVICE); - mMediaSessionManager = InstrumentationRegistry.getTargetContext() - .getSystemService(MediaSessionManager.class); + mMediaSessionManager = + InstrumentationRegistry.getTargetContext() + .getSystemService(MediaSessionManager.class); PackageManager mockPackageManager = mock(PackageManager.class); when(mMockContext.getSystemService(Context.MEDIA_SESSION_SERVICE)) - .thenReturn(mMediaSessionManager); + .thenReturn(mMediaSessionManager); when(mMockContext.getSystemServiceName(MediaSessionManager.class)) - .thenReturn(Context.MEDIA_SESSION_SERVICE); + .thenReturn(Context.MEDIA_SESSION_SERVICE); mMediaPlayerList = - new MediaPlayerList(Looper.myLooper(), InstrumentationRegistry.getTargetContext()); + new MediaPlayerList(Looper.myLooper(), InstrumentationRegistry.getTargetContext()); when(mMockContext.registerReceiver(any(), any())).thenReturn(null); when(mMockContext.getApplicationContext()).thenReturn(mMockContext); @@ -115,7 +115,6 @@ public class MediaPlayerListTest { public void tearDown() throws Exception { BrowsablePlayerConnector.setInstanceForTesting(null); - MediaControllerFactory.inject(null); MediaPlayerWrapperFactory.inject(null); mMediaPlayerList.cleanup(); @@ -129,10 +128,7 @@ public class MediaPlayerListTest { builder.setState(playbackState, 0, 1); ArrayList list = new ArrayList(); list.add(Util.empty_data()); - MediaData newData = new MediaData( - Util.empty_data(), - builder.build(), - list); + MediaData newData = new MediaData(Util.empty_data(), builder.build(), list); return newData; } @@ -141,7 +137,8 @@ public class MediaPlayerListTest { public void testUpdateMeidaDataForAudioPlaybackWhenAcitvePlayNotPlaying() { // Verify update media data with playing state doReturn(prepareMediaData(PlaybackState.STATE_PAUSED)) - .when(mMockPlayerWrapper).getCurrentMediaData(); + .when(mMockPlayerWrapper) + .getCurrentMediaData(); mMediaPlayerList.injectAudioPlaybacActive(true); verify(mMediaUpdateCallback).run(mMediaUpdateData.capture()); MediaData data = mMediaUpdateData.getValue(); @@ -173,7 +170,8 @@ public class MediaPlayerListTest { public void testNotUdpateMediaDataForAudioPlaybackWhenActivePlayerIsPlaying() { // Verify not update media data for Audio Playback when active player is playing doReturn(prepareMediaData(PlaybackState.STATE_PLAYING)) - .when(mMockPlayerWrapper).getCurrentMediaData(); + .when(mMockPlayerWrapper) + .getCurrentMediaData(); mMediaPlayerList.injectAudioPlaybacActive(true); mMediaPlayerList.injectAudioPlaybacActive(false); verify(mMediaUpdateCallback, never()).run(any()); @@ -182,7 +180,8 @@ public class MediaPlayerListTest { @Test public void testNotUdpateMediaDataForActivePlayerWhenAudioPlaybackIsActive() { doReturn(prepareMediaData(PlaybackState.STATE_PLAYING)) - .when(mMockPlayerWrapper).getCurrentMediaData(); + .when(mMockPlayerWrapper) + .getCurrentMediaData(); mMediaPlayerList.injectAudioPlaybacActive(true); verify(mMediaUpdateCallback, never()).run(any()); @@ -197,11 +196,13 @@ public class MediaPlayerListTest { MediaPlayerWrapper activeMediaPlayer = mMediaPlayerList.getActivePlayer(); // Create MediaSession with GLOBAL_PRIORITY flag. - MediaSession session = new MediaSession( - InstrumentationRegistry.getTargetContext(), - MediaPlayerListTest.class.getSimpleName()); - session.setFlags(MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY - | MediaSession.FLAG_HANDLES_MEDIA_BUTTONS); + MediaSession session = + new MediaSession( + InstrumentationRegistry.getTargetContext(), + MediaPlayerListTest.class.getSimpleName()); + session.setFlags( + MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY + | MediaSession.FLAG_HANDLES_MEDIA_BUTTONS); // Use MediaPlayerList onMediaKeyEventSessionChanged callback to send the new session. mMediaPlayerList.mMediaKeyEventSessionChangedListener.onMediaKeyEventSessionChanged( @@ -210,12 +211,11 @@ public class MediaPlayerListTest { // Retrieve the current available controllers ArrayList currentControllers = new ArrayList( - mMediaSessionManager.getActiveSessions(null)); + mMediaSessionManager.getActiveSessions(null)); // Add the new session currentControllers.add(session.getController()); // Use MediaPlayerList onActiveSessionsChanged callback to send the new session. - mMediaPlayerList.mActiveSessionsChangedListener.onActiveSessionsChanged( - currentControllers); + mMediaPlayerList.mActiveSessionsChangedListener.onActiveSessionsChanged(currentControllers); // Retrieve the new active MediaSession. MediaPlayerWrapper newActiveMediaPlayer = mMediaPlayerList.getActivePlayer(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerWrapperTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerWrapperTest.java index 45039686838..719c65d6eb8 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerWrapperTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerWrapperTest.java @@ -94,8 +94,8 @@ public class MediaPlayerWrapperTest { @Before public void setUp() { - mTestResources = TestUtils.getTestApplicationResources( - InstrumentationRegistry.getTargetContext()); + mTestResources = + TestUtils.getTestApplicationResources(InstrumentationRegistry.getTargetContext()); mTestBitmap = loadImage(com.android.bluetooth.tests.R.raw.image_200_200); when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(true); @@ -375,7 +375,9 @@ public class MediaPlayerWrapperTest { // Assert that the metadata returned by getMetadata() is used instead of null verify(mTestCbs, times(1)).mediaUpdatedCallback(mMediaUpdateData.capture()); MediaData data = mMediaUpdateData.getValue(); - Assert.assertEquals("Returned metadata is incorrect", data.metadata, + Assert.assertEquals( + "Returned metadata is incorrect", + data.metadata, Util.toMetadata(mMockContext, mTestMetadata.build())); } @@ -473,15 +475,19 @@ public class MediaPlayerWrapperTest { MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); doReturn(null).when(mMockController).getMetadata(); - Assert.assertFalse(Util.toMetadata(mMockContext, mTestMetadata.build()).duration - .equals(wrapper.getCurrentQueue().get(0).duration)); + Assert.assertFalse( + Util.toMetadata(mMockContext, mTestMetadata.build()) + .duration + .equals(wrapper.getCurrentQueue().get(0).duration)); doReturn(mTestMetadata.build()).when(mMockController).getMetadata(); - Assert.assertEquals(Util.toMetadata(mMockContext, mTestMetadata.build()).duration, + Assert.assertEquals( + Util.toMetadata(mMockContext, mTestMetadata.build()).duration, wrapper.getCurrentQueue().get(0).duration); // The MediaController Metadata should still not be equal to the queue // as the track count is different and should not be overridden. - Assert.assertFalse(Util.toMetadata(mMockContext, mTestMetadata.build()) - .equals(wrapper.getCurrentQueue().get(0))); + Assert.assertFalse( + Util.toMetadata(mMockContext, mTestMetadata.build()) + .equals(wrapper.getCurrentQueue().get(0))); } /* @@ -536,7 +542,6 @@ public class MediaPlayerWrapperTest { doReturn(mTestState.build()).when(mMockController).getPlaybackState(); controllerCallbacks.onPlaybackStateChanged(mTestState.build()); - // Verify that there are no timeout messages pending and there were no timeouts Assert.assertFalse(wrapper.getTimeoutHandler().hasMessages(MSG_TIMEOUT)); verify(mFailHandler, never()).onTerribleFailure(any(), any(), anyBoolean()); @@ -771,7 +776,8 @@ public class MediaPlayerWrapperTest { "Returned PlaybackState isn't equal to given PlaybackState", data.state.toString(), s.build().toString()); - Assert.assertEquals("Returned Queue isn't equal to given Queue", + Assert.assertEquals( + "Returned Queue isn't equal to given Queue", data.queue, Util.toMetadataList(mMockContext, q)); } @@ -783,8 +789,8 @@ public class MediaPlayerWrapperTest { @Test public void pauseCurrent() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); MediaPlayerWrapper wrapper = MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); @@ -796,8 +802,8 @@ public class MediaPlayerWrapperTest { @Test public void playCurrent() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); MediaPlayerWrapper wrapper = MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); @@ -809,8 +815,8 @@ public class MediaPlayerWrapperTest { @Test public void playItemFromQueue() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); when(mMockController.getQueue()).thenReturn(new ArrayList<>()); MediaPlayerWrapper wrapper = @@ -824,8 +830,8 @@ public class MediaPlayerWrapperTest { @Test public void rewind() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); MediaPlayerWrapper wrapper = MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); @@ -837,8 +843,8 @@ public class MediaPlayerWrapperTest { @Test public void seekTo() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); MediaPlayerWrapper wrapper = MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); @@ -851,8 +857,8 @@ public class MediaPlayerWrapperTest { @Test public void setPlaybackSpeed() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); MediaPlayerWrapper wrapper = MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); @@ -865,8 +871,8 @@ public class MediaPlayerWrapperTest { @Test public void skipToNext() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); MediaPlayerWrapper wrapper = MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); @@ -878,8 +884,8 @@ public class MediaPlayerWrapperTest { @Test public void skipToPrevious() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); MediaPlayerWrapper wrapper = MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); @@ -891,8 +897,8 @@ public class MediaPlayerWrapperTest { @Test public void stopCurrent() { - MediaController.TransportControls transportControls - = mock(MediaController.TransportControls.class); + MediaController.TransportControls transportControls = + mock(MediaController.TransportControls.class); when(mMockController.getTransportControls()).thenReturn(transportControls); MediaPlayerWrapper wrapper = MediaPlayerWrapperFactory.wrap(mMockContext, mMockController, mThread.getLooper()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java index 8b8940815e4..47d65269fa9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java @@ -65,15 +65,15 @@ public class MetadataTest { private MockContentResolver mTestContentResolver; private static final String TEST_AUTHORITY = "com.android.bluetooth.avrcp.test"; - private static final Uri TEST_CONTENT_URI = new Uri.Builder() - .scheme(ContentResolver.SCHEME_CONTENT) - .authority(TEST_AUTHORITY) - .build(); + private static final Uri TEST_CONTENT_URI = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(TEST_AUTHORITY) + .build(); private static final String IMAGE_HANDLE_1 = "0000001"; - private static final Uri IMAGE_URI_1 = TEST_CONTENT_URI.buildUpon() - .appendQueryParameter("handle", IMAGE_HANDLE_1) - .build(); + private static final Uri IMAGE_URI_1 = + TEST_CONTENT_URI.buildUpon().appendQueryParameter("handle", IMAGE_HANDLE_1).build(); private static final String IMAGE_STRING_1 = IMAGE_URI_1.toString(); private static final Image DEFAULT_IMAGE = null; @@ -100,17 +100,20 @@ public class MetadataTest { mTestBitmap2 = loadImage(com.android.bluetooth.tests.R.raw.image_200_200_blue); mTestContentResolver = new MockContentResolver(mTargetContext); - mTestContentResolver.addProvider(TEST_AUTHORITY, new MockContentProvider() { - @Override - public AssetFileDescriptor openTypedAssetFile(Uri url, String mimeType, Bundle opts) { - String handle = url.getQueryParameter("handle"); - if (IMAGE_URI_1.equals(url)) { - return mTestResources.openRawResourceFd( - com.android.bluetooth.tests.R.raw.image_200_200); - } - return null; - } - }); + mTestContentResolver.addProvider( + TEST_AUTHORITY, + new MockContentProvider() { + @Override + public AssetFileDescriptor openTypedAssetFile( + Uri url, String mimeType, Bundle opts) { + String handle = url.getQueryParameter("handle"); + if (IMAGE_URI_1.equals(url)) { + return mTestResources.openRawResourceFd( + com.android.bluetooth.tests.R.raw.image_200_200); + } + return null; + } + }); when(mMockContext.getContentResolver()).thenReturn(mTestContentResolver); when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(true); @@ -136,52 +139,69 @@ public class MetadataTest { } private MediaMetadata getMediaMetadata() { - MediaMetadata.Builder builder = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) - .putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE) - .putString(MediaMetadata.METADATA_KEY_ARTIST, SONG_ARTIST) - .putString(MediaMetadata.METADATA_KEY_ALBUM, SONG_ALBUM) - .putLong(MediaMetadata.METADATA_KEY_TRACK_NUMBER, Long.parseLong(SONG_TRACK_NUM)) - .putLong(MediaMetadata.METADATA_KEY_NUM_TRACKS, Long.parseLong(SONG_NUM_TRACKS)) - .putString(MediaMetadata.METADATA_KEY_GENRE, SONG_GENRE) - .putLong(MediaMetadata.METADATA_KEY_DURATION, Long.parseLong(SONG_DURATION)); + MediaMetadata.Builder builder = + new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) + .putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE) + .putString(MediaMetadata.METADATA_KEY_ARTIST, SONG_ARTIST) + .putString(MediaMetadata.METADATA_KEY_ALBUM, SONG_ALBUM) + .putLong( + MediaMetadata.METADATA_KEY_TRACK_NUMBER, + Long.parseLong(SONG_TRACK_NUM)) + .putLong( + MediaMetadata.METADATA_KEY_NUM_TRACKS, + Long.parseLong(SONG_NUM_TRACKS)) + .putString(MediaMetadata.METADATA_KEY_GENRE, SONG_GENRE) + .putLong( + MediaMetadata.METADATA_KEY_DURATION, Long.parseLong(SONG_DURATION)); return builder.build(); } private MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { - MediaMetadata.Builder builder = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) - .putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE) - .putString(MediaMetadata.METADATA_KEY_ARTIST, SONG_ARTIST) - .putString(MediaMetadata.METADATA_KEY_ALBUM, SONG_ALBUM) - .putLong(MediaMetadata.METADATA_KEY_TRACK_NUMBER, Long.parseLong(SONG_TRACK_NUM)) - .putLong(MediaMetadata.METADATA_KEY_NUM_TRACKS, Long.parseLong(SONG_NUM_TRACKS)) - .putString(MediaMetadata.METADATA_KEY_GENRE, SONG_GENRE) - .putLong(MediaMetadata.METADATA_KEY_DURATION, Long.parseLong(SONG_DURATION)) - .putBitmap(field, image); + MediaMetadata.Builder builder = + new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) + .putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE) + .putString(MediaMetadata.METADATA_KEY_ARTIST, SONG_ARTIST) + .putString(MediaMetadata.METADATA_KEY_ALBUM, SONG_ALBUM) + .putLong( + MediaMetadata.METADATA_KEY_TRACK_NUMBER, + Long.parseLong(SONG_TRACK_NUM)) + .putLong( + MediaMetadata.METADATA_KEY_NUM_TRACKS, + Long.parseLong(SONG_NUM_TRACKS)) + .putString(MediaMetadata.METADATA_KEY_GENRE, SONG_GENRE) + .putLong(MediaMetadata.METADATA_KEY_DURATION, Long.parseLong(SONG_DURATION)) + .putBitmap(field, image); return builder.build(); } private MediaMetadata getMediaMetadataWithUri(String field, Uri uri) { - MediaMetadata.Builder builder = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) - .putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE) - .putString(MediaMetadata.METADATA_KEY_ARTIST, SONG_ARTIST) - .putString(MediaMetadata.METADATA_KEY_ALBUM, SONG_ALBUM) - .putLong(MediaMetadata.METADATA_KEY_TRACK_NUMBER, Long.parseLong(SONG_TRACK_NUM)) - .putLong(MediaMetadata.METADATA_KEY_NUM_TRACKS, Long.parseLong(SONG_NUM_TRACKS)) - .putString(MediaMetadata.METADATA_KEY_GENRE, SONG_GENRE) - .putLong(MediaMetadata.METADATA_KEY_DURATION, Long.parseLong(SONG_DURATION)) - .putString(field, uri.toString()); + MediaMetadata.Builder builder = + new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) + .putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE) + .putString(MediaMetadata.METADATA_KEY_ARTIST, SONG_ARTIST) + .putString(MediaMetadata.METADATA_KEY_ALBUM, SONG_ALBUM) + .putLong( + MediaMetadata.METADATA_KEY_TRACK_NUMBER, + Long.parseLong(SONG_TRACK_NUM)) + .putLong( + MediaMetadata.METADATA_KEY_NUM_TRACKS, + Long.parseLong(SONG_NUM_TRACKS)) + .putString(MediaMetadata.METADATA_KEY_GENRE, SONG_GENRE) + .putLong(MediaMetadata.METADATA_KEY_DURATION, Long.parseLong(SONG_DURATION)) + .putString(field, uri.toString()); return builder.build(); } private MediaDescription getMediaDescription(Bitmap bitmap, Uri uri, Bundle extras) { - MediaDescription.Builder builder = new MediaDescription.Builder() - .setMediaId(SONG_MEDIA_ID) - .setTitle(SONG_TITLE) - .setSubtitle(SONG_ARTIST) - .setDescription(SONG_ALBUM); + MediaDescription.Builder builder = + new MediaDescription.Builder() + .setMediaId(SONG_MEDIA_ID) + .setTitle(SONG_TITLE) + .setSubtitle(SONG_ARTIST) + .setDescription(SONG_ALBUM); if (bitmap != null) { builder.setIconBitmap(bitmap); } @@ -227,9 +247,17 @@ public class MetadataTest { return bundle; } - private void assertMetadata(String mediaId, String title, String artist, String album, - String trackNum, String numTracks, String genre, String duration, - Image image, Metadata metadata) { + private void assertMetadata( + String mediaId, + String title, + String artist, + String album, + String trackNum, + String numTracks, + String genre, + String duration, + Image image, + Metadata metadata) { assertThat(metadata.mediaId).isEqualTo(mediaId); assertThat(metadata.title).isEqualTo(title); assertThat(metadata.artist).isEqualTo(artist); @@ -241,157 +269,210 @@ public class MetadataTest { Assert.assertTrue(Image.sameAs(metadata.image, image)); } - /** - * Make sure the media ID we set is transferred to Metadata object we build - */ + /** Make sure the media ID we set is transferred to Metadata object we build */ @Test public void testBuildMetadataSetMediaId() { Metadata metadata = new Metadata.Builder().setMediaId(SONG_MEDIA_ID).build(); assertMetadata(SONG_MEDIA_ID, null, null, null, null, null, null, null, null, metadata); } - /** - * Make sure you can build a Metadata from a MediaMetadata that has no art - */ + /** Make sure you can build a Metadata from a MediaMetadata that has no art */ @Test public void testBuildMetadataFromMediaMetadata() { MediaMetadata m = getMediaMetadata(); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, null, metadata); - } - - /** - * Make sure you can build a Metadata from a MediaMetadata that has bitmap art - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + null, + metadata); + } + + /** Make sure you can build a Metadata from a MediaMetadata that has bitmap art */ @Test public void testBuildMetadataFromMediaMetadataWithArt() { - MediaMetadata m = - getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); + MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make sure you can build a Metadata from a MediaMetadata that has bitmap album art - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make sure you can build a Metadata from a MediaMetadata that has bitmap album art */ @Test public void testBuildMetadataFromMediaMetadataWithAlbumArt() { MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make sure you can build a Metadata from a MediaMetadata that a display icon - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make sure you can build a Metadata from a MediaMetadata that a display icon */ @Test public void testBuildMetadataFromMediaMetadataWithDisplayIcon() { MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make sure you can build a Metadata from a MediaMetadata that has Uri based art - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make sure you can build a Metadata from a MediaMetadata that has Uri based art */ @Test public void testBuildMetadataFromMediaMetadataWithUriArt() { - MediaMetadata m = - getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromMediaMetadata(m) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make sure you can build a Metadata from a MediaMetadata that has Uri based album art - */ + MediaMetadata m = getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_URI_1); + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromMediaMetadata(m).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make sure you can build a Metadata from a MediaMetadata that has Uri based album art */ @Test public void testBuildMetadataFromMediaMetadataWithUriAlbumArt() { MediaMetadata m = getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ALBUM_ART_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromMediaMetadata(m) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make sure you can build a Metadata from a MediaMetadata that has a Uri based display icon - */ + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromMediaMetadata(m).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make sure you can build a Metadata from a MediaMetadata that has a Uri based display icon */ @Test public void testBuildMetadataFromMediaMetadataWithUriDisplayIcon() { MediaMetadata m = getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromMediaMetadata(m) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make sure we're robust to build attempts that include Uri based art without a context - */ + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromMediaMetadata(m).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make sure we're robust to build attempts that include Uri based art without a context */ @Test public void testBuildMetadataFromMediaMetadataWithUriNoContext() { - MediaMetadata m = - getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .fromMediaMetadata(m) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, null, metadata); + MediaMetadata m = getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_URI_1); + Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + null, + metadata); } /** - * Make sure building with a MediaMetadata that contains URI art when URI art is disabled - * yields no cover art. + * Make sure building with a MediaMetadata that contains URI art when URI art is disabled yields + * no cover art. */ @Test public void testBuildMetadataFromMediaMetadataWithUriAndUrisDisabled() { - when(mMockResources.getBoolean( - R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); - MediaMetadata m = - getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromMediaMetadata(m) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, null, metadata); - } - - /** - * Make sure we're robust to building with a null MediaMetadata - */ + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); + MediaMetadata m = getMediaMetadataWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_URI_1); + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromMediaMetadata(m).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + null, + metadata); + } + + /** Make sure we're robust to building with a null MediaMetadata */ @Test public void testBuildMetadataFromNullMediaMetadata() { Metadata metadata = new Metadata.Builder().fromMediaMetadata(null).build(); assertMetadata(null, null, null, null, null, null, null, null, null, metadata); } - /** - * Make sure you can create a Metadata from a simple MediaDescription - */ + /** Make sure you can create a Metadata from a simple MediaDescription */ @Test public void testBuildMetadataFromMediaDescription() { MediaDescription description = getMediaDescription(null, null, null); Metadata metadata = new Metadata.Builder().fromMediaDescription(description).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - null, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + null, + metadata); } /** @@ -402,34 +483,60 @@ public class MetadataTest { public void testBuildMetadataFromMediaDescriptionWithIconArt() { MediaDescription description = getMediaDescription(mTestBitmap, null, null); Metadata metadata = new Metadata.Builder().fromMediaDescription(description).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - mSongImage, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + mSongImage, + metadata); } /** - * Make sure you can create a Metadata from a MediaDescription that contains cover artwork as - * an icon Uri + * Make sure you can create a Metadata from a MediaDescription that contains cover artwork as an + * icon Uri */ @Test public void testBuildMetadataFromMediaDescriptionWithIconUri() { MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromMediaDescription(description) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - mSongImage, metadata); - } - - /** - * Make sure we're robust to attempts to create Uri based images without a context set - */ + Metadata metadata = + new Metadata.Builder() + .useContext(mMockContext) + .fromMediaDescription(description) + .build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + mSongImage, + metadata); + } + + /** Make sure we're robust to attempts to create Uri based images without a context set */ @Test public void testBuildMetadataFromMediaDescriptionWithArtNullContext() { MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null); Metadata metadata = new Metadata.Builder().fromMediaDescription(description).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - null, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + null, + metadata); } /** @@ -441,13 +548,20 @@ public class MetadataTest { Bundle extras = getBundleWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); MediaDescription description = getMediaDescription(null, null, extras); Metadata metadata = new Metadata.Builder().fromMediaDescription(description).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make sure we're robust to null MediaDescriptions - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make sure we're robust to null MediaDescriptions */ @Test public void testBuildMetadataFromNullMediaDescription() { Metadata metadata = new Metadata.Builder().fromMediaDescription(null).build(); @@ -461,8 +575,17 @@ public class MetadataTest { public void testBuildMetadataFromBundle() { Bundle bundle = getBundle(); Metadata metadata = new Metadata.Builder().fromBundle(bundle).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, null, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + null, + metadata); } /** @@ -473,8 +596,17 @@ public class MetadataTest { public void testBuildMetadataFromBundleWithArt() { Bundle bundle = getBundleWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromBundle(bundle).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); } /** @@ -485,8 +617,17 @@ public class MetadataTest { public void testBuildMetadataFromBundleWithAlbumArt() { Bundle bundle = getBundleWithBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromBundle(bundle).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); } /** @@ -497,8 +638,17 @@ public class MetadataTest { public void testBuildMetadataFromBundleWithDisplayIcon() { Bundle bundle = getBundleWithBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON, mTestBitmap); Metadata metadata = new Metadata.Builder().fromBundle(bundle).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); } /** @@ -508,12 +658,19 @@ public class MetadataTest { @Test public void testBuildMetadataFromBundleWithUriArt() { Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_ART_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromBundle(bundle) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromBundle(bundle).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); } /** @@ -523,12 +680,19 @@ public class MetadataTest { @Test public void testBuildMetadataFromBundleWithUriAlbumArt() { Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_ALBUM_ART_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromBundle(bundle) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromBundle(bundle).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); } /** @@ -538,12 +702,19 @@ public class MetadataTest { @Test public void testBuildMetadataFromBundleWithUriDisplayIcon() { Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromBundle(bundle) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromBundle(bundle).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); } /** @@ -552,11 +723,18 @@ public class MetadataTest { @Test public void testBuildMetadataFromBundleWithUriNoContext() { Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .fromBundle(bundle) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, null, metadata); + Metadata metadata = new Metadata.Builder().fromBundle(bundle).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + null, + metadata); } /** @@ -565,20 +743,24 @@ public class MetadataTest { */ @Test public void testBuildMetadataFromBundleWithUriAndUrisDisabled() { - when(mMockResources.getBoolean( - R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); Bundle bundle = getBundleWithUri(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, IMAGE_URI_1); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromBundle(bundle) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, null, metadata); - } - - /** - * Make sure we're robust to empty Bundles - */ + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromBundle(bundle).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + null, + metadata); + } + + /** Make sure we're robust to empty Bundles */ @Test public void testBuildMetadataFromEmptyBundle() { Bundle bundle = new Bundle(); @@ -586,64 +768,88 @@ public class MetadataTest { assertMetadata(null, null, null, null, null, null, null, null, null, metadata); } - /** - * Make sure we're robust to null Bundles - */ + /** Make sure we're robust to null Bundles */ @Test public void testBuildMetadataFromNullBundle() { Metadata metadata = new Metadata.Builder().fromBundle(null).build(); assertMetadata(null, null, null, null, null, null, null, null, null, metadata); } - /** - * Make a Metadata with a simple MediaItem - */ + /** Make a Metadata with a simple MediaItem */ @Test public void testBuildMetadataFromMediaItem() { MediaDescription description = getMediaDescription(null, null, null); MediaItem item = getMediaItem(description); Metadata metadata = new Metadata.Builder().fromMediaItem(item).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - null, metadata); - } - - /** - * Make a Metadata with a MediaItem that has icon art - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + null, + metadata); + } + + /** Make a Metadata with a MediaItem that has icon art */ @Test public void testBuildMetadataFromMediaItemWithIconArt() { MediaDescription description = getMediaDescription(mTestBitmap, null, null); MediaItem item = getMediaItem(description); Metadata metadata = new Metadata.Builder().fromMediaItem(item).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - mSongImage, metadata); - } - - /** - * Make a Metadata with a MediaItem that has an icon uri - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + mSongImage, + metadata); + } + + /** Make a Metadata with a MediaItem that has an icon uri */ @Test public void testBuildMetadataFromMediaItemWithIconUri() { MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null); MediaItem item = getMediaItem(description); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromMediaItem(item) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - mSongImage, metadata); - } - - /** - * Make a Metadata with a MediaItem that has an icon uri, but don't use a context - */ + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromMediaItem(item).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + mSongImage, + metadata); + } + + /** Make a Metadata with a MediaItem that has an icon uri, but don't use a context */ @Test public void testBuildMetadataFromMediaItemWithIconUriNoContext() { MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null); MediaItem item = getMediaItem(description); Metadata metadata = new Metadata.Builder().fromMediaItem(item).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - null, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + null, + metadata); } /** @@ -652,125 +858,173 @@ public class MetadataTest { */ @Test public void testBuildMetadataFromMediaItemWithIconUriAndUrisDisabled() { - when(mMockResources.getBoolean( - R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null); MediaItem item = getMediaItem(description); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromMediaItem(item) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - null, metadata); - } - - /** - * Make a Metadata with a MediaItem that has extras - */ + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromMediaItem(item).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + null, + metadata); + } + + /** Make a Metadata with a MediaItem that has extras */ @Test public void testBuildMetadataFromMediaItemWithExtras() { Bundle extras = getBundleWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); MediaDescription description = getMediaDescription(null, null, extras); MediaItem item = getMediaItem(description); Metadata metadata = new Metadata.Builder().fromMediaItem(item).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make a Metadata with a null MediaItem - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make a Metadata with a null MediaItem */ @Test public void testBuildMetadataFromNullMediaItem() { Metadata metadata = new Metadata.Builder().fromMediaItem(null).build(); assertMetadata(null, null, null, null, null, null, null, null, null, metadata); } - /** - * Make a Metadata from a simple QueueItem - */ + /** Make a Metadata from a simple QueueItem */ @Test public void testBuildMetadataFromQueueItem() { MediaDescription description = getMediaDescription(null, null, null); QueueItem queueItem = getQueueItem(description); Metadata metadata = new Metadata.Builder().fromQueueItem(queueItem).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - null, metadata); - } - - /** - * Make a Metadata from a QueueItem with icon art - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + null, + metadata); + } + + /** Make a Metadata from a QueueItem with icon art */ @Test public void testBuildMetadataFromQueueItemWithIconArt() { MediaDescription description = getMediaDescription(mTestBitmap, null, null); QueueItem queueItem = getQueueItem(description); Metadata metadata = new Metadata.Builder().fromQueueItem(queueItem).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - mSongImage, metadata); - } - - /** - * Make a Metadata from a QueueItem with an icon uri - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + mSongImage, + metadata); + } + + /** Make a Metadata from a QueueItem with an icon uri */ @Test public void testBuildMetadataFromQueueItemWithIconUri() { MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null); QueueItem queueItem = getQueueItem(description); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromQueueItem(queueItem) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - mSongImage, metadata); - } - - /** - * Make a Metadata from a QueueItem with an icon uri, but don't use a context - */ + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromQueueItem(queueItem).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + mSongImage, + metadata); + } + + /** Make a Metadata from a QueueItem with an icon uri, but don't use a context */ @Test public void testBuildMetadataFromQueueItemWithIconUriNoContext() { MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null); QueueItem queueItem = getQueueItem(description); Metadata metadata = new Metadata.Builder().fromQueueItem(queueItem).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - null, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + null, + metadata); } /** - * Make sure building with a QueueItem that contains URI art when URI art is disabled yields - * no cover art. + * Make sure building with a QueueItem that contains URI art when URI art is disabled yields no + * cover art. */ @Test public void testBuildMetadataFromQueueItemWithIconUriandUrisDisabled() { - when(mMockResources.getBoolean( - R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); + when(mMockResources.getBoolean(R.bool.avrcp_target_cover_art_uri_images)).thenReturn(false); MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null); QueueItem queueItem = getQueueItem(description); - Metadata metadata = new Metadata.Builder() - .useContext(mMockContext) - .fromQueueItem(queueItem) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, null, null, null, null, - null, metadata); - } - - /** - * Make a Metadata from a QueueItem with extras - */ + Metadata metadata = + new Metadata.Builder().useContext(mMockContext).fromQueueItem(queueItem).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + null, + null, + null, + null, + null, + metadata); + } + + /** Make a Metadata from a QueueItem with extras */ @Test public void testBuildMetadataFromQueueItemWithExtras() { Bundle extras = getBundleWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); MediaDescription description = getMediaDescription(null, null, extras); QueueItem queueItem = getQueueItem(description); Metadata metadata = new Metadata.Builder().fromQueueItem(queueItem).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); - } - - /** - * Make a Metadata with a null QueueItem - */ + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); + } + + /** Make a Metadata with a null QueueItem */ @Test public void testBuildMetadataFromNullQueueItem() { Metadata metadata = new Metadata.Builder().fromQueueItem(null).build(); @@ -783,9 +1037,17 @@ public class MetadataTest { @Test public void testBuildMetadataUseDefaults() { Metadata metadata = new Metadata.Builder().useDefaults().build(); - assertMetadata(Metadata.EMPTY_MEDIA_ID, Metadata.EMPTY_TITLE, Metadata.EMPTY_ARTIST, - Metadata.EMPTY_ALBUM, Metadata.EMPTY_TRACK_NUM, Metadata.EMPTY_NUM_TRACKS, - Metadata.EMPTY_GENRE, Metadata.EMPTY_DURATION, DEFAULT_IMAGE, metadata); + assertMetadata( + Metadata.EMPTY_MEDIA_ID, + Metadata.EMPTY_TITLE, + Metadata.EMPTY_ARTIST, + Metadata.EMPTY_ALBUM, + Metadata.EMPTY_TRACK_NUM, + Metadata.EMPTY_NUM_TRACKS, + Metadata.EMPTY_GENRE, + Metadata.EMPTY_DURATION, + DEFAULT_IMAGE, + metadata); } /** @@ -795,13 +1057,19 @@ public class MetadataTest { @Test public void testBuildMetadataUseDefaultsAndPartialFields() { MediaDescription description = getMediaDescription(null, null, null); - Metadata metadata = new Metadata.Builder() - .useDefaults() - .fromMediaDescription(description) - .build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, - Metadata.EMPTY_TRACK_NUM, Metadata.EMPTY_NUM_TRACKS, Metadata.EMPTY_GENRE, - Metadata.EMPTY_DURATION, DEFAULT_IMAGE, metadata); + Metadata metadata = + new Metadata.Builder().useDefaults().fromMediaDescription(description).build(); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + Metadata.EMPTY_TRACK_NUM, + Metadata.EMPTY_NUM_TRACKS, + Metadata.EMPTY_GENRE, + Metadata.EMPTY_DURATION, + DEFAULT_IMAGE, + metadata); } /** @@ -810,11 +1078,19 @@ public class MetadataTest { */ @Test public void testBuildMetadataUseDefaultsAndAllFields() { - MediaMetadata m = - getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); + MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().useDefaults().fromMediaMetadata(m).build(); - assertMetadata(SONG_MEDIA_ID, SONG_TITLE, SONG_ARTIST, SONG_ALBUM, SONG_TRACK_NUM, - SONG_NUM_TRACKS, SONG_GENRE, SONG_DURATION, mSongImage, metadata); + assertMetadata( + SONG_MEDIA_ID, + SONG_TITLE, + SONG_ARTIST, + SONG_ALBUM, + SONG_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + SONG_DURATION, + mSongImage, + metadata); } /** @@ -829,15 +1105,23 @@ public class MetadataTest { bundle.putString(MediaMetadata.METADATA_KEY_GENRE, SONG_GENRE); bundle.putParcelable(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().useDefaults().fromBundle(bundle).build(); - assertMetadata(Metadata.EMPTY_MEDIA_ID, SONG_TITLE, Metadata.EMPTY_ARTIST, - Metadata.EMPTY_ALBUM, Metadata.EMPTY_TRACK_NUM, SONG_NUM_TRACKS, SONG_GENRE, - Metadata.EMPTY_DURATION, mSongImage, metadata); + assertMetadata( + Metadata.EMPTY_MEDIA_ID, + SONG_TITLE, + Metadata.EMPTY_ARTIST, + Metadata.EMPTY_ALBUM, + Metadata.EMPTY_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + Metadata.EMPTY_DURATION, + mSongImage, + metadata); } /** - * Build a Metadata using the defaults. Call useDefaults at the end after other fields have - * been extracted from the media framework objects. Ensure we don't overwrite existing values - * with defaults. Ensure that the metadata created is the same (by field) as the one where + * Build a Metadata using the defaults. Call useDefaults at the end after other fields have been + * extracted from the media framework objects. Ensure we don't overwrite existing values with + * defaults. Ensure that the metadata created is the same (by field) as the one where * useDefaults is called first. */ @Test @@ -849,21 +1133,34 @@ public class MetadataTest { bundle.putParcelable(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromBundle(bundle).useDefaults().build(); Metadata metadata2 = new Metadata.Builder().useDefaults().fromBundle(bundle).build(); - assertMetadata(Metadata.EMPTY_MEDIA_ID, SONG_TITLE, Metadata.EMPTY_ARTIST, - Metadata.EMPTY_ALBUM, Metadata.EMPTY_TRACK_NUM, SONG_NUM_TRACKS, SONG_GENRE, - Metadata.EMPTY_DURATION, mSongImage, metadata); - assertMetadata(Metadata.EMPTY_MEDIA_ID, SONG_TITLE, Metadata.EMPTY_ARTIST, - Metadata.EMPTY_ALBUM, Metadata.EMPTY_TRACK_NUM, SONG_NUM_TRACKS, SONG_GENRE, - Metadata.EMPTY_DURATION, mSongImage, metadata2); - } - - /** - * Make sure you can clone a Metadata - */ + assertMetadata( + Metadata.EMPTY_MEDIA_ID, + SONG_TITLE, + Metadata.EMPTY_ARTIST, + Metadata.EMPTY_ALBUM, + Metadata.EMPTY_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + Metadata.EMPTY_DURATION, + mSongImage, + metadata); + assertMetadata( + Metadata.EMPTY_MEDIA_ID, + SONG_TITLE, + Metadata.EMPTY_ARTIST, + Metadata.EMPTY_ALBUM, + Metadata.EMPTY_TRACK_NUM, + SONG_NUM_TRACKS, + SONG_GENRE, + Metadata.EMPTY_DURATION, + mSongImage, + metadata2); + } + + /** Make sure you can clone a Metadata */ @Test public void testClone() { - MediaMetadata m = - getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); + MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); Metadata metadata2 = metadata.clone(); assertThat(metadata.mediaId).isEqualTo(metadata2.mediaId); @@ -878,74 +1175,57 @@ public class MetadataTest { assertThat(metadata).isEqualTo(metadata2); } - /** - * Make sure two Metadata objects are different if title doesn't match - */ + /** Make sure two Metadata objects are different if title doesn't match */ @Test public void testEqualsDifferentTitle() { - MediaMetadata m = - getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); + MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); Metadata metadata2 = metadata.clone(); metadata2.title = null; assertThat(metadata).isNotEqualTo(metadata2); } - /** - * Make sure two Metadata objects are different if artist doesn't match - */ + /** Make sure two Metadata objects are different if artist doesn't match */ @Test public void testEqualsDifferentArtist() { - MediaMetadata m = - getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); + MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); Metadata metadata2 = metadata.clone(); metadata2.artist = Metadata.EMPTY_ARTIST; assertThat(metadata).isNotEqualTo(metadata2); } - /** - * Make sure two Metadata objects are different if album doesn't match - */ + /** Make sure two Metadata objects are different if album doesn't match */ @Test public void testEqualsDifferentAlbum() { - MediaMetadata m = - getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); + MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); Metadata metadata2 = metadata.clone(); metadata2.album = Metadata.EMPTY_ALBUM; assertThat(metadata).isNotEqualTo(metadata2); } - /** - * Make sure two Metadata objects are different if trackNum doesn't match - */ + /** Make sure two Metadata objects are different if trackNum doesn't match */ @Test public void testEqualsDifferentTrackNum() { - MediaMetadata m = - getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); + MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); Metadata metadata2 = metadata.clone(); metadata2.trackNum = Metadata.EMPTY_TRACK_NUM; assertThat(metadata).isNotEqualTo(metadata2); } - /** - * Make sure two Metadata objects are different if numTracks doesn't match - */ + /** Make sure two Metadata objects are different if numTracks doesn't match */ @Test public void testEqualsDifferentNumTracks() { - MediaMetadata m = - getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); + MediaMetadata m = getMediaMetadataWithBitmap(MediaMetadata.METADATA_KEY_ART, mTestBitmap); Metadata metadata = new Metadata.Builder().fromMediaMetadata(m).build(); Metadata metadata2 = metadata.clone(); metadata2.numTracks = Metadata.EMPTY_NUM_TRACKS; assertThat(metadata).isNotEqualTo(metadata2); } - /** - * Make sure you can get any non-null string representation of Metadata - */ + /** Make sure you can get any non-null string representation of Metadata */ @Test public void testToString() { Metadata metadata = new Metadata.Builder().build(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/UtilTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/UtilTest.java index cbae50e01a3..27ec1fcd9fa 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/UtilTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/UtilTest.java @@ -47,8 +47,10 @@ public class UtilTest { @Test public void getDisplayName() throws Exception { PackageManager manager = mContext.getPackageManager(); - String displayName = manager.getApplicationLabel( - manager.getApplicationInfo(mContext.getPackageName(), 0)).toString(); + String displayName = + manager.getApplicationLabel( + manager.getApplicationInfo(mContext.getPackageName(), 0)) + .toString(); assertThat(Util.getDisplayName(mContext, mContext.getPackageName())).isEqualTo(displayName); String invalidPackage = "invalidPackage"; @@ -57,8 +59,8 @@ public class UtilTest { @Test public void toMetadata_withMediaItem() { - Metadata metadata = Util.toMetadata(mContext, - new MediaBrowser.MediaItem(createDescription(), 0)); + Metadata metadata = + Util.toMetadata(mContext, new MediaBrowser.MediaItem(createDescription(), 0)); assertThat(metadata.mediaId).isEqualTo(SONG_MEDIA_ID); assertThat(metadata.title).isEqualTo(SONG_TITLE); assertThat(metadata.artist).isEqualTo(SONG_ARTIST); @@ -69,8 +71,8 @@ public class UtilTest { public void toMetadata_withQueueItem() { // This will change the media ID to NOW_PLAYING_PREFIX ('NowPlayingId') + the given id long queueId = 1; - Metadata metadata = Util.toMetadata(mContext, - new MediaSession.QueueItem(createDescription(), queueId)); + Metadata metadata = + Util.toMetadata(mContext, new MediaSession.QueueItem(createDescription(), queueId)); assertThat(metadata.mediaId).isEqualTo(Util.NOW_PLAYING_PREFIX + queueId); assertThat(metadata.title).isEqualTo(SONG_TITLE); assertThat(metadata.artist).isEqualTo(SONG_ARTIST); @@ -79,11 +81,12 @@ public class UtilTest { @Test public void toMetadata_withMediaMetadata() { - MediaMetadata.Builder builder = new MediaMetadata.Builder() - .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) - .putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE) - .putString(MediaMetadata.METADATA_KEY_ARTIST, SONG_ARTIST) - .putString(MediaMetadata.METADATA_KEY_ALBUM, SONG_ALBUM); + MediaMetadata.Builder builder = + new MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) + .putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE) + .putString(MediaMetadata.METADATA_KEY_ARTIST, SONG_ARTIST) + .putString(MediaMetadata.METADATA_KEY_ALBUM, SONG_ALBUM); // This will change the media ID to "currsong". Metadata metadata = Util.toMetadata(mContext, builder.build()); assertThat(metadata.mediaId).isEqualTo("currsong"); @@ -123,16 +126,16 @@ public class UtilTest { assertThat(PlayStatus.playbackStateToAvrcpState(PlaybackState.STATE_ERROR)) .isEqualTo(PlayStatus.ERROR); - assertThat(PlayStatus.playbackStateToAvrcpState(-100)) - .isEqualTo(PlayStatus.ERROR); + assertThat(PlayStatus.playbackStateToAvrcpState(-100)).isEqualTo(PlayStatus.ERROR); } MediaDescription createDescription() { - MediaDescription.Builder builder = new MediaDescription.Builder() - .setMediaId(SONG_MEDIA_ID) - .setTitle(SONG_TITLE) - .setSubtitle(SONG_ARTIST) - .setDescription(SONG_ALBUM); + MediaDescription.Builder builder = + new MediaDescription.Builder() + .setMediaId(SONG_MEDIA_ID) + .setTitle(SONG_TITLE) + .setSubtitle(SONG_ARTIST) + .setDescription(SONG_ALBUM); return builder.build(); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java index ded83dec58b..26d732b28e5 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java @@ -58,43 +58,45 @@ public class AvrcpBipObexServerTest { private static final byte HEADER_ID_IMG_HANDLE = 0x30; private static final byte HEADER_ID_IMG_DESCRIPTOR = 0x71; - private static final byte[] BLUETOOTH_UUID_AVRCP_COVER_ART = new byte[] { - (byte) 0x71, - (byte) 0x63, - (byte) 0xDD, - (byte) 0x54, - (byte) 0x4A, - (byte) 0x7E, - (byte) 0x11, - (byte) 0xE2, - (byte) 0xB4, - (byte) 0x7C, - (byte) 0x00, - (byte) 0x50, - (byte) 0xC2, - (byte) 0x49, - (byte) 0x00, - (byte) 0x48 - }; - - private static final byte[] NOT_BLUETOOTH_UUID_AVRCP_COVER_ART = new byte[] { - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00 - }; + private static final byte[] BLUETOOTH_UUID_AVRCP_COVER_ART = + new byte[] { + (byte) 0x71, + (byte) 0x63, + (byte) 0xDD, + (byte) 0x54, + (byte) 0x4A, + (byte) 0x7E, + (byte) 0x11, + (byte) 0xE2, + (byte) 0xB4, + (byte) 0x7C, + (byte) 0x00, + (byte) 0x50, + (byte) 0xC2, + (byte) 0x49, + (byte) 0x00, + (byte) 0x48 + }; + + private static final byte[] NOT_BLUETOOTH_UUID_AVRCP_COVER_ART = + new byte[] { + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00, + (byte) 0x00 + }; private static final String IMAGE_HANDLE_1 = "0000001"; private static final String IMAGE_HANDLE_UNSTORED = "0000256"; @@ -114,8 +116,8 @@ public class AvrcpBipObexServerTest { @Before public void setUp() throws Exception { - mTestResources = TestUtils.getTestApplicationResources( - InstrumentationRegistry.getTargetContext()); + mTestResources = + TestUtils.getTestApplicationResources(InstrumentationRegistry.getTargetContext()); mCoverArt = loadCoverArt(com.android.bluetooth.tests.R.raw.image_200_200); @@ -156,11 +158,8 @@ public class AvrcpBipObexServerTest { /** * Creates a mocked operation that can be used by our server as a client request * - * Our server will use: - * - getReceivedHeader - * - sendHeaders - * - getMaxPacketSize - * - openOutputStream + *

Our server will use: - getReceivedHeader - sendHeaders - getMaxPacketSize - + * openOutputStream */ private Operation makeOperation(HeaderSet requestHeaders, OutputStream os) throws Exception { Operation op = mock(Operation.class); @@ -174,12 +173,11 @@ public class AvrcpBipObexServerTest { return new BipImageDescriptor.Builder() .setEncoding(encoding) .setFixedDimensions(width, height) - .build().serialize(); + .build() + .serialize(); } - /** - * Make sure we let a connection through with a valid UUID - */ + /** Make sure we let a connection through with a valid UUID */ @Test public void testConnectWithValidUuidHeader() throws Exception { mRequest.setHeader(HeaderSet.TARGET, BLUETOOTH_UUID_AVRCP_COVER_ART); @@ -188,9 +186,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_OK); } - /** - * Make sure we deny a connection when there is an invalid UUID - */ + /** Make sure we deny a connection when there is an invalid UUID */ @Test public void testConnectWithInvalidUuidHeader() throws Exception { mRequest.setHeader(HeaderSet.TARGET, NOT_BLUETOOTH_UUID_AVRCP_COVER_ART); @@ -199,27 +195,21 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE); } - /** - * Make sure onDisconnect notifies the callbacks in the proper way - */ + /** Make sure onDisconnect notifies the callbacks in the proper way */ @Test public void testDisonnect() { mAvrcpBipObexServer.onDisconnect(mRequest, mReply); verify(mCallback, times(1)).onDisconnected(); } - /** - * Make sure onClose notifies the callbacks in the proper way - */ + /** Make sure onClose notifies the callbacks in the proper way */ @Test public void testOnClose() { mAvrcpBipObexServer.onClose(); verify(mCallback, times(1)).onClose(); } - /** - * Make sure onGet handles null headers gracefully - */ + /** Make sure onGet handles null headers gracefully */ @Test public void testOnGetNoHeaders() throws Exception { Operation op = makeOperation(null, mOutputStream); @@ -227,9 +217,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_BAD_REQUEST); } - /** - * Make sure onGet handles bad type gracefully - */ + /** Make sure onGet handles bad type gracefully */ @Test public void testOnGetBadType() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_BAD); @@ -238,9 +226,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_BAD_REQUEST); } - /** - * Make sure onGet handles no type gracefully - */ + /** Make sure onGet handles no type gracefully */ @Test public void testOnGetNoType() throws Exception { mRequest.setHeader(HeaderSet.TYPE, null); @@ -249,9 +235,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_BAD_REQUEST); } - /** - * Make sure a getImageThumbnail request with a valid handle works - */ + /** Make sure a getImageThumbnail request with a valid handle works */ @Test public void testGetLinkedThumbnailWithValidHandle() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_GET_LINKED_THUMBNAIL); @@ -262,9 +246,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_OK); } - /** - * Make sure a getImageThumbnail request with a unstored handle returns OBEX_HTTP_NOT_FOUND - */ + /** Make sure a getImageThumbnail request with a unstored handle returns OBEX_HTTP_NOT_FOUND */ @Test public void testGetLinkedThumbnailWithValidUnstoredHandle() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_GET_LINKED_THUMBNAIL); @@ -313,9 +295,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_OK); } - /** - * Make sure a getImageProperties request with a unstored handle returns OBEX_HTTP_NOT_FOUND - */ + /** Make sure a getImageProperties request with a unstored handle returns OBEX_HTTP_NOT_FOUND */ @Test public void testGetImagePropertiesWithValidUnstoredHandle() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_GET_IMAGE_PROPERTIES); @@ -351,9 +331,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_BAD_REQUEST); } - /** - * Make sure a GetImage request with a null descriptor returns a native image - */ + /** Make sure a GetImage request with a null descriptor returns a native image */ @Test public void testGetImageWithValidHandleAndNullDescriptor() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_GET_IMAGE); @@ -365,9 +343,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_OK); } - /** - * Make sure a GetImage request with a valid descriptor returns an image - */ + /** Make sure a GetImage request with a valid descriptor returns an image */ @Test public void testGetImageWithValidHandleAndValidDescriptor() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_GET_IMAGE); @@ -386,7 +362,8 @@ public class AvrcpBipObexServerTest { public void testGetImageWithValidHandleAndInvalidDescriptor() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_GET_IMAGE); mRequest.setHeader(HEADER_ID_IMG_HANDLE, IMAGE_HANDLE_1); - mRequest.setHeader(HEADER_ID_IMG_DESCRIPTOR, + mRequest.setHeader( + HEADER_ID_IMG_DESCRIPTOR, makeDescriptor(BipEncoding.WBMP /* No Android support, won't work */, 200, 200)); setCoverArtAvailableAtHandle(IMAGE_HANDLE_1, mCoverArt); Operation op = makeOperation(mRequest, mOutputStream); @@ -394,9 +371,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE); } - /** - * Make sure a GetImage request with a unstored handle returns OBEX_HTTP_NOT_FOUND - */ + /** Make sure a GetImage request with a unstored handle returns OBEX_HTTP_NOT_FOUND */ @Test public void testGetImageWithValidUnstoredHandle() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_GET_IMAGE); @@ -420,9 +395,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_PRECON_FAILED); } - /** - * Make sure a getImage request with a null handle returns OBEX_HTTP_BAD_REQUEST - */ + /** Make sure a getImage request with a null handle returns OBEX_HTTP_BAD_REQUEST */ @Test public void testGetImageWithNullHandle() throws Exception { mRequest.setHeader(HeaderSet.TYPE, TYPE_GET_IMAGE); @@ -433,9 +406,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_BAD_REQUEST); } - /** - * Make sure onPut is not a supported action - */ + /** Make sure onPut is not a supported action */ @Test public void testOnPut() { Operation op = null; @@ -443,9 +414,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED); } - /** - * Make sure onAbort is not a supported action - */ + /** Make sure onAbort is not a supported action */ @Test public void testOnAbort() { HeaderSet request = null; @@ -454,9 +423,7 @@ public class AvrcpBipObexServerTest { assertThat(responseCode).isEqualTo(ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED); } - /** - * Make sure onSetPath is not a supported action - */ + /** Make sure onSetPath is not a supported action */ @Test public void testOnSetPath() { HeaderSet request = null; diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorageTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorageTest.java index d69fae650d9..ff2eb37a87d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorageTest.java @@ -43,8 +43,8 @@ public class AvrcpCoverArtStorageTest { @Before public void setUp() throws Exception { - mTestResources = TestUtils.getTestApplicationResources( - InstrumentationRegistry.getTargetContext()); + mTestResources = + TestUtils.getTestApplicationResources(InstrumentationRegistry.getTargetContext()); mAvrcpCoverArtStorage = new AvrcpCoverArtStorage(2); } @@ -63,9 +63,7 @@ public class AvrcpCoverArtStorageTest { return new CoverArt(image); } - /** - * Make sure you can store and get an image handle for an image - */ + /** Make sure you can store and get an image handle for an image */ @Test public void testStoreImage() { CoverArt artwork = getCoverArt(com.android.bluetooth.tests.R.raw.image_200_200); @@ -74,9 +72,7 @@ public class AvrcpCoverArtStorageTest { assertThat(mAvrcpCoverArtStorage.getImage(handle)).isEqualTo(artwork); } - /** - * Make sure an attempt to store an image that is already stored yields the previous handle - */ + /** Make sure an attempt to store an image that is already stored yields the previous handle */ @Test public void testStoreImageThatIsAlreadyStored() { CoverArt artwork = getCoverArt(com.android.bluetooth.tests.R.raw.image_200_200); @@ -85,9 +81,7 @@ public class AvrcpCoverArtStorageTest { assertThat(mAvrcpCoverArtStorage.storeImage(artwork)).isEqualTo(handle); } - /** - * Make sure you can store and get an image handle for a second image thats not yet stored - */ + /** Make sure you can store and get an image handle for a second image thats not yet stored */ @Test public void testStoreSecondImage() { CoverArt artwork_green = getCoverArt(com.android.bluetooth.tests.R.raw.image_200_200); @@ -104,7 +98,7 @@ public class AvrcpCoverArtStorageTest { /** * Make sure you can store and get an image handle for a third image thats not yet stored. * - * Since the cache size is set to 2 for these tests, this third image should force the least + *

Since the cache size is set to 2 for these tests, this third image should force the least * recently used image to be removed. This test has the LRU image as the first one entered. */ @Test @@ -136,7 +130,7 @@ public class AvrcpCoverArtStorageTest { /** * Make sure you can store and get an image handle for a third image thats not yet stored. * - * Since the cache size is set to 2 for these tests, this third image should force the least + *

Since the cache size is set to 2 for these tests, this third image should force the least * recently used image to be removed. This test has the LRU image as the second one entered. */ @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpPassthroughTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpPassthroughTest.java index a88a849c697..8dbaf5833b0 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpPassthroughTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpPassthroughTest.java @@ -12,120 +12,115 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class AvrcpPassthroughTest { - @Test - public void toKeyCode() { - AvrcpPassthrough ap = new AvrcpPassthrough(); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_UP)) - .isEqualTo(KeyEvent.KEYCODE_DPAD_UP); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_DOWN)) - .isEqualTo(KeyEvent.KEYCODE_DPAD_DOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_LEFT)) - .isEqualTo(KeyEvent.KEYCODE_DPAD_LEFT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_RIGHT)) - .isEqualTo(KeyEvent.KEYCODE_DPAD_RIGHT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_RIGHT_UP)) - .isEqualTo(KeyEvent.KEYCODE_DPAD_UP_RIGHT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_RIGHT_DOWN)) - .isEqualTo(KeyEvent.KEYCODE_DPAD_DOWN_RIGHT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_LEFT_UP)) - .isEqualTo(KeyEvent.KEYCODE_DPAD_UP_LEFT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_LEFT_DOWN)) - .isEqualTo(KeyEvent.KEYCODE_DPAD_DOWN_LEFT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_0)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_0); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_1)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_1); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_2)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_2); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_3)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_3); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_4)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_4); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_5)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_5); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_6)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_6); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_7)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_7); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_8)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_8); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_9)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_9); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_DOT)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_DOT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_ENTER)) - .isEqualTo(KeyEvent.KEYCODE_NUMPAD_ENTER); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_CLEAR)) - .isEqualTo(KeyEvent.KEYCODE_CLEAR); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_CHAN_DOWN)) - .isEqualTo(KeyEvent.KEYCODE_CHANNEL_DOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PREV_CHAN)) - .isEqualTo(KeyEvent.KEYCODE_LAST_CHANNEL); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_INPUT_SEL)) - .isEqualTo(KeyEvent.KEYCODE_TV_INPUT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_DISP_INFO)) - .isEqualTo(KeyEvent.KEYCODE_INFO); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_HELP)) - .isEqualTo(KeyEvent.KEYCODE_HELP); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PAGE_UP)) - .isEqualTo(KeyEvent.KEYCODE_PAGE_UP); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PAGE_DOWN)) - .isEqualTo(KeyEvent.KEYCODE_PAGE_DOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_POWER)) - .isEqualTo(KeyEvent.KEYCODE_POWER); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_VOL_UP)) - .isEqualTo(KeyEvent.KEYCODE_VOLUME_UP); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_VOL_DOWN)) - .isEqualTo(KeyEvent.KEYCODE_VOLUME_DOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_MUTE)) - .isEqualTo(KeyEvent.KEYCODE_MUTE); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PLAY)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_PLAY); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_STOP)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_STOP); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PAUSE)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_PAUSE); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_RECORD)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_RECORD); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_REWIND)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_REWIND); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_FAST_FOR)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_EJECT)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_EJECT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_FORWARD)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_NEXT); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_BACKWARD)) - .isEqualTo(KeyEvent.KEYCODE_MEDIA_PREVIOUS); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F1)) - .isEqualTo(KeyEvent.KEYCODE_F1); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F2)) - .isEqualTo(KeyEvent.KEYCODE_F2); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F3)) - .isEqualTo(KeyEvent.KEYCODE_F3); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F4)) - .isEqualTo(KeyEvent.KEYCODE_F4); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F5)) - .isEqualTo(KeyEvent.KEYCODE_F5); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_SELECT)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_ROOT_MENU)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_SETUP_MENU)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_CONT_MENU)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_FAV_MENU)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_EXIT)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_SOUND_SEL)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_ANGLE)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_SUBPICT)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_VENDOR)) - .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); - } + @Test + public void toKeyCode() { + AvrcpPassthrough ap = new AvrcpPassthrough(); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_UP)) + .isEqualTo(KeyEvent.KEYCODE_DPAD_UP); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_DOWN)) + .isEqualTo(KeyEvent.KEYCODE_DPAD_DOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_LEFT)) + .isEqualTo(KeyEvent.KEYCODE_DPAD_LEFT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_RIGHT)) + .isEqualTo(KeyEvent.KEYCODE_DPAD_RIGHT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_RIGHT_UP)) + .isEqualTo(KeyEvent.KEYCODE_DPAD_UP_RIGHT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_RIGHT_DOWN)) + .isEqualTo(KeyEvent.KEYCODE_DPAD_DOWN_RIGHT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_LEFT_UP)) + .isEqualTo(KeyEvent.KEYCODE_DPAD_UP_LEFT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_LEFT_DOWN)) + .isEqualTo(KeyEvent.KEYCODE_DPAD_DOWN_LEFT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_0)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_0); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_1)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_1); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_2)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_2); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_3)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_3); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_4)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_4); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_5)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_5); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_6)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_6); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_7)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_7); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_8)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_8); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_9)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_9); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_DOT)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_DOT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_ENTER)) + .isEqualTo(KeyEvent.KEYCODE_NUMPAD_ENTER); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_CLEAR)) + .isEqualTo(KeyEvent.KEYCODE_CLEAR); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_CHAN_DOWN)) + .isEqualTo(KeyEvent.KEYCODE_CHANNEL_DOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PREV_CHAN)) + .isEqualTo(KeyEvent.KEYCODE_LAST_CHANNEL); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_INPUT_SEL)) + .isEqualTo(KeyEvent.KEYCODE_TV_INPUT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_DISP_INFO)) + .isEqualTo(KeyEvent.KEYCODE_INFO); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_HELP)) + .isEqualTo(KeyEvent.KEYCODE_HELP); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PAGE_UP)) + .isEqualTo(KeyEvent.KEYCODE_PAGE_UP); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PAGE_DOWN)) + .isEqualTo(KeyEvent.KEYCODE_PAGE_DOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_POWER)) + .isEqualTo(KeyEvent.KEYCODE_POWER); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_VOL_UP)) + .isEqualTo(KeyEvent.KEYCODE_VOLUME_UP); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_VOL_DOWN)) + .isEqualTo(KeyEvent.KEYCODE_VOLUME_DOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_MUTE)) + .isEqualTo(KeyEvent.KEYCODE_MUTE); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PLAY)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_PLAY); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_STOP)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_STOP); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_PAUSE)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_PAUSE); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_RECORD)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_RECORD); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_REWIND)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_REWIND); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_FAST_FOR)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_FAST_FORWARD); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_EJECT)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_EJECT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_FORWARD)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_NEXT); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_BACKWARD)) + .isEqualTo(KeyEvent.KEYCODE_MEDIA_PREVIOUS); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F1)).isEqualTo(KeyEvent.KEYCODE_F1); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F2)).isEqualTo(KeyEvent.KEYCODE_F2); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F3)).isEqualTo(KeyEvent.KEYCODE_F3); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F4)).isEqualTo(KeyEvent.KEYCODE_F4); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_F5)).isEqualTo(KeyEvent.KEYCODE_F5); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_SELECT)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_ROOT_MENU)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_SETUP_MENU)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_CONT_MENU)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_FAV_MENU)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_EXIT)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_SOUND_SEL)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_ANGLE)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_SUBPICT)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + assertThat(ap.toKeyCode(BluetoothAvrcp.PASSTHROUGH_ID_VENDOR)) + .isEqualTo(KeyEvent.KEYCODE_UNKNOWN); + } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpVolumeManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpVolumeManagerTest.java index b367484c443..5ace4413c81 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpVolumeManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpVolumeManagerTest.java @@ -53,11 +53,9 @@ public class AvrcpVolumeManagerTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - AvrcpNativeInterface mNativeInterface; + @Mock AvrcpNativeInterface mNativeInterface; - @Mock - AudioManager mAudioManager; + @Mock AudioManager mAudioManager; Context mContext; BluetoothDevice mRemoteDevice; diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java index 4c37d8a3df1..42f4aac0ab2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java @@ -58,8 +58,8 @@ public class CoverArtTest { @Before public void setUp() throws Exception { - mTestResources = TestUtils.getTestApplicationResources( - InstrumentationRegistry.getTargetContext()); + mTestResources = + TestUtils.getTestApplicationResources(InstrumentationRegistry.getTargetContext()); m200by200Image = loadImage(com.android.bluetooth.tests.R.raw.image_200_200); m200by200ImageBlue = loadImage(com.android.bluetooth.tests.R.raw.image_200_200_blue); @@ -129,18 +129,14 @@ public class CoverArtTest { return (200 == image.getHeight() && 200 == image.getWidth()); } - /** - * Make sure you can create an image from an Image object - */ + /** Make sure you can create an image from an Image object */ @Test public void testCreateCoverArtFromImage() { CoverArt artwork = new CoverArt(mImage); assertThat(artwork.getImage()).isNotNull(); } - /** - * Make sure you get an image hash from a valid image - */ + /** Make sure you get an image hash from a valid image */ @Test public void testGetImageHash() { CoverArt artwork = new CoverArt(mImage); @@ -148,9 +144,7 @@ public class CoverArtTest { assertThat(hash).isNotNull(); } - /** - * Make sure you get the same image hash from several calls to the same object - */ + /** Make sure you get the same image hash from several calls to the same object */ @Test public void testGetImageHashSameForMultipleCalls() { CoverArt artwork = new CoverArt(mImage); @@ -160,9 +154,7 @@ public class CoverArtTest { assertThat(artwork.getImageHash()).isEqualTo(hash); // extra call 2 } - /** - * Make sure you get the same image hash from separate objects created from the same image - */ + /** Make sure you get the same image hash from separate objects created from the same image */ @Test public void testGetImageHashSameForSameImages() { CoverArt artwork = new CoverArt(mImage); @@ -190,9 +182,7 @@ public class CoverArtTest { assertThat(hash).isNotEqualTo(hash2); } - /** - * Make sure you get an image when asking for the native image - */ + /** Make sure you get an image when asking for the native image */ @Test public void testGetNativeImage() { CoverArt artwork = new CoverArt(mImage); @@ -200,9 +190,7 @@ public class CoverArtTest { assertThat(image).isNotNull(); } - /** - * Make sure you getThumbnailImage returns an image as a 200 by 200 JPEG - */ + /** Make sure you getThumbnailImage returns an image as a 200 by 200 JPEG */ @Test public void testGetThumbnailImage() { CoverArt artwork = new CoverArt(mImage); @@ -212,9 +200,7 @@ public class CoverArtTest { assertThat(isThumbnailFormat(image)).isTrue(); } - /** - * Make sure you can set the image handle associated with this object - */ + /** Make sure you can set the image handle associated with this object */ @Test public void testGetAndSetImageHandle() { CoverArt artwork = new CoverArt(mImage); @@ -224,8 +210,8 @@ public class CoverArtTest { } /** - * Make sure a getImageProperties() yields a set of image properties. The thumbnail format - * MUST be contained in that set + * Make sure a getImageProperties() yields a set of image properties. The thumbnail format MUST + * be contained in that set */ @Test public void testGetImageProperties() { @@ -236,9 +222,7 @@ public class CoverArtTest { assertThat(containsThumbnailFormat(properties)).isTrue(); } - /** - * Make sure a getImage() yield an image in the format you asked for - */ + /** Make sure a getImage() yield an image in the format you asked for */ @Test public void testGetImageWithValidDescriptor() { CoverArt artwork = new CoverArt(mImage); @@ -247,9 +231,7 @@ public class CoverArtTest { assertThat(image).isNotNull(); } - /** - * Make sure a getImage() yields the image in the thumbnail format - */ + /** Make sure a getImage() yields the image in the thumbnail format */ @Test public void testGetImageWithThumbnailDescriptor() { CoverArt artwork = new CoverArt(mImage); @@ -260,9 +242,7 @@ public class CoverArtTest { assertThat(isThumbnailFormat(image)).isTrue(); } - /** - * Make sure a getImage() yields a null - */ + /** Make sure a getImage() yields a null */ @Test public void testGetImageWithInvalidDescriptor() { CoverArt artwork = new CoverArt(mImage); @@ -271,9 +251,7 @@ public class CoverArtTest { assertThat(image).isNull(); } - /** - * Make sure a getImage() yields the native image - */ + /** Make sure a getImage() yields the native image */ @Test public void testGetImageWithoutDescriptor() { CoverArt artwork = new CoverArt(mImage); @@ -282,18 +260,14 @@ public class CoverArtTest { assertThat(Arrays.equals(nativeImage, image)).isTrue(); } - /** - * Make sure we can get a valid string representation of the CoverArt - */ + /** Make sure we can get a valid string representation of the CoverArt */ @Test public void testGetSize() { CoverArt artwork = new CoverArt(mImage); assertThat(artwork.size() > 0).isTrue(); } - /** - * Make sure we can get a valid string representation of the CoverArt - */ + /** Make sure we can get a valid string representation of the CoverArt */ @Test public void testToString() { CoverArt artwork = new CoverArt(mImage); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java index ee6481b1970..016041a284c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java @@ -76,12 +76,12 @@ public class AvrcpBipClientTest { mAdapter = BluetoothAdapter.getDefaultAdapter(); mTestDevice = mAdapter.getRemoteDevice("00:01:02:03:04:05"); - AvrcpCoverArtManager.Callback callback = (device, event) -> { - }; + AvrcpCoverArtManager.Callback callback = (device, event) -> {}; mArtManager = new AvrcpCoverArtManager(mService, callback); - mClient = new AvrcpBipClient(mTestDevice, TEST_PSM, - mArtManager.new BipClientCallback(mTestDevice)); + mClient = + new AvrcpBipClient( + mTestDevice, TEST_PSM, mArtManager.new BipClientCallback(mTestDevice)); } @After @@ -96,22 +96,26 @@ public class AvrcpBipClientTest { @Test public void constructor() { - AvrcpBipClient client = new AvrcpBipClient(mTestDevice, TEST_PSM, - mArtManager.new BipClientCallback(mTestDevice)); + AvrcpBipClient client = + new AvrcpBipClient( + mTestDevice, TEST_PSM, mArtManager.new BipClientCallback(mTestDevice)); assertThat(client.getL2capPsm()).isEqualTo(TEST_PSM); } @Test public void constructor_withNullDevice() { - assertThrows(NullPointerException.class, () -> new AvrcpBipClient(null, TEST_PSM, - mArtManager.new BipClientCallback(mTestDevice))); + assertThrows( + NullPointerException.class, + () -> + new AvrcpBipClient( + null, TEST_PSM, mArtManager.new BipClientCallback(mTestDevice))); } @Test public void constructor_withNullCallback() { - assertThrows(NullPointerException.class, () -> new AvrcpBipClient(mTestDevice, TEST_PSM, - null)); + assertThrows( + NullPointerException.class, () -> new AvrcpBipClient(mTestDevice, TEST_PSM, null)); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java index 4acc0810f48..e4371d723f8 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java @@ -40,8 +40,7 @@ public class AvrcpControllerServiceBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private AvrcpControllerService mService; + @Mock private AvrcpControllerService mService; BluetoothDevice mRemoteDevice; diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java index cb327ea7a10..5ff2f75fdfe 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java @@ -65,7 +65,7 @@ import java.util.List; @RunWith(AndroidJUnit4.class) public class AvrcpControllerServiceTest { private static final String REMOTE_DEVICE_ADDRESS = "00:00:00:00:00:00"; - private static final byte[] REMOTE_DEVICE_ADDRESS_AS_ARRAY = new byte[]{0, 0, 0, 0, 0, 0}; + private static final byte[] REMOTE_DEVICE_ADDRESS_AS_ARRAY = new byte[] {0, 0, 0, 0, 0, 0}; private static final String REMOTE_DEVICE_ADDRESS_2 = "11:11:11:11:11:11"; private static final byte[] REMOTE_DEVICE_ADDRESS_AS_ARRAY_2 = new byte[] {11, 11, 11, 11, 11, 11}; @@ -162,8 +162,7 @@ public class AvrcpControllerServiceTest { @Test public void getConnectedDevices() { - when(mAdapterService.getBondedDevices()).thenReturn( - new BluetoothDevice[]{mRemoteDevice}); + when(mAdapterService.getBondedDevices()).thenReturn(new BluetoothDevice[] {mRemoteDevice}); when(mStateMachine.getState()).thenReturn(BluetoothProfile.STATE_CONNECTED); assertThat(mService.getConnectedDevices()).contains(mRemoteDevice); @@ -215,9 +214,9 @@ public class AvrcpControllerServiceTest { } /** - * Pre-conditions: No node in BrowseTree for specified media ID - * Test: Call AvrcpControllerService.getContents() - * Expected Output: BrowseResult object with status ERROR_MEDIA_ID_INVALID + * Pre-conditions: No node in BrowseTree for specified media ID Test: Call + * AvrcpControllerService.getContents() Expected Output: BrowseResult object with status + * ERROR_MEDIA_ID_INVALID */ @Test public void testGetContentsNoNode_returnInvalidMediaIdStatus() { @@ -230,8 +229,8 @@ public class AvrcpControllerServiceTest { /** * Pre-conditions: No device is connected - parent media ID is at the root of the BrowseTree - * Test: Call AvrcpControllerService.getContents() - * Expected Output: BrowseResult object with status NO_DEVICE_CONNECTED + * Test: Call AvrcpControllerService.getContents() Expected Output: BrowseResult object with + * status NO_DEVICE_CONNECTED */ @Test public void getContentsNoDeviceConnected_returnNoDeviceConnectedStatus() { @@ -242,9 +241,8 @@ public class AvrcpControllerServiceTest { } /** - * Pre-conditions: At least one device is connected - * Test: Call AvrcpControllerService.getContents() - * Expected Output: BrowseResult object with status SUCCESS + * Pre-conditions: At least one device is connected Test: Call + * AvrcpControllerService.getContents() Expected Output: BrowseResult object with status SUCCESS */ @Test public void getContentsOneDeviceConnected_returnSuccessStatus() { @@ -256,13 +254,12 @@ public class AvrcpControllerServiceTest { } /** - * Pre-conditions: Node for specified media ID is not cached - * Test: {@link BrowseTree.BrowseNode#getContents} returns {@code null} when the node has no - * children/items and the node is not cached. - * When {@link AvrcpControllerService#getContents} receives a node that is not cached, - * it should interpret the status as `DOWNLOAD_PENDING`. - * Expected Output: BrowseResult object with status DOWNLOAD_PENDING; verify that a download - * request has been sent by checking if mStateMachine.requestContents() is called + * Pre-conditions: Node for specified media ID is not cached Test: {@link + * BrowseTree.BrowseNode#getContents} returns {@code null} when the node has no children/items + * and the node is not cached. When {@link AvrcpControllerService#getContents} receives a node + * that is not cached, it should interpret the status as `DOWNLOAD_PENDING`. Expected Output: + * BrowseResult object with status DOWNLOAD_PENDING; verify that a download request has been + * sent by checking if mStateMachine.requestContents() is called */ @Test public void getContentsNodeNotCached_returnDownloadPendingStatus() { @@ -280,9 +277,8 @@ public class AvrcpControllerServiceTest { } /** - * Pre-conditions: Parent media ID that is not BrowseTree.ROOT; isCached returns true - * Test: Call AvrcpControllerService.getContents() - * Expected Output: BrowseResult object with status SUCCESS + * Pre-conditions: Parent media ID that is not BrowseTree.ROOT; isCached returns true Test: Call + * AvrcpControllerService.getContents() Expected Output: BrowseResult object with status SUCCESS */ @Test public void getContentsNoErrorConditions_returnsSuccessStatus() { @@ -381,8 +377,9 @@ public class AvrcpControllerServiceTest { mService.getRcPsm(mRemoteDevice, psm); - verify(mStateMachine).sendMessage( - AvrcpControllerStateMachine.MESSAGE_PROCESS_RECEIVED_COVER_ART_PSM, psm); + verify(mStateMachine) + .sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_RECEIVED_COVER_ART_PSM, psm); } @Test @@ -435,8 +432,11 @@ public class AvrcpControllerServiceTest { mService.onPlayPositionChanged(mRemoteDevice, songLen, currSongPos); - verify(mStateMachine).sendMessage( - AvrcpControllerStateMachine.MESSAGE_PROCESS_PLAY_POS_CHANGED, songLen, currSongPos); + verify(mStateMachine) + .sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_PLAY_POS_CHANGED, + songLen, + currSongPos); } @Test @@ -445,9 +445,10 @@ public class AvrcpControllerServiceTest { mService.onPlayStatusChanged(mRemoteDevice, status); - verify(mStateMachine).sendMessage( - AvrcpControllerStateMachine.MESSAGE_PROCESS_PLAY_STATUS_CHANGED, - PlaybackStateCompat.STATE_REWINDING); + verify(mStateMachine) + .sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_PLAY_STATUS_CHANGED, + PlaybackStateCompat.STATE_REWINDING); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java index e4f9cd82d6d..bd559d901c2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java @@ -96,7 +96,7 @@ public class AvrcpControllerStateMachineTest { private ArgumentCaptor mIntentArgument = ArgumentCaptor.forClass(Intent.class); - private byte[] mTestAddress = new byte[]{01, 01, 01, 01, 01, 01}; + private byte[] mTestAddress = new byte[] {01, 01, 01, 01, 01, 01}; private BluetoothDevice mTestDevice = null; private AvrcpControllerStateMachine mAvrcpStateMachine = null; @@ -121,9 +121,11 @@ public class AvrcpControllerStateMachineTest { when(mMockResources.getBoolean(R.bool.a2dp_sink_automatically_request_audio_focus)) .thenReturn(true); doReturn(mMockResources).when(mAvrcpControllerService).getResources(); - doReturn(mAudioManager).when(mAvrcpControllerService) + doReturn(mAudioManager) + .when(mAvrcpControllerService) .getSystemService(Context.AUDIO_SERVICE); - doReturn(Context.AUDIO_SERVICE).when(mAvrcpControllerService) + doReturn(Context.AUDIO_SERVICE) + .when(mAvrcpControllerService) .getSystemServiceName(AudioManager.class); doReturn(mCoverArtManager).when(mAvrcpControllerService).getCoverArtManager(); mAvrcpControllerService.sBrowseTree = new BrowseTree(null); @@ -155,9 +157,7 @@ public class AvrcpControllerStateMachineTest { TestUtils.clearAdapterService(mAdapterService); } - /** - * Create a state machine to test - */ + /** Create a state machine to test */ private AvrcpControllerStateMachine makeStateMachine(BluetoothDevice device) { AvrcpControllerStateMachine sm = new AvrcpControllerStateMachine( @@ -166,9 +166,7 @@ public class AvrcpControllerStateMachineTest { return sm; } - /** - * Destroy a state machine you created to test - */ + /** Destroy a state machine you created to test */ private void destroyStateMachine(AvrcpControllerStateMachine sm) { if (sm == null || sm.getState() == BluetoothProfile.STATE_DISCONNECTED) return; @@ -182,9 +180,7 @@ public class AvrcpControllerStateMachineTest { verify(mAvrcpControllerService).removeStateMachine(eq(sm)); } - /** - * Set up which device the AvrcpControllerService will report as active - */ + /** Set up which device the AvrcpControllerService will report as active */ private void setActiveDevice(BluetoothDevice device) { doReturn(device).when(mAvrcpControllerService).getActiveDevice(); if (mTestDevice.equals(device)) { @@ -195,13 +191,10 @@ public class AvrcpControllerStateMachineTest { } } - /** - * Send an audio focus changed event to the state machine under test - */ + /** Send an audio focus changed event to the state machine under test */ private void sendAudioFocusUpdate(int state) { when(mA2dpSinkService.getFocusState()).thenReturn(state); - mAvrcpStateMachine.sendMessage( - AvrcpControllerStateMachine.AUDIO_FOCUS_STATE_CHANGE, state); + mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.AUDIO_FOCUS_STATE_CHANGE, state); } /** @@ -211,24 +204,32 @@ public class AvrcpControllerStateMachineTest { */ private int setUpConnectedState(boolean control, boolean browsing) { - Assert.assertThat(mAvrcpStateMachine.getCurrentState(), + Assert.assertThat( + mAvrcpStateMachine.getCurrentState(), IsInstanceOf.instanceOf(AvrcpControllerStateMachine.Disconnected.class)); mAvrcpStateMachine.connect(StackEvent.connectionStateChanged(control, browsing)); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); - verify(mAvrcpControllerService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcast( - mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - Assert.assertThat(mAvrcpStateMachine.getCurrentState(), + verify(mAvrcpControllerService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcast(mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + Assert.assertThat( + mAvrcpStateMachine.getCurrentState(), IsInstanceOf.instanceOf(AvrcpControllerStateMachine.Connected.class)); Assert.assertEquals(mAvrcpStateMachine.getState(), BluetoothProfile.STATE_CONNECTED); return BluetoothProfile.STATE_CONNECTED; } - private AvrcpItem makeTrack(String title, String artist, String album, long trackNum, - long totalTracks, String genre, long duration, String imageHandle) { + private AvrcpItem makeTrack( + String title, + String artist, + String album, + long trackNum, + long totalTracks, + String genre, + long duration, + String imageHandle) { AvrcpItem.Builder builder = new AvrcpItem.Builder(); builder.setItemType(AvrcpItem.TYPE_MEDIA); builder.setType(AvrcpItem.MEDIA_AUDIO); @@ -267,37 +268,30 @@ public class AvrcpControllerStateMachineTest { } /** - * Send a message to the state machine that the track has changed. Must be connected to - * do this. + * Send a message to the state machine that the track has changed. Must be connected to do this. */ private void setCurrentTrack(AvrcpItem track) { - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_TRACK_CHANGED, - track); + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_TRACK_CHANGED, track); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); Assert.assertEquals(mAvrcpStateMachine.getCurrentTrack(), track); } - /** - * Set the current play status (Play, Pause, etc.) of the device - */ + /** Set the current play status (Play, Pause, etc.) of the device */ private void setPlaybackState(int state) { mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_PLAY_STATUS_CHANGED, state); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); } - /** - * Set the current playback position of the device - */ + /** Set the current playback position of the device */ private void setPlaybackPosition(int position, int duration) { mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_PLAY_POS_CHANGED, duration, position); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); } - /** - * Make an AvrcpItem suitable for being included in the Now Playing list for the test device - */ + /** Make an AvrcpItem suitable for being included in the Now Playing list for the test device */ private AvrcpItem makeNowPlayingItem(long uid, String name) { AvrcpItem.Builder aib = new AvrcpItem.Builder(); aib.setDevice(mTestDevice); @@ -310,9 +304,7 @@ public class AvrcpControllerStateMachineTest { return aib.build(); } - /** - * Get the current Now Playing list for the test device - */ + /** Get the current Now Playing list for the test device */ private List getNowPlayingList() { BrowseTree.BrowseNode nowPlaying = mAvrcpStateMachine.findNode("NOW_PLAYING"); List nowPlayingList = new ArrayList(); @@ -322,9 +314,7 @@ public class AvrcpControllerStateMachineTest { return nowPlayingList; } - /** - * Set the current Now Playing list for the test device - */ + /** Set the current Now Playing list for the test device */ private void setNowPlayingList(List nowPlayingList) { BrowseTree.BrowseNode nowPlaying = mAvrcpStateMachine.findNode("NOW_PLAYING"); mAvrcpStateMachine.requestContents(nowPlaying); @@ -356,13 +346,14 @@ public class AvrcpControllerStateMachineTest { return s.toString(); } - /** - * Assert that the Now Playing list is a particular value - */ + /** Assert that the Now Playing list is a particular value */ private void assertNowPlayingList(List expected) { List current = getNowPlayingList(); - String err = "Now playing list incorrect, expected=" - + avrcpItemListToString(expected) + ", actual=" + avrcpItemListToString(current); + String err = + "Now playing list incorrect, expected=" + + avrcpItemListToString(expected) + + ", actual=" + + avrcpItemListToString(current); Assert.assertEquals(err, expected.size(), current.size()); for (int i = 0; i < expected.size(); i++) { Assert.assertEquals(err, expected.get(i), current.get(i)); @@ -370,8 +361,8 @@ public class AvrcpControllerStateMachineTest { } /** - * Test to confirm that the state machine is capable of cycling through the 4 - * connection states, and that upon completion, it cleans up afterwards. + * Test to confirm that the state machine is capable of cycling through the 4 connection states, + * and that upon completion, it cleans up afterwards. */ @Test public void testDisconnect() { @@ -380,9 +371,9 @@ public class AvrcpControllerStateMachineTest { } /** - * Test to confirm that the state machine is capable of cycling through the 4 - * connection states with no crashes, even if the {@link AvrcpControllerService} is stopped and - * the {@code sBrowseTree} is null. This could happen if BT is disabled as the profile is being + * Test to confirm that the state machine is capable of cycling through the 4 connection states + * with no crashes, even if the {@link AvrcpControllerService} is stopped and the {@code + * sBrowseTree} is null. This could happen if BT is disabled as the profile is being * disconnected. */ @Test @@ -396,75 +387,79 @@ public class AvrcpControllerStateMachineTest { private void testDisconnectInternal(int numBroadcastsSent) { mAvrcpStateMachine.disconnect(); numBroadcastsSent += 2; - verify(mAvrcpControllerService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcast( - mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - Assert.assertEquals(mTestDevice, mIntentArgument.getValue().getParcelableExtra( - BluetoothDevice.EXTRA_DEVICE)); - Assert.assertEquals(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED, + verify(mAvrcpControllerService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcast(mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + Assert.assertEquals( + mTestDevice, + mIntentArgument.getValue().getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); + Assert.assertEquals( + BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED, mIntentArgument.getValue().getAction()); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertThat(mAvrcpStateMachine.getCurrentState(), + Assert.assertThat( + mAvrcpStateMachine.getCurrentState(), IsInstanceOf.instanceOf(AvrcpControllerStateMachine.Disconnected.class)); Assert.assertEquals(mAvrcpStateMachine.getState(), BluetoothProfile.STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); } - /** - * Test to confirm that a control only device can be established (no browsing) - */ + /** Test to confirm that a control only device can be established (no browsing) */ @Test public void testControlOnly() { int numBroadcastsSent = setUpConnectedState(true, false); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); Assert.assertNotNull(transportControls); - Assert.assertEquals(PlaybackStateCompat.STATE_NONE, + Assert.assertEquals( + PlaybackStateCompat.STATE_NONE, BluetoothMediaBrowserService.getPlaybackState().getState()); mAvrcpStateMachine.disconnect(); numBroadcastsSent += 2; - verify(mAvrcpControllerService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcast( - mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - Assert.assertEquals(mTestDevice, mIntentArgument.getValue().getParcelableExtra( - BluetoothDevice.EXTRA_DEVICE)); - Assert.assertEquals(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED, + verify(mAvrcpControllerService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcast(mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + Assert.assertEquals( + mTestDevice, + mIntentArgument.getValue().getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); + Assert.assertEquals( + BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED, mIntentArgument.getValue().getAction()); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertThat(mAvrcpStateMachine.getCurrentState(), + Assert.assertThat( + mAvrcpStateMachine.getCurrentState(), IsInstanceOf.instanceOf(AvrcpControllerStateMachine.Disconnected.class)); Assert.assertEquals(mAvrcpStateMachine.getState(), BluetoothProfile.STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); } - /** - * Test to confirm that a browsing only device can be established (no control) - */ + /** Test to confirm that a browsing only device can be established (no control) */ @Test @FlakyTest public void testBrowsingOnly() { Assert.assertEquals(0, mAvrcpControllerService.sBrowseTree.mRootNode.getChildrenCount()); int numBroadcastsSent = setUpConnectedState(false, true); Assert.assertEquals(1, mAvrcpControllerService.sBrowseTree.mRootNode.getChildrenCount()); - Assert.assertEquals(PlaybackStateCompat.STATE_NONE, + Assert.assertEquals( + PlaybackStateCompat.STATE_NONE, BluetoothMediaBrowserService.getPlaybackState().getState()); mAvrcpStateMachine.disconnect(); numBroadcastsSent += 2; - verify(mAvrcpControllerService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcast( - mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - Assert.assertEquals(mTestDevice, mIntentArgument.getValue().getParcelableExtra( - BluetoothDevice.EXTRA_DEVICE)); - Assert.assertEquals(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED, + verify(mAvrcpControllerService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcast(mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + Assert.assertEquals( + mTestDevice, + mIntentArgument.getValue().getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); + Assert.assertEquals( + BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED, mIntentArgument.getValue().getAction()); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertThat(mAvrcpStateMachine.getCurrentState(), + Assert.assertThat( + mAvrcpStateMachine.getCurrentState(), IsInstanceOf.instanceOf(AvrcpControllerStateMachine.Disconnected.class)); Assert.assertEquals(mAvrcpStateMachine.getState(), BluetoothProfile.STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); @@ -496,17 +491,13 @@ public class AvrcpControllerStateMachineTest { assertThat((results.getID()).substring(UUID_START, UUID_LENGTH)).isEqualTo(rootName); } - /** - * Test to make sure the state machine is tracking the correct device - */ + /** Test to make sure the state machine is tracking the correct device */ @Test public void testGetDevice() { Assert.assertEquals(mAvrcpStateMachine.getDevice(), mTestDevice); } - /** - * Test that dumpsys will generate information about connected devices - */ + /** Test that dumpsys will generate information about connected devices */ @Test public void testDump() { StringBuilder sb = new StringBuilder(); @@ -514,16 +505,14 @@ public class AvrcpControllerStateMachineTest { Assert.assertNotNull(sb.toString()); } - /** - * Test media browser play command - */ + /** Test media browser play command */ @Test public void testPlay() throws Exception { setUpConnectedState(true, true); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Play + // Play transportControls.play(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( @@ -537,16 +526,14 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test media browser pause command - */ + /** Test media browser pause command */ @Test public void testPause() throws Exception { setUpConnectedState(true, true); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Pause + // Pause transportControls.pause(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( @@ -560,16 +547,14 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test media browser stop command - */ + /** Test media browser stop command */ @Test public void testStop() throws Exception { setUpConnectedState(true, true); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Stop + // Stop transportControls.stop(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( @@ -583,16 +568,14 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test media browser next command - */ + /** Test media browser next command */ @Test public void testNext() throws Exception { setUpConnectedState(true, true); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Next + // Next transportControls.skipToNext(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( @@ -606,16 +589,14 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test media browser previous command - */ + /** Test media browser previous command */ @Test public void testPrevious() throws Exception { setUpConnectedState(true, true); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Previous + // Previous transportControls.skipToPrevious(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( @@ -629,9 +610,7 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test media browser fast forward command - */ + /** Test media browser fast forward command */ @Test @FlakyTest public void testFastForward() throws Exception { @@ -639,14 +618,14 @@ public class AvrcpControllerStateMachineTest { MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //FastForward + // FastForward transportControls.fastForward(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( eq(mTestAddress), eq(AvrcpControllerService.PASS_THRU_CMD_ID_FF), eq(KEY_DOWN)); - //Finish FastForwarding + // Finish FastForwarding transportControls.play(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( @@ -655,23 +634,21 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test media browser rewind command - */ + /** Test media browser rewind command */ @Test public void testRewind() throws Exception { setUpConnectedState(true, true); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Rewind + // Rewind transportControls.rewind(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( eq(mTestAddress), eq(AvrcpControllerService.PASS_THRU_CMD_ID_REWIND), eq(KEY_DOWN)); - //Finish Rewinding + // Finish Rewinding transportControls.play(); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .sendPassThroughCommand( @@ -680,9 +657,7 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test media browser skip to queue item - */ + /** Test media browser skip to queue item */ @Test public void testSkipToQueueInvalid() throws Exception { byte scope = 1; @@ -692,49 +667,45 @@ public class AvrcpControllerStateMachineTest { MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Play an invalid item below start + // Play an invalid item below start transportControls.skipToQueueItem(minSize - 1); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(0)) .playItem(eq(mTestAddress), eq(scope), anyLong(), anyInt()); - //Play an invalid item beyond end + // Play an invalid item beyond end transportControls.skipToQueueItem(maxSize + 1); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(0)) .playItem(eq(mTestAddress), eq(scope), anyLong(), anyInt()); } - /** - * Test media browser shuffle command - */ + /** Test media browser shuffle command */ @Test public void testShuffle() throws Exception { - byte[] shuffleSetting = new byte[]{3}; - byte[] shuffleMode = new byte[]{2}; + byte[] shuffleSetting = new byte[] {3}; + byte[] shuffleMode = new byte[] {2}; setUpConnectedState(true, true); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Shuffle + // Shuffle transportControls.setShuffleMode(1); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .setPlayerApplicationSettingValues( eq(mTestAddress), eq((byte) 1), eq(shuffleSetting), eq(shuffleMode)); } - /** - * Test media browser repeat command - */ + /** Test media browser repeat command */ @Test public void testRepeat() throws Exception { - byte[] repeatSetting = new byte[]{2}; - byte[] repeatMode = new byte[]{3}; + byte[] repeatSetting = new byte[] {2}; + byte[] repeatMode = new byte[] {3}; setUpConnectedState(true, true); MediaControllerCompat.TransportControls transportControls = BluetoothMediaBrowserService.getTransportControls(); - //Shuffle + // Shuffle transportControls.setRepeatMode(2); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .setPlayerApplicationSettingValues( @@ -742,10 +713,9 @@ public class AvrcpControllerStateMachineTest { } /** - * Test media browsing - * Verify that a browse tree is created with the proper root - * Verify that a player can be fetched and added to the browse tree - * Verify that the contents of a player are fetched upon request + * Test media browsing Verify that a browse tree is created with the proper root Verify that a + * player can be fetched and added to the browse tree Verify that the contents of a player are + * fetched upon request */ @Test @FlakyTest @@ -754,31 +724,32 @@ public class AvrcpControllerStateMachineTest { final String playerName = "Player 1"; BrowseTree.BrowseNode results = mAvrcpStateMachine.mBrowseTree.mRootNode; - //Request fetch the list of players + // Request fetch the list of players BrowseTree.BrowseNode playerNodes = mAvrcpStateMachine.findNode(results.getID()); mAvrcpStateMachine.requestContents(results); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .getPlayerList(eq(mTestAddress), eq(0), eq(19)); - //Provide back a player object + // Provide back a player object byte[] playerFeatures = - new byte[]{0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; + new byte[] {0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; AvrcpPlayer playerOne = makePlayer(mTestDevice, 1, playerName, playerFeatures, 1); List testPlayers = new ArrayList<>(); testPlayers.add(playerOne); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, - testPlayers); + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, testPlayers); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); - //Verify that the player object is available. + // Verify that the player object is available. playerNodes = mAvrcpStateMachine.findNode(results.getID()); Assert.assertEquals(true, results.isCached()); - Assert.assertEquals("MediaItem{mFlags=1, mDescription=" + playerName + ", null, null}", + Assert.assertEquals( + "MediaItem{mFlags=1, mDescription=" + playerName + ", null, null}", results.getChildren().get(0).getMediaItem().toString()); - //Fetch contents of that player object - BrowseTree.BrowseNode playerOneNode = mAvrcpStateMachine.findNode( - results.getChildren().get(0).getID()); + // Fetch contents of that player object + BrowseTree.BrowseNode playerOneNode = + mAvrcpStateMachine.findNode(results.getChildren().get(0).getID()); mAvrcpStateMachine.requestContents(playerOneNode); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .setBrowsedPlayer(eq(mTestAddress), eq(1)); @@ -790,7 +761,7 @@ public class AvrcpControllerStateMachineTest { /** * Test our reaction to an available players changed event * - * Verify that we issue a command to fetch the new available players + *

Verify that we issue a command to fetch the new available players */ @Test public void testAvailablePlayersChanged() { @@ -807,8 +778,8 @@ public class AvrcpControllerStateMachineTest { } /** - * Test how we handle receiving an available players list that contains the player we know to - * be the addressed player + * Test how we handle receiving an available players list that contains the player we know to be + * the addressed player */ @Test public void testAvailablePlayersReceived_AddressedPlayerExists() { @@ -836,14 +807,14 @@ public class AvrcpControllerStateMachineTest { // Send available players set that contains our addressed player byte[] playerFeatures = - new byte[]{0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; + new byte[] {0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; AvrcpPlayer playerOne = makePlayer(mTestDevice, 1, "Player 1", playerFeatures, 1); AvrcpPlayer playerTwo = makePlayer(mTestDevice, 2, "Player 2", playerFeatures, 1); List testPlayers = new ArrayList<>(); testPlayers.add(playerOne); testPlayers.add(playerTwo); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, - testPlayers); + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, testPlayers); // Wait for them to be processed TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); @@ -887,14 +858,14 @@ public class AvrcpControllerStateMachineTest { // Send available players set that does not contain the addressed player byte[] playerFeatures = - new byte[]{0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; + new byte[] {0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; AvrcpPlayer playerOne = makePlayer(mTestDevice, 1, "Player 1", playerFeatures, 1); AvrcpPlayer playerTwo = makePlayer(mTestDevice, 2, "Player 2", playerFeatures, 1); List testPlayers = new ArrayList<>(); testPlayers.add(playerOne); testPlayers.add(playerTwo); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, - testPlayers); + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, testPlayers); // Wait for them to be processed TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); @@ -921,8 +892,8 @@ public class AvrcpControllerStateMachineTest { } /** - * Test addressed media player changing to a player we know about - * Verify when the addressed media player changes browsing data updates + * Test addressed media player changing to a player we know about Verify when the addressed + * media player changes browsing data updates */ @Test public void testAddressedPlayerChangedToNewKnownPlayer() { @@ -930,24 +901,24 @@ public class AvrcpControllerStateMachineTest { // Get the root of the device BrowseTree.BrowseNode results = mAvrcpStateMachine.mBrowseTree.mRootNode; - //Request fetch the list of players + // Request fetch the list of players BrowseTree.BrowseNode playerNodes = mAvrcpStateMachine.findNode(results.getID()); mAvrcpStateMachine.requestContents(results); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .getPlayerList(eq(mTestAddress), eq(0), eq(19)); - //Provide back two player objects, IDs 1 and 2 + // Provide back two player objects, IDs 1 and 2 byte[] playerFeatures = - new byte[]{0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; + new byte[] {0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; AvrcpPlayer playerOne = makePlayer(mTestDevice, 1, "Player 1", playerFeatures, 1); AvrcpPlayer playerTwo = makePlayer(mTestDevice, 2, "Player 2", playerFeatures, 1); List testPlayers = new ArrayList<>(); testPlayers.add(playerOne); testPlayers.add(playerTwo); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, - testPlayers); + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, testPlayers); - //Set something arbitrary for the current Now Playing list + // Set something arbitrary for the current Now Playing list List nowPlayingList = new ArrayList(); nowPlayingList.add(makeNowPlayingItem(1, "Song 1")); nowPlayingList.add(makeNowPlayingItem(2, "Song 2")); @@ -955,7 +926,7 @@ public class AvrcpControllerStateMachineTest { clearInvocations(mAvrcpControllerService); clearInvocations(mNativeInterface); - //Change players and verify that BT attempts to update the results + // Change players and verify that BT attempts to update the results mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_ADDRESSED_PLAYER_CHANGED, 2); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); @@ -965,7 +936,7 @@ public class AvrcpControllerStateMachineTest { SparseArray players = mAvrcpStateMachine.getAvailablePlayers(); Assert.assertTrue(players.contains(mAvrcpStateMachine.getAddressedPlayerId())); - //Make sure the Now Playing list is now cleared + // Make sure the Now Playing list is now cleared assertNowPlayingList(new ArrayList()); // Verify that a player change to a player with Now Playing support causes a refresh. @@ -980,9 +951,9 @@ public class AvrcpControllerStateMachineTest { } /** - * Test addressed media player change to a player we don't know about - * Verify when the addressed media player changes browsing data updates - * Verify that the contents of a player are fetched upon request + * Test addressed media player change to a player we don't know about Verify when the addressed + * media player changes browsing data updates Verify that the contents of a player are fetched + * upon request */ @Test public void testAddressedPlayerChangedToUnknownPlayer() { @@ -991,31 +962,31 @@ public class AvrcpControllerStateMachineTest { // Get the root of the device BrowseTree.BrowseNode rootNode = mAvrcpStateMachine.mBrowseTree.mRootNode; - //Request fetch the list of players + // Request fetch the list of players BrowseTree.BrowseNode playerNodes = mAvrcpStateMachine.findNode(rootNode.getID()); mAvrcpStateMachine.requestContents(rootNode); - //Provide back a player object + // Provide back a player object byte[] playerFeatures = - new byte[]{0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; + new byte[] {0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; AvrcpPlayer playerOne = makePlayer(mTestDevice, 1, "Player 1", playerFeatures, 1); List testPlayers = new ArrayList<>(); testPlayers.add(playerOne); mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, testPlayers); - //Set something arbitrary for the current Now Playing list + // Set something arbitrary for the current Now Playing list List nowPlayingList = new ArrayList(); nowPlayingList.add(makeNowPlayingItem(1, "Song 1")); nowPlayingList.add(makeNowPlayingItem(2, "Song 2")); setNowPlayingList(nowPlayingList); - //Change players + // Change players mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_ADDRESSED_PLAYER_CHANGED, 4); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); - //Make sure the Now Playing list is now cleared and we requested metadata + // Make sure the Now Playing list is now cleared and we requested metadata assertNowPlayingList(new ArrayList()); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) .getCurrentMetadata(eq(mTestAddress)); @@ -1027,7 +998,7 @@ public class AvrcpControllerStateMachineTest { * Test what we do when we receive an addressed player change to a player with the same ID as * the current addressed play. * - * Verify we assume nothing and re-fetch the current metadata and playback status. + *

Verify we assume nothing and re-fetch the current metadata and playback status. */ @Test public void testAddressedPlayerChangedToSamePlayerId() { @@ -1046,20 +1017,20 @@ public class AvrcpControllerStateMachineTest { // Get the root of the device BrowseTree.BrowseNode rootNode = mAvrcpStateMachine.mBrowseTree.mRootNode; - //Request fetch the list of players + // Request fetch the list of players BrowseTree.BrowseNode playerNodes = mAvrcpStateMachine.findNode(rootNode.getID()); mAvrcpStateMachine.requestContents(rootNode); // Send available players set that contains our addressed player byte[] playerFeatures = - new byte[]{0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; + new byte[] {0, 0, 0, 0, 0, (byte) 0xb7, 0x01, 0x0c, 0x0a, 0, 0, 0, 0, 0, 0, 0}; AvrcpPlayer playerOne = makePlayer(mTestDevice, 1, "Player 1", playerFeatures, 1); AvrcpPlayer playerTwo = makePlayer(mTestDevice, 2, "Player 2", playerFeatures, 1); List testPlayers = new ArrayList<>(); testPlayers.add(playerOne); testPlayers.add(playerTwo); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, - testPlayers); + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_PLAYER_ITEMS, testPlayers); // Wait until idle so Now Playing List is queried for again, resolve it again TestUtils.waitForLooperToBeIdle(mAvrcpStateMachine.getHandler().getLooper()); @@ -1084,9 +1055,7 @@ public class AvrcpControllerStateMachineTest { .getPlaybackState(eq(mTestAddress)); } - /** - * Test that the Now Playing playlist is updated when it changes. - */ + /** Test that the Now Playing playlist is updated when it changes. */ @Test public void testNowPlaying() { setUpConnectedState(true, true); @@ -1095,9 +1064,7 @@ public class AvrcpControllerStateMachineTest { .getNowPlayingList(eq(mTestAddress), eq(0), eq(19)); } - /** - * Test that AVRCP events such as playback commands can execute while performing browsing. - */ + /** Test that AVRCP events such as playback commands can execute while performing browsing. */ @Test public void testPlayWhileBrowsing() { setUpConnectedState(true, true); @@ -1106,7 +1073,7 @@ public class AvrcpControllerStateMachineTest { // Get the root of the device BrowseTree.BrowseNode results = mAvrcpStateMachine.mBrowseTree.mRootNode; - //Request fetch the list of players + // Request fetch the list of players BrowseTree.BrowseNode playerNodes = mAvrcpStateMachine.findNode(results.getID()); mAvrcpStateMachine.requestContents(results); @@ -1125,9 +1092,7 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test that Absolute Volume Registration is working - */ + /** Test that Absolute Volume Registration is working */ @Test public void testRegisterAbsVolumeNotification() { byte label = 42; @@ -1187,9 +1152,7 @@ public class AvrcpControllerStateMachineTest { .sendAbsVolRsp(any(), eq(127), eq((int) label)); } - /** - * Test playback does not request focus when another app is playing music. - */ + /** Test playback does not request focus when another app is playing music. */ @Test public void testPlaybackWhileMusicPlaying() { when(mMockResources.getBoolean(R.bool.a2dp_sink_automatically_request_audio_focus)) @@ -1209,9 +1172,7 @@ public class AvrcpControllerStateMachineTest { verify(mA2dpSinkService, never()).requestAudioFocus(mTestDevice, true); } - /** - * Test playback requests focus while nothing is playing music. - */ + /** Test playback requests focus while nothing is playing music. */ @Test public void testPlaybackWhileIdle() { when(mA2dpSinkService.getFocusState()).thenReturn(AudioManager.AUDIOFOCUS_NONE); @@ -1225,10 +1186,10 @@ public class AvrcpControllerStateMachineTest { } /** - * Test receiving a playback status of playing while we're in an error state - * as it relates to getting audio focus. + * Test receiving a playback status of playing while we're in an error state as it relates to + * getting audio focus. * - * Verify we send a pause command and never attempt to request audio focus + *

Verify we send a pause command and never attempt to request audio focus */ @Test public void testPlaybackWhileErrorState() { @@ -1249,7 +1210,7 @@ public class AvrcpControllerStateMachineTest { /** * Test receiving a playback status of playing while we have focus * - * Verify we do not send a pause command and never attempt to request audio focus + *

Verify we do not send a pause command and never attempt to request audio focus */ @Test public void testPlaybackWhilePlayingState() { @@ -1268,26 +1229,20 @@ public class AvrcpControllerStateMachineTest { verify(mA2dpSinkService, never()).requestAudioFocus(mTestDevice, true); } - /** - * Test that isActive() reports the proper value when we're active - */ + /** Test that isActive() reports the proper value when we're active */ @Test public void testIsActive_deviceActive() { Assert.assertTrue(mAvrcpStateMachine.isActive()); } - /** - * Test that isActive() reports the proper value when we're inactive - */ + /** Test that isActive() reports the proper value when we're inactive */ @Test public void testIsActive_deviceInactive() { setActiveDevice(null); Assert.assertFalse(mAvrcpStateMachine.isActive()); } - /** - * Test becoming active from the inactive state - */ + /** Test becoming active from the inactive state */ @Test public void testBecomeActive() { // Note device starts as active in setUp() and state cascades come the CONNECTED state @@ -1344,9 +1299,7 @@ public class AvrcpControllerStateMachineTest { Assert.assertEquals("title 2", queue.get(1).getDescription().getTitle().toString()); } - /** - * Test becoming inactive from the active state - */ + /** Test becoming inactive from the active state */ @Test public void testBecomeInactive() { // Note device starts as active in setUp() @@ -1428,9 +1381,7 @@ public class AvrcpControllerStateMachineTest { Assert.assertEquals(1, playbackState.getActiveQueueItemId()); } - /** - * Test receiving a track change update when we're not the active device - */ + /** Test receiving a track change update when we're not the active device */ @Test public void testTrackChangeWhileNotActiveDevice() { setUpConnectedState(true, true); @@ -1455,9 +1406,7 @@ public class AvrcpControllerStateMachineTest { Assert.assertNull(metadata); // track starts as null and shouldn't change } - /** - * Test receiving a playback status of playing when we're not the active device - */ + /** Test receiving a playback status of playing when we're not the active device */ @Test public void testPlaybackWhileNotActiveDevice() { setUpConnectedState(true, true); @@ -1480,13 +1429,12 @@ public class AvrcpControllerStateMachineTest { eq(AvrcpControllerService.PASS_THRU_CMD_ID_PAUSE), eq(KEY_DOWN)); verify(mA2dpSinkService, never()).requestAudioFocus(mTestDevice, true); - Assert.assertEquals(PlaybackStateCompat.STATE_ERROR, + Assert.assertEquals( + PlaybackStateCompat.STATE_ERROR, BluetoothMediaBrowserService.getPlaybackState().getState()); } - /** - * Test receiving a play position update when we're not the active device - */ + /** Test receiving a play position update when we're not the active device */ @Test public void testPlayPositionChangeWhileNotActiveDevice() { setUpConnectedState(true, true); @@ -1512,9 +1460,7 @@ public class AvrcpControllerStateMachineTest { Assert.assertEquals(0, playbackState.getPosition()); } - /** - * Test receiving a now playing list update when we're not the active device - */ + /** Test receiving a now playing list update when we're not the active device */ @Test public void testNowPlayingListChangeWhileNotActiveDevice() { setUpConnectedState(true, true); @@ -1616,9 +1562,7 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test receiving an audio focus loss event. A pause should be sent if we were playing - */ + /** Test receiving an audio focus loss event. A pause should be sent if we were playing */ @Test public void testOnAudioFocusLossWhilePlaying_pauseSent() { setUpConnectedState(true, true); @@ -1639,9 +1583,7 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test receiving an audio focus loss event. A pause should not be sent if we were paused - */ + /** Test receiving an audio focus loss event. A pause should not be sent if we were paused */ @Test public void testOnAudioFocusLossWhilePause_pauseNotSent() { setUpConnectedState(true, true); @@ -1687,9 +1629,7 @@ public class AvrcpControllerStateMachineTest { eq(KEY_UP)); } - /** - * Test receiving an audio focus changed event following a transient loss where - */ + /** Test receiving an audio focus changed event following a transient loss where */ @Test public void testOnAudioFocusGainFromTransientLossWhilePlayingWithPause_playNotSent() { testOnAudioFocusTransientLossWhilePlaying_pauseSent(); @@ -1822,7 +1762,8 @@ public class AvrcpControllerStateMachineTest { // Verify download attempt and send some elements over, verify next set is requested verify(mNativeInterface, times(1)).getNowPlayingList(eq(mTestAddress), eq(0), eq(19)); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(nowPlayingList.subList(0, 20))); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); verify(mNativeInterface, times(1)).getNowPlayingList(eq(mTestAddress), eq(20), eq(39)); @@ -1833,15 +1774,18 @@ public class AvrcpControllerStateMachineTest { // Send requested items, they're likely from the new list at this point, but it shouldn't // matter what they are because we should toss them out and restart our download next. - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(nowPlayingList.subList(20, 25))); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); verify(mNativeInterface, times(2)).getNowPlayingList(eq(mTestAddress), eq(0), eq(19)); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(updatedNowPlayingList.subList(0, 20))); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(updatedNowPlayingList.subList(20, 25))); mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS_OUT_OF_RANGE); @@ -1887,7 +1831,8 @@ public class AvrcpControllerStateMachineTest { verify(mNativeInterface, times(1)).getNowPlayingList(eq(mTestAddress), eq(0), eq(19)); mAvrcpStateMachine.nowPlayingContentChanged(); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(nowPlayingList.subList(0, 20))); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); @@ -1896,9 +1841,11 @@ public class AvrcpControllerStateMachineTest { verify(mNativeInterface, times(2)).getNowPlayingList(eq(mTestAddress), eq(0), eq(19)); // Send whole list - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(updatedNowPlayingList.subList(0, 20))); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(updatedNowPlayingList.subList(20, 25))); mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS_OUT_OF_RANGE); @@ -1942,7 +1889,8 @@ public class AvrcpControllerStateMachineTest { // Verify download attempt and send some elements over, verify next set is requested verify(mNativeInterface, times(1)).getNowPlayingList(eq(mTestAddress), eq(0), eq(19)); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(nowPlayingList.subList(0, 20))); TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); verify(mNativeInterface, times(1)).getNowPlayingList(eq(mTestAddress), eq(20), eq(39)); @@ -1954,15 +1902,18 @@ public class AvrcpControllerStateMachineTest { // Send requested items, they're likely from the new list at this point, but it shouldn't // matter what they are because we should toss them out and restart our download next. - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(nowPlayingList.subList(20, 25))); TestUtils.waitForLooperToBeIdle(mAvrcpStateMachine.getHandler().getLooper()); verify(mNativeInterface, times(2)).getNowPlayingList(eq(mTestAddress), eq(0), eq(19)); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(updatedNowPlayingList.subList(0, 20))); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(updatedNowPlayingList.subList(20, 25))); mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS_OUT_OF_RANGE); @@ -2014,7 +1965,8 @@ public class AvrcpControllerStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mAvrcpStateMachine.getHandler().getLooper()); // Now, send the items in and let it process - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(nowPlayingList.subList(0, 20))); TestUtils.waitForLooperToBeIdle(mAvrcpStateMachine.getHandler().getLooper()); @@ -2022,9 +1974,11 @@ public class AvrcpControllerStateMachineTest { // Send requested items, they're likely from the new list at this point, but it shouldn't // matter what they are because we should toss them out and restart our download next. - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(updatedNowPlayingList.subList(0, 20))); - mAvrcpStateMachine.sendMessage(AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, + mAvrcpStateMachine.sendMessage( + AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS, new ArrayList(updatedNowPlayingList.subList(20, 25))); mAvrcpStateMachine.sendMessage( AvrcpControllerStateMachine.MESSAGE_PROCESS_GET_FOLDER_ITEMS_OUT_OF_RANGE); @@ -2047,7 +2001,7 @@ public class AvrcpControllerStateMachineTest { setUpConnectedState(true, true); sendAudioFocusUpdate(AudioManager.AUDIOFOCUS_GAIN); - //Set something arbitrary for the current Now Playing list + // Set something arbitrary for the current Now Playing list List nowPlayingList = new ArrayList(); nowPlayingList.add(makeNowPlayingItem(1, "Song 1")); setNowPlayingList(nowPlayingList); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProviderTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProviderTest.java index ddddbd08fe2..7514f3a5215 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProviderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProviderTest.java @@ -48,14 +48,13 @@ import java.io.FileNotFoundException; public class AvrcpCoverArtProviderTest { private static final String TEST_MODE = "test_mode"; - private final byte[] mTestAddress = new byte[]{01, 01, 01, 01, 01, 01}; + private final byte[] mTestAddress = new byte[] {01, 01, 01, 01, 01, 01}; private BluetoothAdapter mAdapter; private BluetoothDevice mTestDevice = null; private AvrcpCoverArtProvider mArtProvider; - @Rule - public final ServiceTestRule mServiceRule = new ServiceTestRule(); + @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule(); @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock private Uri mUri; @@ -111,8 +110,12 @@ public class AvrcpCoverArtProviderTest { @Test public void getImageUri_withValidImageUuid() { String uuid = "1111"; - Uri expectedUri = AvrcpCoverArtProvider.CONTENT_URI.buildUpon().appendQueryParameter( - "device", mTestDevice.getAddress()).appendQueryParameter("uuid", uuid).build(); + Uri expectedUri = + AvrcpCoverArtProvider.CONTENT_URI + .buildUpon() + .appendQueryParameter("device", mTestDevice.getAddress()) + .appendQueryParameter("uuid", uuid) + .build(); assertThat(AvrcpCoverArtProvider.getImageUri(mTestDevice, uuid)).isEqualTo(expectedUri); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java index 903a4277d94..f11054f05ca 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java @@ -37,9 +37,7 @@ import org.junit.runner.RunWith; import java.io.InputStream; -/** - * A test suite for the AvrcpCoverArtStorage class. - */ +/** A test suite for the AvrcpCoverArtStorage class. */ @RunWith(AndroidJUnit4.class) public final class AvrcpCoverArtStorageTest { private Context mTargetContext; @@ -58,11 +56,11 @@ public final class AvrcpCoverArtStorageTest { mTestResources = TestUtils.getTestApplicationResources(mTargetContext); mDevice1 = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("AA:BB:CC:DD:EE:FF"); mDevice2 = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("BB:CC:DD:EE:FF:AA"); - InputStream is = mTestResources.openRawResource( - com.android.bluetooth.tests.R.raw.image_200_200); + InputStream is = + mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_200_200); mImage1 = BitmapFactory.decodeStream(is); - InputStream is2 = mTestResources.openRawResource( - com.android.bluetooth.tests.R.raw.image_600_600); + InputStream is2 = + mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_600_600); mImage2 = BitmapFactory.decodeStream(is2); mAvrcpCoverArtStorage = new AvrcpCoverArtStorage(mTargetContext); @@ -332,8 +330,15 @@ public final class AvrcpCoverArtStorageTest { @Test public void toString_returnsDeviceInfo() { String expectedString = - "CoverArtStorage:\n" + " " + mDevice1 + " (" + 1 + "):" + "\n " - + mHandle1 + "\n"; + "CoverArtStorage:\n" + + " " + + mDevice1 + + " (" + + 1 + + "):" + + "\n " + + mHandle1 + + "\n"; mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java index a3f0715021e..55257a5365e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java @@ -33,16 +33,14 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -/** - * A test suite for the AvrcpItem class. - */ +/** A test suite for the AvrcpItem class. */ @RunWith(AndroidJUnit4.class) public final class AvrcpItemTest { private BluetoothDevice mDevice; private static final String UUID = "AVRCP-ITEM-TEST-UUID"; - // Attribute ID Values from AVRCP Specification + // Attribute ID Values from AVRCP Specification private static final int MEDIA_ATTRIBUTE_TITLE = 0x01; private static final int MEDIA_ATTRIBUTE_ARTIST_NAME = 0x02; private static final int MEDIA_ATTRIBUTE_ALBUM_NAME = 0x03; @@ -121,27 +119,22 @@ public final class AvrcpItemTest { String playingTime = "301"; String artHandle = "0000001"; - int[] attrIds = new int[]{ - MEDIA_ATTRIBUTE_TITLE, - MEDIA_ATTRIBUTE_ARTIST_NAME, - MEDIA_ATTRIBUTE_ALBUM_NAME, - MEDIA_ATTRIBUTE_TRACK_NUMBER, - MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, - MEDIA_ATTRIBUTE_GENRE, - MEDIA_ATTRIBUTE_PLAYING_TIME, - MEDIA_ATTRIBUTE_COVER_ART_HANDLE - }; - - String[] attrMap = new String[]{ - title, - artist, - album, - trackNumber, - totalTracks, - genre, - playingTime, - artHandle - }; + int[] attrIds = + new int[] { + MEDIA_ATTRIBUTE_TITLE, + MEDIA_ATTRIBUTE_ARTIST_NAME, + MEDIA_ATTRIBUTE_ALBUM_NAME, + MEDIA_ATTRIBUTE_TRACK_NUMBER, + MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, + MEDIA_ATTRIBUTE_GENRE, + MEDIA_ATTRIBUTE_PLAYING_TIME, + MEDIA_ATTRIBUTE_COVER_ART_HANDLE + }; + + String[] attrMap = + new String[] { + title, artist, album, trackNumber, totalTracks, genre, playingTime, artHandle + }; AvrcpItem.Builder builder = new AvrcpItem.Builder(); builder.fromAvrcpAttributeArray(attrIds, attrMap); @@ -173,35 +166,37 @@ public final class AvrcpItemTest { String playingTime = "301"; String artHandle = "0000001"; - int[] attrIds = new int[]{ - MEDIA_ATTRIBUTE_TITLE, - MEDIA_ATTRIBUTE_ARTIST_NAME, - MEDIA_ATTRIBUTE_ALBUM_NAME, - MEDIA_ATTRIBUTE_TRACK_NUMBER, - MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, - MEDIA_ATTRIBUTE_GENRE, - MEDIA_ATTRIBUTE_PLAYING_TIME, - MEDIA_ATTRIBUTE_COVER_ART_HANDLE, - 75, - 76, - 77, - 78 - }; - - String[] attrMap = new String[]{ - title, - artist, - album, - trackNumber, - totalTracks, - genre, - playingTime, - artHandle, - "ignore me", - "ignore me", - "ignore me", - "ignore me" - }; + int[] attrIds = + new int[] { + MEDIA_ATTRIBUTE_TITLE, + MEDIA_ATTRIBUTE_ARTIST_NAME, + MEDIA_ATTRIBUTE_ALBUM_NAME, + MEDIA_ATTRIBUTE_TRACK_NUMBER, + MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, + MEDIA_ATTRIBUTE_GENRE, + MEDIA_ATTRIBUTE_PLAYING_TIME, + MEDIA_ATTRIBUTE_COVER_ART_HANDLE, + 75, + 76, + 77, + 78 + }; + + String[] attrMap = + new String[] { + title, + artist, + album, + trackNumber, + totalTracks, + genre, + playingTime, + artHandle, + "ignore me", + "ignore me", + "ignore me", + "ignore me" + }; AvrcpItem.Builder builder = new AvrcpItem.Builder(); builder.fromAvrcpAttributeArray(attrIds, attrMap); @@ -233,27 +228,22 @@ public final class AvrcpItemTest { String playingTime = "301"; String artHandle = "000001"; // length 6 and not 7 - int[] attrIds = new int[]{ - MEDIA_ATTRIBUTE_TITLE, - MEDIA_ATTRIBUTE_ARTIST_NAME, - MEDIA_ATTRIBUTE_ALBUM_NAME, - MEDIA_ATTRIBUTE_TRACK_NUMBER, - MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, - MEDIA_ATTRIBUTE_GENRE, - MEDIA_ATTRIBUTE_PLAYING_TIME, - MEDIA_ATTRIBUTE_COVER_ART_HANDLE - }; - - String[] attrMap = new String[]{ - title, - artist, - album, - trackNumber, - totalTracks, - genre, - playingTime, - artHandle - }; + int[] attrIds = + new int[] { + MEDIA_ATTRIBUTE_TITLE, + MEDIA_ATTRIBUTE_ARTIST_NAME, + MEDIA_ATTRIBUTE_ALBUM_NAME, + MEDIA_ATTRIBUTE_TRACK_NUMBER, + MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, + MEDIA_ATTRIBUTE_GENRE, + MEDIA_ATTRIBUTE_PLAYING_TIME, + MEDIA_ATTRIBUTE_COVER_ART_HANDLE + }; + + String[] attrMap = + new String[] { + title, artist, album, trackNumber, totalTracks, genre, playingTime, artHandle + }; AvrcpItem.Builder builder = new AvrcpItem.Builder(); builder.fromAvrcpAttributeArray(attrIds, attrMap); @@ -285,27 +275,22 @@ public final class AvrcpItemTest { String playingTime = "301"; String artHandle = ""; - int[] attrIds = new int[]{ - MEDIA_ATTRIBUTE_TITLE, - MEDIA_ATTRIBUTE_ARTIST_NAME, - MEDIA_ATTRIBUTE_ALBUM_NAME, - MEDIA_ATTRIBUTE_TRACK_NUMBER, - MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, - MEDIA_ATTRIBUTE_GENRE, - MEDIA_ATTRIBUTE_PLAYING_TIME, - MEDIA_ATTRIBUTE_COVER_ART_HANDLE - }; - - String[] attrMap = new String[]{ - title, - artist, - album, - trackNumber, - totalTracks, - genre, - playingTime, - artHandle - }; + int[] attrIds = + new int[] { + MEDIA_ATTRIBUTE_TITLE, + MEDIA_ATTRIBUTE_ARTIST_NAME, + MEDIA_ATTRIBUTE_ALBUM_NAME, + MEDIA_ATTRIBUTE_TRACK_NUMBER, + MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, + MEDIA_ATTRIBUTE_GENRE, + MEDIA_ATTRIBUTE_PLAYING_TIME, + MEDIA_ATTRIBUTE_COVER_ART_HANDLE + }; + + String[] attrMap = + new String[] { + title, artist, album, trackNumber, totalTracks, genre, playingTime, artHandle + }; AvrcpItem.Builder builder = new AvrcpItem.Builder(); builder.fromAvrcpAttributeArray(attrIds, attrMap); @@ -337,27 +322,22 @@ public final class AvrcpItemTest { String playingTime = "301"; String artHandle = null; - int[] attrIds = new int[]{ - MEDIA_ATTRIBUTE_TITLE, - MEDIA_ATTRIBUTE_ARTIST_NAME, - MEDIA_ATTRIBUTE_ALBUM_NAME, - MEDIA_ATTRIBUTE_TRACK_NUMBER, - MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, - MEDIA_ATTRIBUTE_GENRE, - MEDIA_ATTRIBUTE_PLAYING_TIME, - MEDIA_ATTRIBUTE_COVER_ART_HANDLE - }; - - String[] attrMap = new String[]{ - title, - artist, - album, - trackNumber, - totalTracks, - genre, - playingTime, - artHandle - }; + int[] attrIds = + new int[] { + MEDIA_ATTRIBUTE_TITLE, + MEDIA_ATTRIBUTE_ARTIST_NAME, + MEDIA_ATTRIBUTE_ALBUM_NAME, + MEDIA_ATTRIBUTE_TRACK_NUMBER, + MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, + MEDIA_ATTRIBUTE_GENRE, + MEDIA_ATTRIBUTE_PLAYING_TIME, + MEDIA_ATTRIBUTE_COVER_ART_HANDLE + }; + + String[] attrMap = + new String[] { + title, artist, album, trackNumber, totalTracks, genre, playingTime, artHandle + }; AvrcpItem.Builder builder = new AvrcpItem.Builder(); builder.fromAvrcpAttributeArray(attrIds, attrMap); @@ -389,27 +369,22 @@ public final class AvrcpItemTest { String playingTime = "301"; String artHandle = "123abcd"; - int[] attrIds = new int[]{ - MEDIA_ATTRIBUTE_TITLE, - MEDIA_ATTRIBUTE_ARTIST_NAME, - MEDIA_ATTRIBUTE_ALBUM_NAME, - MEDIA_ATTRIBUTE_TRACK_NUMBER, - MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, - MEDIA_ATTRIBUTE_GENRE, - MEDIA_ATTRIBUTE_PLAYING_TIME, - MEDIA_ATTRIBUTE_COVER_ART_HANDLE - }; - - String[] attrMap = new String[]{ - title, - artist, - album, - trackNumber, - totalTracks, - genre, - playingTime, - artHandle - }; + int[] attrIds = + new int[] { + MEDIA_ATTRIBUTE_TITLE, + MEDIA_ATTRIBUTE_ARTIST_NAME, + MEDIA_ATTRIBUTE_ALBUM_NAME, + MEDIA_ATTRIBUTE_TRACK_NUMBER, + MEDIA_ATTRIBUTE_TOTAL_TRACK_NUMBER, + MEDIA_ATTRIBUTE_GENRE, + MEDIA_ATTRIBUTE_PLAYING_TIME, + MEDIA_ATTRIBUTE_COVER_ART_HANDLE + }; + + String[] attrMap = + new String[] { + title, artist, album, trackNumber, totalTracks, genre, playingTime, artHandle + }; AvrcpItem.Builder builder = new AvrcpItem.Builder(); builder.fromAvrcpAttributeArray(attrIds, attrMap); @@ -479,26 +454,27 @@ public final class AvrcpItemTest { MediaMetadataCompat metadata = item.toMediaMetadata(); Assert.assertEquals(UUID, metadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID)); - Assert.assertEquals(title, - metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE)); + Assert.assertEquals( + title, metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE)); Assert.assertEquals(title, metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE)); Assert.assertEquals(artist, metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST)); Assert.assertEquals(album, metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM)); - Assert.assertEquals(trackNumber, - metadata.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER)); - Assert.assertEquals(totalTracks, - metadata.getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS)); + Assert.assertEquals( + trackNumber, metadata.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER)); + Assert.assertEquals( + totalTracks, metadata.getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS)); Assert.assertEquals(genre, metadata.getString(MediaMetadataCompat.METADATA_KEY_GENRE)); - Assert.assertEquals(playingTime, - metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION)); - Assert.assertEquals(uri, + Assert.assertEquals( + playingTime, metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION)); + Assert.assertEquals( + uri, Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI))); - Assert.assertEquals(uri, - Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ART_URI))); - Assert.assertEquals(uri, - Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI))); - Assert.assertEquals(null, - metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON)); + Assert.assertEquals( + uri, Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ART_URI))); + Assert.assertEquals( + uri, Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI))); + Assert.assertEquals( + null, metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON)); Assert.assertEquals(null, metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ART)); Assert.assertEquals(null, metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART)); Assert.assertFalse(metadata.containsKey(MediaMetadataCompat.METADATA_KEY_BT_FOLDER_TYPE)); @@ -533,28 +509,29 @@ public final class AvrcpItemTest { MediaMetadataCompat metadata = item.toMediaMetadata(); Assert.assertEquals(UUID, metadata.getString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID)); - Assert.assertEquals(title, - metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE)); + Assert.assertEquals( + title, metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE)); Assert.assertEquals(title, metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE)); Assert.assertEquals(artist, metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST)); Assert.assertEquals(null, metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM)); - Assert.assertEquals(totalTracks, - metadata.getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS)); + Assert.assertEquals( + totalTracks, metadata.getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS)); Assert.assertEquals(genre, metadata.getString(MediaMetadataCompat.METADATA_KEY_GENRE)); - Assert.assertEquals(playingTime, - metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION)); - Assert.assertEquals(uri, + Assert.assertEquals( + playingTime, metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION)); + Assert.assertEquals( + uri, Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI))); - Assert.assertEquals(uri, - Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ART_URI))); - Assert.assertEquals(uri, - Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI))); - Assert.assertEquals(null, - metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON)); + Assert.assertEquals( + uri, Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ART_URI))); + Assert.assertEquals( + uri, Uri.parse(metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI))); + Assert.assertEquals( + null, metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON)); Assert.assertEquals(null, metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ART)); Assert.assertEquals(null, metadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART)); - Assert.assertEquals(type, - metadata.getLong(MediaMetadataCompat.METADATA_KEY_BT_FOLDER_TYPE)); + Assert.assertEquals( + type, metadata.getLong(MediaMetadataCompat.METADATA_KEY_BT_FOLDER_TYPE)); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java index 5740a8086dc..33eeb5d2b24 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java @@ -40,14 +40,13 @@ public class AvrcpPlayerTest { private static final int TEST_PLAY_TIME = 1; private final AvrcpItem mAvrcpItem = new AvrcpItem.Builder().build(); - private final byte[] mTestAddress = new byte[]{01, 01, 01, 01, 01, 01}; + private final byte[] mTestAddress = new byte[] {01, 01, 01, 01, 01, 01}; private BluetoothAdapter mAdapter; private BluetoothDevice mTestDevice = null; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private PlayerApplicationSettings mPlayerApplicationSettings; + @Mock private PlayerApplicationSettings mPlayerApplicationSettings; @Before public void setUp() { @@ -73,8 +72,8 @@ public class AvrcpPlayerTest { assertThat(avrcpPlayer.supportsFeature(TEST_FEATURE)).isTrue(); assertThat(avrcpPlayer.getPlayStatus()).isEqualTo(TEST_PLAY_STATUS); assertThat(avrcpPlayer.getCurrentTrack()).isEqualTo(mAvrcpItem); - assertThat(avrcpPlayer.getPlaybackState().getActions()).isEqualTo( - PlaybackStateCompat.ACTION_PREPARE | PlaybackStateCompat.ACTION_PLAY); + assertThat(avrcpPlayer.getPlaybackState().getActions()) + .isEqualTo(PlaybackStateCompat.ACTION_PREPARE | PlaybackStateCompat.ACTION_PLAY); } @Test @@ -106,13 +105,14 @@ public class AvrcpPlayerTest { @Test public void setSupportedPlayerApplicationSettings() { - when(mPlayerApplicationSettings.supportsSetting( - PlayerApplicationSettings.REPEAT_STATUS)).thenReturn(true); - when(mPlayerApplicationSettings.supportsSetting( - PlayerApplicationSettings.SHUFFLE_STATUS)).thenReturn(true); + when(mPlayerApplicationSettings.supportsSetting(PlayerApplicationSettings.REPEAT_STATUS)) + .thenReturn(true); + when(mPlayerApplicationSettings.supportsSetting(PlayerApplicationSettings.SHUFFLE_STATUS)) + .thenReturn(true); AvrcpPlayer avrcpPlayer = new AvrcpPlayer.Builder().build(); long expectedActions = - PlaybackStateCompat.ACTION_PREPARE | PlaybackStateCompat.ACTION_SET_REPEAT_MODE + PlaybackStateCompat.ACTION_PREPARE + | PlaybackStateCompat.ACTION_SET_REPEAT_MODE | PlaybackStateCompat.ACTION_SET_SHUFFLE_MODE; avrcpPlayer.setSupportedPlayerApplicationSettings(mPlayerApplicationSettings); @@ -124,8 +124,8 @@ public class AvrcpPlayerTest { public void supportsSetting() { int settingType = 1; int settingValue = 1; - when(mPlayerApplicationSettings.supportsSetting(settingType, settingValue)).thenReturn( - true); + when(mPlayerApplicationSettings.supportsSetting(settingType, settingValue)) + .thenReturn(true); AvrcpPlayer avrcpPlayer = new AvrcpPlayer.Builder().build(); avrcpPlayer.setSupportedPlayerApplicationSettings(mPlayerApplicationSettings); @@ -142,21 +142,29 @@ public class AvrcpPlayerTest { setSupportedFeature(supportedFeatures, AvrcpPlayer.FEATURE_FAST_FORWARD); setSupportedFeature(supportedFeatures, AvrcpPlayer.FEATURE_FORWARD); setSupportedFeature(supportedFeatures, AvrcpPlayer.FEATURE_PREVIOUS); - long expectedActions = PlaybackStateCompat.ACTION_PREPARE | PlaybackStateCompat.ACTION_STOP - | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_REWIND - | PlaybackStateCompat.ACTION_FAST_FORWARD | PlaybackStateCompat.ACTION_SKIP_TO_NEXT - | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; + long expectedActions = + PlaybackStateCompat.ACTION_PREPARE + | PlaybackStateCompat.ACTION_STOP + | PlaybackStateCompat.ACTION_PAUSE + | PlaybackStateCompat.ACTION_REWIND + | PlaybackStateCompat.ACTION_FAST_FORWARD + | PlaybackStateCompat.ACTION_SKIP_TO_NEXT + | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; - AvrcpPlayer avrcpPlayer = new AvrcpPlayer.Builder().setSupportedFeatures( - supportedFeatures).build(); + AvrcpPlayer avrcpPlayer = + new AvrcpPlayer.Builder().setSupportedFeatures(supportedFeatures).build(); assertThat(avrcpPlayer.getPlaybackState().getActions()).isEqualTo(expectedActions); } @Test public void toString_returnsInfo() { - AvrcpPlayer avrcpPlayer = new AvrcpPlayer.Builder().setPlayerId(TEST_PLAYER_ID).setName( - TEST_NAME).setCurrentTrack(mAvrcpItem).build(); + AvrcpPlayer avrcpPlayer = + new AvrcpPlayer.Builder() + .setPlayerId(TEST_PLAYER_ID) + .setName(TEST_NAME) + .setCurrentTrack(mAvrcpItem) + .build(); assertThat(avrcpPlayer.toString()).isNotNull(); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java index cabdc9a18d2..c384dab35a2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java @@ -40,7 +40,7 @@ public class BrowseNodeTest { private static final String TEST_UUID = "1111"; private static final String TEST_NAME = "item"; - private final byte[] mTestAddress = new byte[]{01, 01, 01, 01, 01, 01}; + private final byte[] mTestAddress = new byte[] {01, 01, 01, 01, 01, 01}; private BluetoothAdapter mAdapter; private BluetoothDevice mTestDevice = null; private BrowseTree mBrowseTree; @@ -56,9 +56,14 @@ public class BrowseNodeTest { @Test public void constructor_withAvrcpPlayer() { - BrowseNode browseNode = mBrowseTree.new BrowseNode(new AvrcpPlayer.Builder().setDevice( - mTestDevice).setPlayerId(TEST_PLAYER_ID).setSupportedFeature( - AvrcpPlayer.FEATURE_BROWSING).build()); + BrowseNode browseNode = + mBrowseTree + .new BrowseNode( + new AvrcpPlayer.Builder() + .setDevice(mTestDevice) + .setPlayerId(TEST_PLAYER_ID) + .setSupportedFeature(AvrcpPlayer.FEATURE_BROWSING) + .build()); assertThat(browseNode.isPlayer()).isTrue(); assertThat(browseNode.getBluetoothID()).isEqualTo(TEST_PLAYER_ID); @@ -77,8 +82,8 @@ public class BrowseNodeTest { @Test public void addChildren() { - AvrcpPlayer childAvrcpPlayer = new AvrcpPlayer.Builder().setPlayerId( - TEST_PLAYER_ID).build(); + AvrcpPlayer childAvrcpPlayer = + new AvrcpPlayer.Builder().setPlayerId(TEST_PLAYER_ID).build(); AvrcpItem childAvrcpItem = new AvrcpItem.Builder().setUuid(TEST_UUID).build(); List children = new ArrayList<>(); children.add(childAvrcpPlayer); @@ -104,15 +109,15 @@ public class BrowseNodeTest { assertThat(mBrowseTree.mNowPlayingNode.isChild(browseNode)).isTrue(); assertThat(browseNode.getParent()).isEqualTo(mBrowseTree.mNowPlayingNode); - assertThat(browseNode.getScope()).isEqualTo( - AvrcpControllerService.BROWSE_SCOPE_NOW_PLAYING); + assertThat(browseNode.getScope()) + .isEqualTo(AvrcpControllerService.BROWSE_SCOPE_NOW_PLAYING); assertThat(mBrowseTree.getNodesUsingCoverArt(coverArtUuid).get(0)).isEqualTo(TEST_UUID); } @Test public void removeChild() { - BrowseNode browseNode = mBrowseTree.new BrowseNode( - new AvrcpItem.Builder().setUuid(TEST_UUID).build()); + BrowseNode browseNode = + mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build()); mRootNode.addChild(browseNode); assertThat(mRootNode.getChildrenCount()).isEqualTo(1); @@ -135,8 +140,8 @@ public class BrowseNodeTest { @Test public void setCached() { - BrowseNode browseNode = mBrowseTree.new BrowseNode( - new AvrcpItem.Builder().setUuid(TEST_UUID).build()); + BrowseNode browseNode = + mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build()); mRootNode.addChild(browseNode); assertThat(mRootNode.getChildrenCount()).isEqualTo(1); @@ -148,12 +153,12 @@ public class BrowseNodeTest { @Test public void getters() { - BrowseNode browseNode = mBrowseTree.new BrowseNode( - new AvrcpItem.Builder().setUuid(TEST_UUID).build()); + BrowseNode browseNode = + mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build()); assertThat(browseNode.getFolderUID()).isEqualTo(TEST_UUID); - assertThat(browseNode.getPlayerID()).isEqualTo( - Integer.parseInt((TEST_UUID).replace(BrowseTree.PLAYER_PREFIX, ""))); + assertThat(browseNode.getPlayerID()) + .isEqualTo(Integer.parseInt((TEST_UUID).replace(BrowseTree.PLAYER_PREFIX, ""))); } @Test @@ -165,18 +170,18 @@ public class BrowseNodeTest { @Test public void equals_withSameId() { - BrowseNode browseNodeOne = mBrowseTree.new BrowseNode( - new AvrcpItem.Builder().setUuid(TEST_UUID).build()); - BrowseNode browseNodeTwo = mBrowseTree.new BrowseNode( - new AvrcpItem.Builder().setUuid(TEST_UUID).build()); + BrowseNode browseNodeOne = + mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build()); + BrowseNode browseNodeTwo = + mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build()); assertThat(browseNodeOne).isEqualTo(browseNodeTwo); } @Test public void isDescendant() { - BrowseNode browseNode = mBrowseTree.new BrowseNode( - new AvrcpItem.Builder().setUuid(TEST_UUID).build()); + BrowseNode browseNode = + mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build()); mRootNode.addChild(browseNode); assertThat(mRootNode.isDescendant(browseNode)).isTrue(); @@ -184,27 +189,40 @@ public class BrowseNodeTest { @Test public void toTreeString_returnFormattedString() { - final String expected = " [Id: 1111 Name: item Size: 2]\n" - + " [Id: child1 Name: child1 Size: 1]\n" - + " [Id: child3 Name: child3 Size: 0]\n" - + " [Id: child2 Name: child2 Size: 0]\n"; - - BrowseNode browseNode = mBrowseTree.new BrowseNode(new AvrcpItem.Builder() - .setUuid(TEST_UUID) - .setDisplayableName(TEST_NAME) - .build()); - BrowseNode childNode1 = mBrowseTree.new BrowseNode(new AvrcpItem.Builder() - .setUuid("child1") - .setDisplayableName("child1") - .build()); - BrowseNode childNode2 = mBrowseTree.new BrowseNode(new AvrcpItem.Builder() - .setUuid("child2") - .setDisplayableName("child2") - .build()); - BrowseNode childNode3 = mBrowseTree.new BrowseNode(new AvrcpItem.Builder() - .setUuid("child3") - .setDisplayableName("child3") - .build()); + final String expected = + " [Id: 1111 Name: item Size: 2]\n" + + " [Id: child1 Name: child1 Size: 1]\n" + + " [Id: child3 Name: child3 Size: 0]\n" + + " [Id: child2 Name: child2 Size: 0]\n"; + + BrowseNode browseNode = + mBrowseTree + .new BrowseNode( + new AvrcpItem.Builder() + .setUuid(TEST_UUID) + .setDisplayableName(TEST_NAME) + .build()); + BrowseNode childNode1 = + mBrowseTree + .new BrowseNode( + new AvrcpItem.Builder() + .setUuid("child1") + .setDisplayableName("child1") + .build()); + BrowseNode childNode2 = + mBrowseTree + .new BrowseNode( + new AvrcpItem.Builder() + .setUuid("child2") + .setDisplayableName("child2") + .build()); + BrowseNode childNode3 = + mBrowseTree + .new BrowseNode( + new AvrcpItem.Builder() + .setUuid("child3") + .setDisplayableName("child3") + .build()); childNode1.addChild(childNode3); browseNode.addChild(childNode1); browseNode.addChild(childNode2); @@ -216,12 +234,15 @@ public class BrowseNodeTest { @Test public void toString_returnsId() { - BrowseNode browseNode = mBrowseTree.new BrowseNode(new AvrcpItem.Builder() - .setUuid(TEST_UUID) - .setDisplayableName(TEST_NAME) - .build()); - - assertThat(browseNode.toString()).isEqualTo( - "[Id: " + TEST_UUID + " Name: " + TEST_NAME + " Size: 0]"); + BrowseNode browseNode = + mBrowseTree + .new BrowseNode( + new AvrcpItem.Builder() + .setUuid(TEST_UUID) + .setDisplayableName(TEST_NAME) + .build()); + + assertThat(browseNode.toString()) + .isEqualTo("[Id: " + TEST_UUID + " Name: " + TEST_NAME + " Size: 0]"); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseTreeTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseTreeTest.java index 330be020f04..e801439f0bd 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseTreeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseTreeTest.java @@ -38,7 +38,7 @@ public class BrowseTreeTest { @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); - private final byte[] mTestAddress = new byte[]{01, 01, 01, 01, 01, 01}; + private final byte[] mTestAddress = new byte[] {01, 01, 01, 01, 01, 01}; private BluetoothAdapter mAdapter; private BluetoothDevice mTestDevice = null; @@ -74,13 +74,18 @@ public class BrowseTreeTest { @Test public void getTrackFromNowPlayingList() { BrowseTree browseTree = new BrowseTree(mTestDevice); - BrowseNode trackInNowPlayingList = browseTree.new BrowseNode(new AvrcpItem.Builder() - .setUuid(ILLEGAL_ID).setTitle(ILLEGAL_ID).setBrowsable(true).build()); + BrowseNode trackInNowPlayingList = + browseTree + .new BrowseNode( + new AvrcpItem.Builder() + .setUuid(ILLEGAL_ID) + .setTitle(ILLEGAL_ID) + .setBrowsable(true) + .build()); browseTree.mNowPlayingNode.addChild(trackInNowPlayingList); - assertThat(browseTree.getTrackFromNowPlayingList(0)).isEqualTo( - trackInNowPlayingList); + assertThat(browseTree.getTrackFromNowPlayingList(0)).isEqualTo(trackInNowPlayingList); } @Test @@ -156,8 +161,8 @@ public class BrowseTreeTest { BrowseTree browseTree = new BrowseTree(mTestDevice); assertThat(browseTree.setCurrentBrowsedPlayer(ILLEGAL_ID, 0, 0)).isFalse(); - assertThat( - browseTree.setCurrentBrowsedPlayer(BrowseTree.NOW_PLAYING_PREFIX, 2, 1)).isTrue(); + assertThat(browseTree.setCurrentBrowsedPlayer(BrowseTree.NOW_PLAYING_PREFIX, 2, 1)) + .isTrue(); assertThat(browseTree.getCurrentBrowsedPlayer()).isEqualTo(browseTree.mNowPlayingNode); } @@ -204,8 +209,8 @@ public class BrowseTreeTest { browseTree.onConnected(mTestDevice); - assertThat(BrowseTree.getEldestChild(browseTree.mNowPlayingNode, - browseTree.mRootNode)).isNull(); + assertThat(BrowseTree.getEldestChild(browseTree.mNowPlayingNode, browseTree.mRootNode)) + .isNull(); } @Test @@ -214,34 +219,42 @@ public class BrowseTreeTest { browseTree.onConnected(mTestDevice); - assertThat(BrowseTree.getEldestChild(browseTree.mRootNode, - browseTree.mRootNode.getChild(0))).isEqualTo(browseTree.mRootNode.getChild(0)); + assertThat( + BrowseTree.getEldestChild( + browseTree.mRootNode, browseTree.mRootNode.getChild(0))) + .isEqualTo(browseTree.mRootNode.getChild(0)); } @Test public void getNextStepFolder() { BrowseTree browseTree = new BrowseTree(null); - BrowseNode nodeOutOfMap = browseTree.new BrowseNode(new AvrcpItem.Builder() - .setUuid(ILLEGAL_ID).setTitle(ILLEGAL_ID).setBrowsable(true).build()); + BrowseNode nodeOutOfMap = + browseTree + .new BrowseNode( + new AvrcpItem.Builder() + .setUuid(ILLEGAL_ID) + .setTitle(ILLEGAL_ID) + .setBrowsable(true) + .build()); browseTree.onConnected(mTestDevice); assertThat(browseTree.getNextStepToFolder(null)).isNull(); - assertThat(browseTree.getNextStepToFolder(browseTree.mRootNode)).isEqualTo( - browseTree.mRootNode); - assertThat(browseTree.getNextStepToFolder(browseTree.mRootNode.getChild(0))).isEqualTo( - browseTree.mRootNode.getChild(0)); + assertThat(browseTree.getNextStepToFolder(browseTree.mRootNode)) + .isEqualTo(browseTree.mRootNode); + assertThat(browseTree.getNextStepToFolder(browseTree.mRootNode.getChild(0))) + .isEqualTo(browseTree.mRootNode.getChild(0)); assertThat(browseTree.getNextStepToFolder(nodeOutOfMap)).isNull(); browseTree.setCurrentBrowsedPlayer(BrowseTree.NOW_PLAYING_PREFIX, 2, 1); - assertThat(browseTree.getNextStepToFolder(browseTree.mRootNode.getChild(0))).isEqualTo( - browseTree.mNavigateUpNode); + assertThat(browseTree.getNextStepToFolder(browseTree.mRootNode.getChild(0))) + .isEqualTo(browseTree.mNavigateUpNode); } @Test public void toString_returnsSizeInfo() { BrowseTree browseTree = new BrowseTree(mTestDevice); - assertThat(browseTree.toString()).isEqualTo( - "[BrowseTree size=" + browseTree.mBrowseMap.size() + "]"); + assertThat(browseTree.toString()) + .isEqualTo("[BrowseTree size=" + browseTree.mBrowseMap.size() + "]"); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java index b311ddcf3bc..6f232a7883a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java @@ -37,8 +37,8 @@ public class PlayerApplicationSettingsTest { btAvrcpAttributeList[1] = 1; btAvrcpAttributeList[2] = PlayerApplicationSettings.JNI_REPEAT_STATUS_ALL_TRACK_REPEAT; - PlayerApplicationSettings settings = PlayerApplicationSettings.makeSupportedSettings( - btAvrcpAttributeList); + PlayerApplicationSettings settings = + PlayerApplicationSettings.makeSupportedSettings(btAvrcpAttributeList); assertThat(settings.supportsSetting(PlayerApplicationSettings.REPEAT_STATUS)).isTrue(); } @@ -49,11 +49,11 @@ public class PlayerApplicationSettingsTest { btAvrcpAttributeList[0] = PlayerApplicationSettings.REPEAT_STATUS; btAvrcpAttributeList[1] = PlayerApplicationSettings.JNI_REPEAT_STATUS_GROUP_REPEAT; - PlayerApplicationSettings settings = PlayerApplicationSettings.makeSettings( - btAvrcpAttributeList); + PlayerApplicationSettings settings = + PlayerApplicationSettings.makeSettings(btAvrcpAttributeList); - assertThat(settings.getSetting(PlayerApplicationSettings.REPEAT_STATUS)).isEqualTo( - PlaybackStateCompat.REPEAT_MODE_GROUP); + assertThat(settings.getSetting(PlayerApplicationSettings.REPEAT_STATUS)) + .isEqualTo(PlaybackStateCompat.REPEAT_MODE_GROUP); } @Test @@ -61,84 +61,98 @@ public class PlayerApplicationSettingsTest { byte[] btAvrcpAttributeList = new byte[2]; btAvrcpAttributeList[0] = PlayerApplicationSettings.REPEAT_STATUS; btAvrcpAttributeList[1] = PlayerApplicationSettings.JNI_REPEAT_STATUS_GROUP_REPEAT; - PlayerApplicationSettings settings = PlayerApplicationSettings.makeSettings( - btAvrcpAttributeList); + PlayerApplicationSettings settings = + PlayerApplicationSettings.makeSettings(btAvrcpAttributeList); PlayerApplicationSettings settingsFromSetSupport = new PlayerApplicationSettings(); settingsFromSetSupport.setSupport(settings); - assertThat(settingsFromSetSupport.getSetting( - PlayerApplicationSettings.REPEAT_STATUS)).isEqualTo( - PlaybackStateCompat.REPEAT_MODE_GROUP); + assertThat(settingsFromSetSupport.getSetting(PlayerApplicationSettings.REPEAT_STATUS)) + .isEqualTo(PlaybackStateCompat.REPEAT_MODE_GROUP); } @Test public void mapAttribIdValtoAvrcpPlayerSetting() { - assertThat(PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( - PlayerApplicationSettings.REPEAT_STATUS, - PlayerApplicationSettings.JNI_REPEAT_STATUS_ALL_TRACK_REPEAT)).isEqualTo( - PlaybackStateCompat.REPEAT_MODE_ALL); - assertThat(PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( - PlayerApplicationSettings.REPEAT_STATUS, - PlayerApplicationSettings.JNI_REPEAT_STATUS_GROUP_REPEAT)).isEqualTo( - PlaybackStateCompat.REPEAT_MODE_GROUP); - assertThat(PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( - PlayerApplicationSettings.REPEAT_STATUS, - PlayerApplicationSettings.JNI_REPEAT_STATUS_OFF)).isEqualTo( - PlaybackStateCompat.REPEAT_MODE_NONE); - assertThat(PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( - PlayerApplicationSettings.REPEAT_STATUS, - PlayerApplicationSettings.JNI_REPEAT_STATUS_SINGLE_TRACK_REPEAT)).isEqualTo( - PlaybackStateCompat.REPEAT_MODE_ONE); - assertThat(PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( - PlayerApplicationSettings.SHUFFLE_STATUS, - PlayerApplicationSettings.JNI_SHUFFLE_STATUS_ALL_TRACK_SHUFFLE)).isEqualTo( - PlaybackStateCompat.SHUFFLE_MODE_ALL); - assertThat(PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( - PlayerApplicationSettings.SHUFFLE_STATUS, - PlayerApplicationSettings.JNI_SHUFFLE_STATUS_GROUP_SHUFFLE)).isEqualTo( - PlaybackStateCompat.SHUFFLE_MODE_GROUP); - assertThat(PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( - PlayerApplicationSettings.SHUFFLE_STATUS, - PlayerApplicationSettings.JNI_SHUFFLE_STATUS_OFF)).isEqualTo( - PlaybackStateCompat.SHUFFLE_MODE_NONE); - assertThat(PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( - PlayerApplicationSettings.JNI_STATUS_INVALID, - PlayerApplicationSettings.JNI_STATUS_INVALID)).isEqualTo( - PlayerApplicationSettings.JNI_STATUS_INVALID); + assertThat( + PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( + PlayerApplicationSettings.REPEAT_STATUS, + PlayerApplicationSettings.JNI_REPEAT_STATUS_ALL_TRACK_REPEAT)) + .isEqualTo(PlaybackStateCompat.REPEAT_MODE_ALL); + assertThat( + PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( + PlayerApplicationSettings.REPEAT_STATUS, + PlayerApplicationSettings.JNI_REPEAT_STATUS_GROUP_REPEAT)) + .isEqualTo(PlaybackStateCompat.REPEAT_MODE_GROUP); + assertThat( + PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( + PlayerApplicationSettings.REPEAT_STATUS, + PlayerApplicationSettings.JNI_REPEAT_STATUS_OFF)) + .isEqualTo(PlaybackStateCompat.REPEAT_MODE_NONE); + assertThat( + PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( + PlayerApplicationSettings.REPEAT_STATUS, + PlayerApplicationSettings.JNI_REPEAT_STATUS_SINGLE_TRACK_REPEAT)) + .isEqualTo(PlaybackStateCompat.REPEAT_MODE_ONE); + assertThat( + PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( + PlayerApplicationSettings.SHUFFLE_STATUS, + PlayerApplicationSettings.JNI_SHUFFLE_STATUS_ALL_TRACK_SHUFFLE)) + .isEqualTo(PlaybackStateCompat.SHUFFLE_MODE_ALL); + assertThat( + PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( + PlayerApplicationSettings.SHUFFLE_STATUS, + PlayerApplicationSettings.JNI_SHUFFLE_STATUS_GROUP_SHUFFLE)) + .isEqualTo(PlaybackStateCompat.SHUFFLE_MODE_GROUP); + assertThat( + PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( + PlayerApplicationSettings.SHUFFLE_STATUS, + PlayerApplicationSettings.JNI_SHUFFLE_STATUS_OFF)) + .isEqualTo(PlaybackStateCompat.SHUFFLE_MODE_NONE); + assertThat( + PlayerApplicationSettings.mapAttribIdValtoAvrcpPlayerSetting( + PlayerApplicationSettings.JNI_STATUS_INVALID, + PlayerApplicationSettings.JNI_STATUS_INVALID)) + .isEqualTo(PlayerApplicationSettings.JNI_STATUS_INVALID); } @Test public void mapAvrcpPlayerSettingstoBTattribVal() { - assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( - PlayerApplicationSettings.REPEAT_STATUS, - PlaybackStateCompat.REPEAT_MODE_NONE)).isEqualTo( - PlayerApplicationSettings.JNI_REPEAT_STATUS_OFF); - assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( - PlayerApplicationSettings.REPEAT_STATUS, - PlaybackStateCompat.REPEAT_MODE_ONE)).isEqualTo( - PlayerApplicationSettings.JNI_REPEAT_STATUS_SINGLE_TRACK_REPEAT); - assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( - PlayerApplicationSettings.REPEAT_STATUS, - PlaybackStateCompat.REPEAT_MODE_ALL)).isEqualTo( - PlayerApplicationSettings.JNI_REPEAT_STATUS_ALL_TRACK_REPEAT); - assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( - PlayerApplicationSettings.REPEAT_STATUS, - PlaybackStateCompat.REPEAT_MODE_GROUP)).isEqualTo( - PlayerApplicationSettings.JNI_REPEAT_STATUS_GROUP_REPEAT); - assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( - PlayerApplicationSettings.SHUFFLE_STATUS, - PlaybackStateCompat.SHUFFLE_MODE_NONE)).isEqualTo( - PlayerApplicationSettings.JNI_SHUFFLE_STATUS_OFF); - assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( - PlayerApplicationSettings.SHUFFLE_STATUS, - PlaybackStateCompat.SHUFFLE_MODE_ALL)).isEqualTo( - PlayerApplicationSettings.JNI_SHUFFLE_STATUS_ALL_TRACK_SHUFFLE); - assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( - PlayerApplicationSettings.SHUFFLE_STATUS, - PlaybackStateCompat.SHUFFLE_MODE_GROUP)).isEqualTo( - PlayerApplicationSettings.JNI_SHUFFLE_STATUS_GROUP_SHUFFLE); - assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(-1, -1)).isEqualTo( - PlayerApplicationSettings.JNI_STATUS_INVALID); + assertThat( + PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( + PlayerApplicationSettings.REPEAT_STATUS, + PlaybackStateCompat.REPEAT_MODE_NONE)) + .isEqualTo(PlayerApplicationSettings.JNI_REPEAT_STATUS_OFF); + assertThat( + PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( + PlayerApplicationSettings.REPEAT_STATUS, + PlaybackStateCompat.REPEAT_MODE_ONE)) + .isEqualTo(PlayerApplicationSettings.JNI_REPEAT_STATUS_SINGLE_TRACK_REPEAT); + assertThat( + PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( + PlayerApplicationSettings.REPEAT_STATUS, + PlaybackStateCompat.REPEAT_MODE_ALL)) + .isEqualTo(PlayerApplicationSettings.JNI_REPEAT_STATUS_ALL_TRACK_REPEAT); + assertThat( + PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( + PlayerApplicationSettings.REPEAT_STATUS, + PlaybackStateCompat.REPEAT_MODE_GROUP)) + .isEqualTo(PlayerApplicationSettings.JNI_REPEAT_STATUS_GROUP_REPEAT); + assertThat( + PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( + PlayerApplicationSettings.SHUFFLE_STATUS, + PlaybackStateCompat.SHUFFLE_MODE_NONE)) + .isEqualTo(PlayerApplicationSettings.JNI_SHUFFLE_STATUS_OFF); + assertThat( + PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( + PlayerApplicationSettings.SHUFFLE_STATUS, + PlaybackStateCompat.SHUFFLE_MODE_ALL)) + .isEqualTo(PlayerApplicationSettings.JNI_SHUFFLE_STATUS_ALL_TRACK_SHUFFLE); + assertThat( + PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal( + PlayerApplicationSettings.SHUFFLE_STATUS, + PlaybackStateCompat.SHUFFLE_MODE_GROUP)) + .isEqualTo(PlayerApplicationSettings.JNI_SHUFFLE_STATUS_GROUP_SHUFFLE); + assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(-1, -1)) + .isEqualTo(PlayerApplicationSettings.JNI_STATUS_INVALID); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/StackEventTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/StackEventTest.java index 3f3083bb872..82fe7c61624 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/StackEventTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/StackEventTest.java @@ -33,14 +33,14 @@ public class StackEventTest { boolean remoteControlConnected = true; boolean browsingConnected = true; - StackEvent stackEvent = StackEvent.connectionStateChanged(remoteControlConnected, - browsingConnected); + StackEvent stackEvent = + StackEvent.connectionStateChanged(remoteControlConnected, browsingConnected); assertThat(stackEvent.mType).isEqualTo(StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); assertThat(stackEvent.mRemoteControlConnected).isTrue(); assertThat(stackEvent.mBrowsingConnected).isTrue(); - assertThat(stackEvent.toString()).isEqualTo( - "EVENT_TYPE_CONNECTION_STATE_CHANGED " + remoteControlConnected); + assertThat(stackEvent.toString()) + .isEqualTo("EVENT_TYPE_CONNECTION_STATE_CHANGED " + remoteControlConnected); } @Test @@ -62,4 +62,4 @@ public class StackEventTest { assertThat(stackEvent.toString()).isEqualTo("Unknown"); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java index feb63087e3f..7e4ccf87f98 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java @@ -26,9 +26,7 @@ import java.util.Calendar; import java.util.Date; import java.util.TimeZone; -/** - * A test suite for the BipAttachmentFormat class - */ +/** A test suite for the BipAttachmentFormat class */ @RunWith(AndroidJUnit4.class) public class BipAttachmentFormatTest { @@ -46,12 +44,20 @@ public class BipAttachmentFormatTest { return makeDate(month, day, year, hours, min, sec, null); } - private void testParse(String contentType, String charset, String name, String size, - String created, String modified, Date expectedCreated, boolean isCreatedUtc, - Date expectedModified, boolean isModifiedUtc) { + private void testParse( + String contentType, + String charset, + String name, + String size, + String created, + String modified, + Date expectedCreated, + boolean isCreatedUtc, + Date expectedModified, + boolean isModifiedUtc) { int expectedSize = (size != null ? Integer.parseInt(size) : -1); - BipAttachmentFormat attachment = new BipAttachmentFormat(contentType, charset, name, - size, created, modified); + BipAttachmentFormat attachment = + new BipAttachmentFormat(contentType, charset, name, size, created, modified); Assert.assertEquals(contentType, attachment.getContentType()); Assert.assertEquals(charset, attachment.getCharset()); Assert.assertEquals(name, attachment.getName()); @@ -72,10 +78,15 @@ public class BipAttachmentFormatTest { } } - private void testCreate(String contentType, String charset, String name, int size, - Date created, Date modified) { - BipAttachmentFormat attachment = new BipAttachmentFormat(contentType, charset, name, - size, created, modified); + private void testCreate( + String contentType, + String charset, + String name, + int size, + Date created, + Date modified) { + BipAttachmentFormat attachment = + new BipAttachmentFormat(contentType, charset, name, size, created, modified); Assert.assertEquals(contentType, attachment.getContentType()); Assert.assertEquals(charset, attachment.getCharset()); Assert.assertEquals(name, attachment.getName()); @@ -104,52 +115,141 @@ public class BipAttachmentFormatTest { Date dateUtc = makeDate(1, 1, 1990, 12, 34, 56, utc); // Well defined fields - testParse("text/plain", "ISO-8859-1", "thisisatextfile.txt", "2048", "19900101T123456", - "19900101T123456", date, false, date, false); + testParse( + "text/plain", + "ISO-8859-1", + "thisisatextfile.txt", + "2048", + "19900101T123456", + "19900101T123456", + date, + false, + date, + false); // Well defined fields with UTC date - testParse("text/plain", "ISO-8859-1", "thisisatextfile.txt", "2048", "19900101T123456Z", - "19900101T123456Z", dateUtc, true, dateUtc, true); + testParse( + "text/plain", + "ISO-8859-1", + "thisisatextfile.txt", + "2048", + "19900101T123456Z", + "19900101T123456Z", + dateUtc, + true, + dateUtc, + true); // Change up the content type and file name - testParse("audio/basic", "ISO-8859-1", "thisisawavfile.wav", "1024", "19900101T123456", - "19900101T123456", date, false, date, false); + testParse( + "audio/basic", + "ISO-8859-1", + "thisisawavfile.wav", + "1024", + "19900101T123456", + "19900101T123456", + date, + false, + date, + false); // Use a null modified date - testParse("text/plain", "ISO-8859-1", "thisisatextfile.txt", "2048", "19900101T123456", - null, date, false, null, false); + testParse( + "text/plain", + "ISO-8859-1", + "thisisatextfile.txt", + "2048", + "19900101T123456", + null, + date, + false, + null, + false); // Use a null created date - testParse("text/plain", "ISO-8859-1", "thisisatextfile.txt", "2048", null, - "19900101T123456", null, false, date, false); + testParse( + "text/plain", + "ISO-8859-1", + "thisisatextfile.txt", + "2048", + null, + "19900101T123456", + null, + false, + date, + false); // Use all null dates - testParse("text/plain", "ISO-8859-1", "thisisatextfile.txt", "123", null, null, null, false, - null, false); + testParse( + "text/plain", + "ISO-8859-1", + "thisisatextfile.txt", + "123", + null, + null, + null, + false, + null, + false); // Use a null size - testParse("text/plain", "ISO-8859-1", "thisisatextfile.txt", null, null, null, null, false, - null, false); + testParse( + "text/plain", + "ISO-8859-1", + "thisisatextfile.txt", + null, + null, + null, + null, + false, + null, + false); // Use a null charset - testParse("text/plain", null, "thisisatextfile.txt", "2048", null, null, null, false, null, + testParse( + "text/plain", + null, + "thisisatextfile.txt", + "2048", + null, + null, + null, + false, + null, false); // Use only required fields - testParse("text/plain", null, "thisisatextfile.txt", null, null, null, null, false, null, + testParse( + "text/plain", + null, + "thisisatextfile.txt", + null, + null, + null, + null, + false, + null, false); } @Test(expected = ParseException.class) public void testParseNullContentType() { - testParse(null, "ISO-8859-1", "thisisatextfile.txt", null, null, null, null, false, null, + testParse( + null, + "ISO-8859-1", + "thisisatextfile.txt", + null, + null, + null, + null, + false, + null, false); } @Test(expected = ParseException.class) public void testParseNullName() { - testParse("text/plain", "ISO-8859-1", null, null, null, null, null, false, null, - false); + testParse("text/plain", "ISO-8859-1", null, null, null, null, null, false, null, false); } @Test @@ -189,54 +289,75 @@ public class BipAttachmentFormatTest { Date dateUtc = makeDate(1, 1, 1990, 12, 34, 56, utc); BipAttachmentFormat attachment = null; - String expected = ""; + String expected = + ""; - String expectedUtc = ""; + String expectedUtc = + ""; - String expectedNoDates = ""; + String expectedNoDates = + ""; - String expectedNoSizeNoDates = ""; + String expectedNoSizeNoDates = + ""; - String expectedNoCharsetNoDates = ""; + String expectedNoCharsetNoDates = + ""; - String expectedRequiredOnly = ""; + String expectedRequiredOnly = + ""; // Create by parsing, all fields - attachment = new BipAttachmentFormat("text/plain", "ISO-8859-1", "thisisatextfile.txt", - "2048", "19900101T123456", "19900101T123456"); + attachment = + new BipAttachmentFormat( + "text/plain", + "ISO-8859-1", + "thisisatextfile.txt", + "2048", + "19900101T123456", + "19900101T123456"); Assert.assertEquals(expected, attachment.toString()); // Create by parsing, all fields with utc dates - attachment = new BipAttachmentFormat("text/plain", "ISO-8859-1", "thisisatextfile.txt", - "2048", "19900101T123456Z", "19900101T123456Z"); + attachment = + new BipAttachmentFormat( + "text/plain", + "ISO-8859-1", + "thisisatextfile.txt", + "2048", + "19900101T123456Z", + "19900101T123456Z"); Assert.assertEquals(expectedUtc, attachment.toString()); // Create by parsing, no timestamps - attachment = new BipAttachmentFormat("text/plain", "ISO-8859-1", "thisisatextfile.txt", - "2048", null, null); + attachment = + new BipAttachmentFormat( + "text/plain", "ISO-8859-1", "thisisatextfile.txt", "2048", null, null); Assert.assertEquals(expectedNoDates, attachment.toString()); // Create by parsing, no size, no dates - attachment = new BipAttachmentFormat("text/plain", "ISO-8859-1", "thisisatextfile.txt", - null, null, null); + attachment = + new BipAttachmentFormat( + "text/plain", "ISO-8859-1", "thisisatextfile.txt", null, null, null); Assert.assertEquals(expectedNoSizeNoDates, attachment.toString()); // Create by parsing, no charset, no dates - attachment = new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", "2048", - null, null); + attachment = + new BipAttachmentFormat( + "text/plain", null, "thisisatextfile.txt", "2048", null, null); Assert.assertEquals(expectedNoCharsetNoDates, attachment.toString()); // Create by parsing, content type only - attachment = new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", null, null, - null); + attachment = + new BipAttachmentFormat( + "text/plain", null, "thisisatextfile.txt", null, null, null); Assert.assertEquals(expectedRequiredOnly, attachment.toString()); } @@ -247,61 +368,69 @@ public class BipAttachmentFormatTest { Date date = makeDate(1, 1, 1990, 12, 34, 56, utc); BipAttachmentFormat attachment = null; - String expected = ""; + String expected = + ""; - String expectedNoDates = ""; + String expectedNoDates = + ""; - String expectedNoSizeNoDates = ""; + String expectedNoSizeNoDates = + ""; - String expectedNoCharsetNoDates = ""; + String expectedNoCharsetNoDates = + ""; - String expectedRequiredOnly = ""; + String expectedRequiredOnly = + ""; // Create with objects, all fields. Now we Use UTC since all Date objects eventually become // UTC anyway and this will be timezone agnostic - attachment = new BipAttachmentFormat("text/plain", "ISO-8859-1", "thisisatextfile.txt", - 2048, date, date); + attachment = + new BipAttachmentFormat( + "text/plain", "ISO-8859-1", "thisisatextfile.txt", 2048, date, date); Assert.assertEquals(expected, attachment.toString()); // Create with objects, no dates - attachment = new BipAttachmentFormat("text/plain", "ISO-8859-1", "thisisatextfile.txt", - 2048, null, null); + attachment = + new BipAttachmentFormat( + "text/plain", "ISO-8859-1", "thisisatextfile.txt", 2048, null, null); Assert.assertEquals(expectedNoDates, attachment.toString()); // Create with objects, no size and no dates - attachment = new BipAttachmentFormat("text/plain", "ISO-8859-1", "thisisatextfile.txt", - -1, null, null); + attachment = + new BipAttachmentFormat( + "text/plain", "ISO-8859-1", "thisisatextfile.txt", -1, null, null); Assert.assertEquals(expectedNoSizeNoDates, attachment.toString()); // Create with objects, no charset, no dates - attachment = new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", 2048, null, - null); + attachment = + new BipAttachmentFormat( + "text/plain", null, "thisisatextfile.txt", 2048, null, null); Assert.assertEquals(expectedNoCharsetNoDates, attachment.toString()); // Create with objects, content type only - attachment = new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, - null); + attachment = + new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); Assert.assertEquals(expectedRequiredOnly, attachment.toString()); } @Test public void testEquals_withSameInstance() { - BipAttachmentFormat attachment = new BipAttachmentFormat("text/plain", null, - "thisisatextfile.txt", -1, null, null); + BipAttachmentFormat attachment = + new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); Assert.assertTrue(attachment.equals(attachment)); } @Test public void testEquals_withDifferentClass() { - BipAttachmentFormat attachment = new BipAttachmentFormat("text/plain", null, - "thisisatextfile.txt", -1, null, null); + BipAttachmentFormat attachment = + new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); String notAttachment = "notAttachment"; Assert.assertFalse(attachment.equals(notAttachment)); @@ -309,10 +438,10 @@ public class BipAttachmentFormatTest { @Test public void testEquals_withSameInfo() { - BipAttachmentFormat attachment = new BipAttachmentFormat("text/plain", null, - "thisisatextfile.txt", -1, null, null); - BipAttachmentFormat attachmentEqual = new BipAttachmentFormat("text/plain", null, - "thisisatextfile.txt", -1, null, null); + BipAttachmentFormat attachment = + new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); + BipAttachmentFormat attachmentEqual = + new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); Assert.assertTrue(attachment.equals(attachmentEqual)); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java index 958e1c439a0..91c6b594983 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java @@ -27,9 +27,7 @@ import java.util.Date; import java.util.Locale; import java.util.TimeZone; -/** - * A test suite for the BipDateTime class - */ +/** A test suite for the BipDateTime class */ @RunWith(AndroidJUnit4.class) public class BipDatetimeTest { @@ -47,14 +45,18 @@ public class BipDatetimeTest { return makeDate(month, day, year, hours, min, sec, null); } - private String makeTzAdjustedString(int month, int day, int year, int hours, int min, - int sec) { + private String makeTzAdjustedString(int month, int day, int year, int hours, int min, int sec) { Calendar cal = Calendar.getInstance(); cal.setTime(makeDate(month, day, year, hours, min, sec)); cal.setTimeZone(TimeZone.getDefault()); - return String.format(Locale.US, "%04d%02d%02dT%02d%02d%02d", cal.get(Calendar.YEAR), - cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DATE), - cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), + return String.format( + Locale.US, + "%04d%02d%02dT%02d%02d%02d", + cal.get(Calendar.YEAR), + cal.get(Calendar.MONTH) + 1, + cal.get(Calendar.DATE), + cal.get(Calendar.HOUR_OF_DAY), + cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); } @@ -74,19 +76,40 @@ public class BipDatetimeTest { @Test public void testCreateFromValidString() { - testParse("20000101T000000", makeDate(1, 1, 2000, 0, 0, 0), false, + testParse( + "20000101T000000", + makeDate(1, 1, 2000, 0, 0, 0), + false, makeTzAdjustedString(1, 1, 2000, 0, 0, 0)); - testParse("20000101T060115", makeDate(1, 1, 2000, 6, 1, 15), false, + testParse( + "20000101T060115", + makeDate(1, 1, 2000, 6, 1, 15), + false, makeTzAdjustedString(1, 1, 2000, 6, 1, 15)); - testParse("20000101T060000", makeDate(1, 1, 2000, 6, 0, 0), false, + testParse( + "20000101T060000", + makeDate(1, 1, 2000, 6, 0, 0), + false, makeTzAdjustedString(1, 1, 2000, 6, 0, 0)); - testParse("20000101T071500", makeDate(1, 1, 2000, 7, 15, 0), false, + testParse( + "20000101T071500", + makeDate(1, 1, 2000, 7, 15, 0), + false, makeTzAdjustedString(1, 1, 2000, 7, 15, 0)); - testParse("20000101T151700", makeDate(1, 1, 2000, 15, 17, 0), false, + testParse( + "20000101T151700", + makeDate(1, 1, 2000, 15, 17, 0), + false, makeTzAdjustedString(1, 1, 2000, 15, 17, 0)); - testParse("20000101T235959", makeDate(1, 1, 2000, 23, 59, 59), false, + testParse( + "20000101T235959", + makeDate(1, 1, 2000, 23, 59, 59), + false, makeTzAdjustedString(1, 1, 2000, 23, 59, 59)); - testParse("20501127T235959", makeDate(11, 27, 2050, 23, 59, 59), false, + testParse( + "20501127T235959", + makeDate(11, 27, 2050, 23, 59, 59), + false, makeTzAdjustedString(11, 27, 2050, 23, 59, 59)); } @@ -94,19 +117,23 @@ public class BipDatetimeTest { public void testParseFromValidStringWithUtc() { TimeZone utc = TimeZone.getTimeZone("UTC"); utc.setRawOffset(0); - testParse("20000101T000000Z", makeDate(1, 1, 2000, 0, 0, 0, utc), true, - "20000101T000000Z"); - testParse("20000101T060115Z", makeDate(1, 1, 2000, 6, 1, 15, utc), true, - "20000101T060115Z"); - testParse("20000101T060000Z", makeDate(1, 1, 2000, 6, 0, 0, utc), true, - "20000101T060000Z"); - testParse("20000101T071500Z", makeDate(1, 1, 2000, 7, 15, 0, utc), true, - "20000101T071500Z"); - testParse("20000101T151700Z", makeDate(1, 1, 2000, 15, 17, 0, utc), true, - "20000101T151700Z"); - testParse("20000101T235959Z", makeDate(1, 1, 2000, 23, 59, 59, utc), true, + testParse("20000101T000000Z", makeDate(1, 1, 2000, 0, 0, 0, utc), true, "20000101T000000Z"); + testParse( + "20000101T060115Z", makeDate(1, 1, 2000, 6, 1, 15, utc), true, "20000101T060115Z"); + testParse("20000101T060000Z", makeDate(1, 1, 2000, 6, 0, 0, utc), true, "20000101T060000Z"); + testParse( + "20000101T071500Z", makeDate(1, 1, 2000, 7, 15, 0, utc), true, "20000101T071500Z"); + testParse( + "20000101T151700Z", makeDate(1, 1, 2000, 15, 17, 0, utc), true, "20000101T151700Z"); + testParse( + "20000101T235959Z", + makeDate(1, 1, 2000, 23, 59, 59, utc), + true, "20000101T235959Z"); - testParse("20501127T235959Z", makeDate(11, 27, 2050, 23, 59, 59, utc), true, + testParse( + "20501127T235959Z", + makeDate(11, 27, 2050, 23, 59, 59, utc), + true, "20501127T235959Z"); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java index 5ae69fbc1a9..dcecc314d2d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java @@ -22,13 +22,15 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -/** - * A test suite for the BipEncoding class - */ +/** A test suite for the BipEncoding class */ @RunWith(AndroidJUnit4.class) public class BipEncodingTest { - private void testParse(String input, int encodingType, String encodingStr, String propId, + private void testParse( + String input, + int encodingType, + String encodingStr, + String propId, boolean isAndroidSupported) { BipEncoding encoding = new BipEncoding(input); Assert.assertEquals(encodingType, encoding.getType()); @@ -37,7 +39,11 @@ public class BipEncodingTest { Assert.assertEquals(isAndroidSupported, encoding.isAndroidSupported()); } - private void testParseMany(String[] inputs, int encodingType, String encodingStr, String propId, + private void testParseMany( + String[] inputs, + int encodingType, + String encodingStr, + String propId, boolean isAndroidSupported) { for (String input : inputs) { testParse(input, encodingType, encodingStr, propId, isAndroidSupported); @@ -46,54 +52,61 @@ public class BipEncodingTest { @Test public void testParseJpeg() { - String[] inputs = new String[]{"JPEG", "jpeg", "Jpeg", "JpEg"}; + String[] inputs = new String[] {"JPEG", "jpeg", "Jpeg", "JpEg"}; testParseMany(inputs, BipEncoding.JPEG, "JPEG", null, true); } @Test public void testParseGif() { - String[] inputs = new String[]{"GIF", "gif", "Gif", "gIf"}; + String[] inputs = new String[] {"GIF", "gif", "Gif", "gIf"}; testParseMany(inputs, BipEncoding.GIF, "GIF", null, true); } @Test public void testParseWbmp() { - String[] inputs = new String[]{"WBMP", "wbmp", "Wbmp", "WbMp"}; + String[] inputs = new String[] {"WBMP", "wbmp", "Wbmp", "WbMp"}; testParseMany(inputs, BipEncoding.WBMP, "WBMP", null, false); } @Test public void testParsePng() { - String[] inputs = new String[]{"PNG", "png", "Png", "PnG"}; + String[] inputs = new String[] {"PNG", "png", "Png", "PnG"}; testParseMany(inputs, BipEncoding.PNG, "PNG", null, true); } @Test public void testParseJpeg2000() { - String[] inputs = new String[]{"JPEG2000", "jpeg2000", "Jpeg2000", "JpEg2000"}; + String[] inputs = new String[] {"JPEG2000", "jpeg2000", "Jpeg2000", "JpEg2000"}; testParseMany(inputs, BipEncoding.JPEG2000, "JPEG2000", null, false); } @Test public void testParseBmp() { - String[] inputs = new String[]{"BMP", "bmp", "Bmp", "BmP"}; + String[] inputs = new String[] {"BMP", "bmp", "Bmp", "BmP"}; testParseMany(inputs, BipEncoding.BMP, "BMP", null, true); } @Test public void testParseUsrProprietary() { - String[] inputs = new String[]{"USR-test", "usr-test", "Usr-Test", "UsR-TeSt"}; + String[] inputs = new String[] {"USR-test", "usr-test", "Usr-Test", "UsR-TeSt"}; testParseMany(inputs, BipEncoding.USR_XXX, "USR-TEST", "TEST", false); // Example used in the spec so not a bad choice here - inputs = new String[]{"USR-NOKIA-FORMAT1", "usr-nokia-format1"}; + inputs = new String[] {"USR-NOKIA-FORMAT1", "usr-nokia-format1"}; testParseMany(inputs, BipEncoding.USR_XXX, "USR-NOKIA-FORMAT1", "NOKIA-FORMAT1", false); } @Test public void testCreateBasicEncoding() { - int[] inputs = new int[]{BipEncoding.JPEG, BipEncoding.PNG, BipEncoding.BMP, - BipEncoding.GIF, BipEncoding.JPEG2000, BipEncoding.WBMP}; + int[] inputs = + new int[] { + BipEncoding.JPEG, + BipEncoding.PNG, + BipEncoding.BMP, + BipEncoding.GIF, + BipEncoding.JPEG2000, + BipEncoding.WBMP + }; for (int encodingType : inputs) { BipEncoding encoding = new BipEncoding(encodingType, null); Assert.assertEquals(encodingType, encoding.getType()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java index 2a12b1a449a..658dca4eefb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java @@ -22,9 +22,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -/** - * A test suite for the BipImageDescriptor class - */ +/** A test suite for the BipImageDescriptor class */ @RunWith(AndroidJUnit4.class) public class BipImageDescriptorTest { @@ -33,9 +31,11 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_encodingConstants() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setEncoding(BipEncoding.JPEG); @@ -48,9 +48,11 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_encodingObject() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipEncoding encoding = new BipEncoding(BipEncoding.JPEG, null); BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); @@ -64,9 +66,12 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_proprietaryEncoding() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setPropietaryEncoding("NOKIA-1"); @@ -79,10 +84,12 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_transformationConstantStretch() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setPropietaryEncoding("NOKIA-1"); @@ -95,10 +102,12 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_transformationConstantCrop() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setPropietaryEncoding("NOKIA-1"); @@ -111,10 +120,12 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_transformationConstantFill() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setPropietaryEncoding("NOKIA-1"); @@ -127,10 +138,12 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_transformationConstantCropThenFill() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setPropietaryEncoding("NOKIA-1"); @@ -144,9 +157,11 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_noSize() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setEncoding(BipEncoding.JPEG); @@ -158,9 +173,11 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_useMaxSize() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setEncoding(BipEncoding.JPEG); @@ -173,10 +190,12 @@ public class BipImageDescriptorTest { @Test public void testBuildImageDescriptor_allButSize() { - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); builder.setEncoding(BipEncoding.JPEG); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java index d5d6bdf2ac4..e02d9f9267f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java @@ -22,9 +22,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -/** - * A test suite for the BipImageFormat class - */ +/** A test suite for the BipImageFormat class */ @RunWith(AndroidJUnit4.class) public class BipImageFormatTest { @Test @@ -81,8 +79,9 @@ public class BipImageFormatTest { @Test public void testParseVariant_withTransformation() { - String expected = ""; + String expected = + ""; BipTransformation trans = new BipTransformation(); trans.addTransformation(BipTransformation.STRETCH); trans.addTransformation(BipTransformation.FILL); @@ -105,8 +104,9 @@ public class BipImageFormatTest { @Test public void testParseVariant_allFields() { - String expected = ""; + String expected = + ""; BipTransformation trans = new BipTransformation(); trans.addTransformation(BipTransformation.STRETCH); trans.addTransformation(BipTransformation.FILL); @@ -145,8 +145,11 @@ public class BipImageFormatTest { @Test public void testCreateNative_requiredOnly() { String expected = ""; - BipImageFormat format = BipImageFormat.createNative( - new BipEncoding(BipEncoding.JPEG, null), BipPixel.createFixed(1280, 1024), -1); + BipImageFormat format = + BipImageFormat.createNative( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(1280, 1024), + -1); Assert.assertEquals(BipImageFormat.FORMAT_NATIVE, format.getType()); Assert.assertEquals(new BipEncoding(BipEncoding.JPEG, null), format.getEncoding()); Assert.assertEquals(BipPixel.createFixed(1280, 1024), format.getPixel()); @@ -159,8 +162,11 @@ public class BipImageFormatTest { @Test public void testCreateNative_withSize() { String expected = ""; - BipImageFormat format = BipImageFormat.createNative( - new BipEncoding(BipEncoding.JPEG, null), BipPixel.createFixed(1280, 1024), 1048576); + BipImageFormat format = + BipImageFormat.createNative( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(1280, 1024), + 1048576); Assert.assertEquals(BipImageFormat.FORMAT_NATIVE, format.getType()); Assert.assertEquals(new BipEncoding(BipEncoding.JPEG, null), format.getEncoding()); Assert.assertEquals(BipPixel.createFixed(1280, 1024), format.getPixel()); @@ -173,8 +179,12 @@ public class BipImageFormatTest { @Test public void testCreateVariant_requiredOnly() { String expected = ""; - BipImageFormat format = BipImageFormat.createVariant( - new BipEncoding(BipEncoding.JPEG, null), BipPixel.createFixed(32, 32), -1, null); + BipImageFormat format = + BipImageFormat.createVariant( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(32, 32), + -1, + null); Assert.assertEquals(BipImageFormat.FORMAT_VARIANT, format.getType()); Assert.assertEquals(new BipEncoding(BipEncoding.JPEG, null), format.getEncoding()); Assert.assertEquals(BipPixel.createFixed(32, 32), format.getPixel()); @@ -186,12 +196,22 @@ public class BipImageFormatTest { @Test public void testCreateVariant_withTransformations() { - BipTransformation trans = new BipTransformation(new int[]{BipTransformation.STRETCH, - BipTransformation.CROP, BipTransformation.FILL}); - String expected = ""; - BipImageFormat format = BipImageFormat.createVariant( - new BipEncoding(BipEncoding.JPEG, null), BipPixel.createFixed(32, 32), -1, trans); + BipTransformation trans = + new BipTransformation( + new int[] { + BipTransformation.STRETCH, + BipTransformation.CROP, + BipTransformation.FILL + }); + String expected = + ""; + BipImageFormat format = + BipImageFormat.createVariant( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(32, 32), + -1, + trans); Assert.assertEquals(BipImageFormat.FORMAT_VARIANT, format.getType()); Assert.assertEquals(new BipEncoding(BipEncoding.JPEG, null), format.getEncoding()); Assert.assertEquals(BipPixel.createFixed(32, 32), format.getPixel()); @@ -204,8 +224,12 @@ public class BipImageFormatTest { @Test public void testCreateVariant_withMaxsize() { String expected = ""; - BipImageFormat format = BipImageFormat.createVariant( - new BipEncoding(BipEncoding.JPEG, null), BipPixel.createFixed(32, 32), 123, null); + BipImageFormat format = + BipImageFormat.createVariant( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(32, 32), + 123, + null); Assert.assertEquals(BipImageFormat.FORMAT_VARIANT, format.getType()); Assert.assertEquals(new BipEncoding(BipEncoding.JPEG, null), format.getEncoding()); Assert.assertEquals(BipPixel.createFixed(32, 32), format.getPixel()); @@ -217,12 +241,22 @@ public class BipImageFormatTest { @Test public void testCreateVariant_allFields() { - BipTransformation trans = new BipTransformation(new int[]{BipTransformation.STRETCH, - BipTransformation.CROP, BipTransformation.FILL}); - String expected = ""; - BipImageFormat format = BipImageFormat.createVariant( - new BipEncoding(BipEncoding.JPEG, null), BipPixel.createFixed(32, 32), 123, trans); + BipTransformation trans = + new BipTransformation( + new int[] { + BipTransformation.STRETCH, + BipTransformation.CROP, + BipTransformation.FILL + }); + String expected = + ""; + BipImageFormat format = + BipImageFormat.createVariant( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(32, 32), + 123, + trans); Assert.assertEquals(BipImageFormat.FORMAT_VARIANT, format.getType()); Assert.assertEquals(new BipEncoding(BipEncoding.JPEG, null), format.getEncoding()); Assert.assertEquals(BipPixel.createFixed(32, 32), format.getPixel()); @@ -264,28 +298,34 @@ public class BipImageFormatTest { @Test(expected = NullPointerException.class) public void testCreateFormat_noEncoding() { - BipImageFormat format = BipImageFormat.createNative(null, BipPixel.createFixed(1280, 1024), - -1); + BipImageFormat format = + BipImageFormat.createNative(null, BipPixel.createFixed(1280, 1024), -1); } @Test(expected = NullPointerException.class) public void testCreateFormat_noPixel() { - BipImageFormat format = BipImageFormat.createNative(new BipEncoding(BipEncoding.JPEG, null), - null, -1); + BipImageFormat format = + BipImageFormat.createNative(new BipEncoding(BipEncoding.JPEG, null), null, -1); } @Test public void testEquals_withSameInstance() { - BipImageFormat format = BipImageFormat.createNative( - new BipEncoding(BipEncoding.JPEG, null), BipPixel.createFixed(1280, 1024), -1); + BipImageFormat format = + BipImageFormat.createNative( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(1280, 1024), + -1); Assert.assertTrue(format.equals(format)); } @Test public void testEquals_withDifferentClass() { - BipImageFormat format = BipImageFormat.createNative( - new BipEncoding(BipEncoding.JPEG, null), BipPixel.createFixed(1280, 1024), -1); + BipImageFormat format = + BipImageFormat.createNative( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(1280, 1024), + -1); String notFormat = "notFormat"; Assert.assertFalse(format.equals(notFormat)); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java index dce9ab21b8e..d38b05b30a6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java @@ -26,9 +26,7 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; -/** - * A test suite for the BipImageProperties class - */ +/** A test suite for the BipImageProperties class */ @RunWith(AndroidJUnit4.class) public class BipImagePropertiesTest { private static final String IMAGE_HANDLE = "123456789"; @@ -39,18 +37,29 @@ public class BipImagePropertiesTest { // An image-properties tag with all available attributes private static final String IMAGE_PROPERTIES = - "\r\n"; + "\r\n"; // An image-properties tag without an xml version - OUT OF SPEC / INVALID private static final String IMAGE_PROPERTIES_NO_VERSION = - "\r\n"; + "\r\n"; // An image-properties tag without an image handle - OUT OF SPEC / INVALID private static final String IMAGE_PROPERTIES_NO_HANDLE = - "\r\n"; + "\r\n"; // An image-properties tag without an xml version - IN SPEC / VALID private static final String IMAGE_PROPERTIES_NO_FRIENDLY_NAME = @@ -71,7 +80,7 @@ public class BipImagePropertiesTest { // A variant format representing an range of sizes available. Has transformations and no size private static final String VARIANT_RANGE_FORMAT = " \r\n"; + + "transformation=\"stretch fill crop\" />\r\n"; // A variant format representing a range of sizes within a fixed aspect ratio. private static final String VARIANT_FIXED_RANGE_FORMAT = @@ -94,7 +103,7 @@ public class BipImagePropertiesTest { " \r\n"; private static final String ATTACHMENT_2 = " \r\n"; + + "/>\r\n"; private static final String IMAGE_PROPERTIES_END = ""; @@ -109,18 +118,19 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties with very simple information available. * - * This is the most common type of object we will receive. + *

This is the most common type of object we will receive. * - * Payload: - * - * - * - * "; + *

Payload: + * "; */ @Test public void testParsePropertiesSimple() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES_NO_FRIENDLY_NAME - + NATIVE_THUMBNAIL_FORMAT + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES_NO_FRIENDLY_NAME + + NATIVE_THUMBNAIL_FORMAT + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(IMAGE_HANDLE, properties.getImageHandle()); @@ -133,25 +143,29 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties with very rich information available. * - * This information includes attachments, which are not allowed in AVRCP-BIP but completely + *

This information includes attachments, which are not allowed in AVRCP-BIP but completely * allowed in standard BIP. * - * Payload: - * - * - * - * - * - * - * - * - * "; + *

Payload: + * "; */ @Test public void testParsePropertiesRich() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES + NATIVE_THUMBNAIL_FORMAT - + VARIANT_FIXED_FORMAT + VARIANT_RANGE_FORMAT + VARIANT_FIXED_RANGE_FORMAT - + ATTACHMENT_1 + ATTACHMENT_2 + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES + + NATIVE_THUMBNAIL_FORMAT + + VARIANT_FIXED_FORMAT + + VARIANT_RANGE_FORMAT + + VARIANT_FIXED_RANGE_FORMAT + + ATTACHMENT_1 + + ATTACHMENT_2 + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(IMAGE_HANDLE, properties.getImageHandle()); @@ -164,19 +178,20 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties without an image handle. * - * This is out of spec, but should not crash. Instead, the individual attributes should be + *

This is out of spec, but should not crash. Instead, the individual attributes should be * available and serializing should return null. * - * Payload: - * - * - * - * "; + *

Payload: + * "; */ @Test public void testParseNoHandle() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES_NO_HANDLE + NATIVE_THUMBNAIL_FORMAT - + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES_NO_HANDLE + + NATIVE_THUMBNAIL_FORMAT + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(null, properties.getImageHandle()); @@ -190,19 +205,20 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties without a version. * - * This is out of spec, but should not crash. Instead, the individual attributes should be + *

This is out of spec, but should not crash. Instead, the individual attributes should be * available and serializing should return null. * - * Payload: - * - * - * - * "; + *

Payload: "; */ @Test public void testParseNoVersion() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES_NO_VERSION + NATIVE_THUMBNAIL_FORMAT - + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES_NO_VERSION + + NATIVE_THUMBNAIL_FORMAT + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(IMAGE_HANDLE, properties.getImageHandle()); @@ -216,18 +232,19 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties without a friendly name. * - * This is in spec, as friendly name isn't required. + *

This is in spec, as friendly name isn't required. * - * Payload: - * - * - * - * "; + *

Payload: "; */ @Test public void testParseNoFriendlyName() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES_NO_FRIENDLY_NAME - + NATIVE_THUMBNAIL_FORMAT + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES_NO_FRIENDLY_NAME + + NATIVE_THUMBNAIL_FORMAT + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(IMAGE_HANDLE, properties.getImageHandle()); @@ -240,16 +257,17 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties with a fixed variant thumbnail format * - * Payload: - * - * - * - * "; + *

Payload: "; */ @Test public void testParseFixedVariantThumbnailFormat() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES + VARIANT_FIXED_THUMBNAIL_FORMAT - + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES + + VARIANT_FIXED_THUMBNAIL_FORMAT + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(IMAGE_HANDLE, properties.getImageHandle()); @@ -262,16 +280,17 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties with a range variant thumbnail format * - * Payload: - * - * - * - * "; + *

Payload: "; */ @Test public void testParseRangeVariantThumbnailFormat() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES + VARIANT_RANGE_THUMBNAIL_FORMAT - + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES + + VARIANT_RANGE_THUMBNAIL_FORMAT + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(IMAGE_HANDLE, properties.getImageHandle()); @@ -284,16 +303,17 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties with a fixed aspect ratio range variant thumbnail format * - * Payload: - * - * - * - * "; + *

Payload: "; */ @Test public void testParseFixedRangeVariantThumbnailFormat() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES + VARIANT_FIXED_RANGE_THUMBNAIL_FORMAT - + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES + + VARIANT_FIXED_RANGE_THUMBNAIL_FORMAT + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(IMAGE_HANDLE, properties.getImageHandle()); @@ -306,19 +326,22 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties without any thumbnail formats * - * Payload: - * - * - * - * - * - * - * "; + *

Payload: "; */ @Test public void testParseNoThumbnailFormats() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES + NATIVE_FORMAT + VARIANT_FIXED_FORMAT - + VARIANT_RANGE_FORMAT + VARIANT_FIXED_RANGE_FORMAT + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES + + NATIVE_FORMAT + + VARIANT_FIXED_FORMAT + + VARIANT_RANGE_FORMAT + + VARIANT_FIXED_RANGE_FORMAT + + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); Assert.assertEquals(IMAGE_HANDLE, properties.getImageHandle()); @@ -332,10 +355,8 @@ public class BipImagePropertiesTest { /** * Test parsing image-properties without any formats * - * Payload: - * - * - * "; + *

Payload: "; */ @Test public void testParseNoFormats() { @@ -349,20 +370,16 @@ public class BipImagePropertiesTest { Assert.assertEquals(null, properties.serialize()); } - /** - * Test parsing an image-properties with no open tag - */ - @Test (expected = ParseException.class) + /** Test parsing an image-properties with no open tag */ + @Test(expected = ParseException.class) public void testParseMalformedNoOpen() { String xmlString = XML_DOC_DECL + NATIVE_FORMAT + IMAGE_PROPERTIES_END; InputStream stream = toUtf8Stream(xmlString); BipImageProperties properties = new BipImageProperties(stream); } - /** - * Test parsing a malformed image-properties that just cuts out - */ - @Test (expected = ParseException.class) + /** Test parsing a malformed image-properties that just cuts out */ + @Test(expected = ParseException.class) public void testParseSimulateStreamEndedUnexpectedly() { String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES + " - * - * - * - * - * - * - * - * "; + *

Expected Payload created: + * + * + * "; */ @Test public void testCreateProperties() { - String xmlString = XML_DOC_DECL + IMAGE_PROPERTIES + NATIVE_THUMBNAIL_FORMAT - + VARIANT_FIXED_FORMAT + VARIANT_RANGE_FORMAT + VARIANT_FIXED_RANGE_FORMAT - + ATTACHMENT_1 + ATTACHMENT_2 + IMAGE_PROPERTIES_END; + String xmlString = + XML_DOC_DECL + + IMAGE_PROPERTIES + + NATIVE_THUMBNAIL_FORMAT + + VARIANT_FIXED_FORMAT + + VARIANT_RANGE_FORMAT + + VARIANT_FIXED_RANGE_FORMAT + + ATTACHMENT_1 + + ATTACHMENT_2 + + IMAGE_PROPERTIES_END; BipTransformation trans = new BipTransformation(); trans.addTransformation(BipTransformation.STRETCH); @@ -397,21 +418,30 @@ public class BipImagePropertiesTest { BipImageProperties.Builder builder = new BipImageProperties.Builder(); builder.setImageHandle(IMAGE_HANDLE); builder.setFriendlyName(FRIENDLY_NAME); - builder.addNativeFormat(BipImageFormat.createNative(new BipEncoding(BipEncoding.JPEG, null), - BipPixel.createFixed(200, 200), -1)); + builder.addNativeFormat( + BipImageFormat.createNative( + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(200, 200), + -1)); builder.addVariantFormat( BipImageFormat.createVariant( - new BipEncoding(BipEncoding.JPEG, null), - BipPixel.createFixed(640, 480), -1, null)); + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createFixed(640, 480), + -1, + null)); builder.addVariantFormat( BipImageFormat.createVariant( - new BipEncoding(BipEncoding.GIF, null), - BipPixel.createResizableModified(80, 60, 640, 175), -1, trans)); + new BipEncoding(BipEncoding.GIF, null), + BipPixel.createResizableModified(80, 60, 640, 175), + -1, + trans)); builder.addVariantFormat( BipImageFormat.createVariant( - new BipEncoding(BipEncoding.JPEG, null), - BipPixel.createResizableFixed(150, 600, 120), -1, null)); + new BipEncoding(BipEncoding.JPEG, null), + BipPixel.createResizableFixed(150, 600, 120), + -1, + null)); builder.addAttachment( new BipAttachmentFormat("text/plain", null, "ABCD1234.txt", 5120, null, null)); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageTest.java index 7456434ae9c..5f028d1ba34 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageTest.java @@ -32,9 +32,7 @@ import org.junit.runner.RunWith; import java.io.InputStream; -/** - * A test suite for the BipImage class - */ +/** A test suite for the BipImage class */ @RunWith(AndroidJUnit4.class) public class BipImageTest { private static String sImageHandle = "123456789"; @@ -42,18 +40,18 @@ public class BipImageTest { @Before public void setUp() { - mTestResources = TestUtils.getTestApplicationResources( - InstrumentationRegistry.getTargetContext()); + mTestResources = + TestUtils.getTestApplicationResources(InstrumentationRegistry.getTargetContext()); } @Test public void testParseImage_200by200() { - InputStream imageInputStream = mTestResources.openRawResource( - com.android.bluetooth.tests.R.raw.image_200_200); + InputStream imageInputStream = + mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_200_200); BipImage image = new BipImage(sImageHandle, imageInputStream); - InputStream expectedInputStream = mTestResources.openRawResource( - com.android.bluetooth.tests.R.raw.image_200_200); + InputStream expectedInputStream = + mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_200_200); Bitmap bitmap = BitmapFactory.decodeStream(expectedInputStream); Assert.assertEquals(sImageHandle, image.getImageHandle()); @@ -62,12 +60,12 @@ public class BipImageTest { @Test public void testParseImage_600by600() { - InputStream imageInputStream = mTestResources.openRawResource( - com.android.bluetooth.tests.R.raw.image_600_600); + InputStream imageInputStream = + mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_600_600); BipImage image = new BipImage(sImageHandle, imageInputStream); - InputStream expectedInputStream = mTestResources.openRawResource( - com.android.bluetooth.tests.R.raw.image_600_600); + InputStream expectedInputStream = + mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_600_600); Bitmap bitmap = BitmapFactory.decodeStream(expectedInputStream); Assert.assertEquals(sImageHandle, image.getImageHandle()); @@ -76,8 +74,8 @@ public class BipImageTest { @Test public void testMakeFromImage_200by200() { - InputStream imageInputStream = mTestResources.openRawResource( - com.android.bluetooth.tests.R.raw.image_200_200); + InputStream imageInputStream = + mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_200_200); Bitmap bitmap = BitmapFactory.decodeStream(imageInputStream); BipImage image = new BipImage(sImageHandle, bitmap); Assert.assertEquals(sImageHandle, image.getImageHandle()); @@ -86,8 +84,8 @@ public class BipImageTest { @Test public void testMakeFromImage_600by600() { - InputStream imageInputStream = mTestResources.openRawResource( - com.android.bluetooth.tests.R.raw.image_600_600); + InputStream imageInputStream = + mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_600_600); Bitmap bitmap = BitmapFactory.decodeStream(imageInputStream); BipImage image = new BipImage(sImageHandle, bitmap); Assert.assertEquals(sImageHandle, image.getImageHandle()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java index 11c0f339942..e40ef9cefc9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java @@ -22,14 +22,18 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -/** - * A test suite for the BipPixel class - */ +/** A test suite for the BipPixel class */ @RunWith(AndroidJUnit4.class) public class BipPixelTest { - private void testParse(String input, int pixelType, int minWidth, int minHeight, int maxWidth, - int maxHeight, String pixelStr) { + private void testParse( + String input, + int pixelType, + int minWidth, + int minHeight, + int maxWidth, + int maxHeight, + String pixelStr) { BipPixel pixel = new BipPixel(input); Assert.assertEquals(pixelType, pixel.getType()); Assert.assertEquals(minWidth, pixel.getMinWidth()); @@ -49,8 +53,8 @@ public class BipPixelTest { Assert.assertEquals(pixelStr, pixel.toString()); } - private void testResizableModified(int minWidth, int minHeight, int maxWidth, int maxHeight, - String pixelStr) { + private void testResizableModified( + int minWidth, int minHeight, int maxWidth, int maxHeight, String pixelStr) { BipPixel pixel = BipPixel.createResizableModified(minWidth, minHeight, maxWidth, maxHeight); Assert.assertEquals(BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, pixel.getType()); Assert.assertEquals(minWidth, pixel.getMinWidth()); @@ -60,8 +64,7 @@ public class BipPixelTest { Assert.assertEquals(pixelStr, pixel.toString()); } - private void testResizableFixed(int minWidth, int maxWidth, int maxHeight, - String pixelStr) { + private void testResizableFixed(int minWidth, int maxWidth, int maxHeight, String pixelStr) { int minHeight = (minWidth * maxHeight) / maxWidth; // spec defined BipPixel pixel = BipPixel.createResizableFixed(minWidth, maxWidth, maxHeight); Assert.assertEquals(BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, pixel.getType()); @@ -82,25 +85,73 @@ public class BipPixelTest { @Test public void testParseResizableModified() { - testParse("0*0-200*200", BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, 0, 0, 200, 200, + testParse( + "0*0-200*200", + BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, + 0, + 0, + 200, + 200, "0*0-200*200"); - testParse("200*200-600*600", BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, 200, 200, 600, 600, + testParse( + "200*200-600*600", + BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, + 200, + 200, + 600, + 600, "200*200-600*600"); - testParse("12*67-34*89", BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, 12, 67, 34, 89, + testParse( + "12*67-34*89", + BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, + 12, + 67, + 34, + 89, "12*67-34*89"); - testParse("123*456-1000*1000", BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, 123, 456, 1000, - 1000, "123*456-1000*1000"); + testParse( + "123*456-1000*1000", + BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO, + 123, + 456, + 1000, + 1000, + "123*456-1000*1000"); } @Test public void testParseResizableFixed() { - testParse("0**-200*200", BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, 0, 0, 200, 200, + testParse( + "0**-200*200", + BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, + 0, + 0, + 200, + 200, "0**-200*200"); - testParse("200**-600*600", BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, 200, 200, 600, 600, + testParse( + "200**-600*600", + BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, + 200, + 200, + 600, + 600, "200**-600*600"); - testParse("123**-1000*1000", BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, 123, 123, 1000, 1000, + testParse( + "123**-1000*1000", + BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, + 123, + 123, + 1000, + 1000, "123**-1000*1000"); - testParse("12**-35*89", BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, 12, (12 * 89) / 35, 35, 89, + testParse( + "12**-35*89", + BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO, + 12, + (12 * 89) / 35, + 35, + 89, "12**-35*89"); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformationTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformationTest.java index 793b2df3803..53d653d3c0b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformationTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformationTest.java @@ -22,9 +22,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -/** - * A test suite for the BipTransformation class - */ +/** A test suite for the BipTransformation class */ @RunWith(AndroidJUnit4.class) public class BipTransformationTest { @@ -257,7 +255,7 @@ public class BipTransformationTest { @Test public void testCreate_cropArray() { - BipTransformation trans = new BipTransformation(new int[]{BipTransformation.CROP}); + BipTransformation trans = new BipTransformation(new int[] {BipTransformation.CROP}); Assert.assertFalse(trans.isSupported(BipTransformation.STRETCH)); Assert.assertFalse(trans.isSupported(BipTransformation.FILL)); Assert.assertTrue(trans.isSupported(BipTransformation.CROP)); @@ -266,8 +264,9 @@ public class BipTransformationTest { @Test public void testCreate_stretchFill() { - BipTransformation trans = new BipTransformation(new int[]{BipTransformation.STRETCH, - BipTransformation.FILL}); + BipTransformation trans = + new BipTransformation( + new int[] {BipTransformation.STRETCH, BipTransformation.FILL}); Assert.assertTrue(trans.isSupported(BipTransformation.STRETCH)); Assert.assertTrue(trans.isSupported(BipTransformation.FILL)); Assert.assertFalse(trans.isSupported(BipTransformation.CROP)); @@ -276,8 +275,13 @@ public class BipTransformationTest { @Test public void testCreate_stretchFillCrop() { - BipTransformation trans = new BipTransformation(new int[]{BipTransformation.STRETCH, - BipTransformation.FILL, BipTransformation.CROP}); + BipTransformation trans = + new BipTransformation( + new int[] { + BipTransformation.STRETCH, + BipTransformation.FILL, + BipTransformation.CROP + }); Assert.assertTrue(trans.isSupported(BipTransformation.STRETCH)); Assert.assertTrue(trans.isSupported(BipTransformation.FILL)); Assert.assertTrue(trans.isSupported(BipTransformation.CROP)); @@ -286,8 +290,13 @@ public class BipTransformationTest { @Test public void testCreate_stretchFillCropOrderChanged() { - BipTransformation trans = new BipTransformation(new int[]{BipTransformation.CROP, - BipTransformation.FILL, BipTransformation.STRETCH}); + BipTransformation trans = + new BipTransformation( + new int[] { + BipTransformation.CROP, + BipTransformation.FILL, + BipTransformation.STRETCH + }); Assert.assertTrue(trans.isSupported(BipTransformation.STRETCH)); Assert.assertTrue(trans.isSupported(BipTransformation.FILL)); Assert.assertTrue(trans.isSupported(BipTransformation.CROP)); @@ -301,7 +310,7 @@ public class BipTransformationTest { @Test(expected = IllegalArgumentException.class) public void testCreate_badTransformation() { - BipTransformation trans = new BipTransformation(new int[]{BipTransformation.CROP, -7}); + BipTransformation trans = new BipTransformation(new int[] {BipTransformation.CROP, -7}); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/RequestGetImagePropertiesTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/RequestGetImagePropertiesTest.java index d795dca157e..fb833c757b8 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/RequestGetImagePropertiesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/RequestGetImagePropertiesTest.java @@ -31,18 +31,18 @@ public class RequestGetImagePropertiesTest { @Test public void constructor() { - RequestGetImageProperties requestGetImageProperties = new RequestGetImageProperties( - TEST_IMAGE_HANDLE); + RequestGetImageProperties requestGetImageProperties = + new RequestGetImageProperties(TEST_IMAGE_HANDLE); assertThat(requestGetImageProperties.getImageHandle()).isEqualTo(TEST_IMAGE_HANDLE); } @Test public void getType() { - RequestGetImageProperties requestGetImageProperties = new RequestGetImageProperties( - TEST_IMAGE_HANDLE); + RequestGetImageProperties requestGetImageProperties = + new RequestGetImageProperties(TEST_IMAGE_HANDLE); - assertThat(requestGetImageProperties.getType()).isEqualTo( - BipRequest.TYPE_GET_IMAGE_PROPERTIES); + assertThat(requestGetImageProperties.getType()) + .isEqualTo(BipRequest.TYPE_GET_IMAGE_PROPERTIES); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/RequestGetImageTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/RequestGetImageTest.java index 8f55832574a..d68854b91e9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/RequestGetImageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/RequestGetImageTest.java @@ -40,9 +40,11 @@ public class RequestGetImageTest { RequestGetImage requestGetImage = new RequestGetImage(TEST_IMAGE_HANDLE, descriptor); - String expected = sXmlDocDecl + "\r\n" - + " \r\n" - + ""; + String expected = + sXmlDocDecl + + "\r\n" + + " \r\n" + + ""; assertThat(requestGetImage.getImageHandle()).isEqualTo(TEST_IMAGE_HANDLE); assertThat(requestGetImage.mImageDescriptor.toString()).isEqualTo(expected); } @@ -60,4 +62,4 @@ public class RequestGetImageTest { assertThat(requestGetImage.getType()).isEqualTo(BipRequest.TYPE_GET_IMAGE); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceBinderTest.java index 697ab000016..1e7aaee9490 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceBinderTest.java @@ -36,8 +36,7 @@ import org.mockito.junit.MockitoRule; public class BatteryServiceBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private BatteryService mService; + @Mock private BatteryService mService; private BatteryService.BluetoothBatteryBinder mBinder; private BluetoothAdapter mAdapter; @@ -80,7 +79,7 @@ public class BatteryServiceBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] { BluetoothProfile.STATE_CONNECTED }; + int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; AttributionSource source = new AttributionSource.Builder(0).build(); mBinder.getDevicesMatchingConnectionStates(states, source); diff --git a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java index 64753a466d6..ddb36153ff8 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java @@ -60,8 +60,7 @@ public class BatteryServiceTest { @Mock private AdapterService mAdapterService; @Mock private DatabaseManager mDatabaseManager; - @Rule - public final MockitoRule mockito = MockitoJUnit.rule(); + @Rule public final MockitoRule mockito = MockitoJUnit.rule(); @Before public void setUp() throws Exception { @@ -78,11 +77,12 @@ public class BatteryServiceTest { startService(); // Override the timeout value to speed up the test - BatteryStateMachine.sConnectTimeoutMs = CONNECTION_TIMEOUT_MS; // 1s + BatteryStateMachine.sConnectTimeoutMs = CONNECTION_TIMEOUT_MS; // 1s // Get a device for testing mDevice = TestUtils.getTestDevice(mAdapter, 0); - doReturn(BluetoothDevice.BOND_BONDED).when(mAdapterService) + doReturn(BluetoothDevice.BOND_BONDED) + .when(mAdapterService) .getBondState(any(BluetoothDevice.class)); } @@ -104,108 +104,121 @@ public class BatteryServiceTest { Assert.assertNull(mService); } - /** - * Test get Battery Service - */ + /** Test get Battery Service */ @Test public void testGetBatteryService() { Assert.assertEquals(mService, BatteryService.getBatteryService()); } - /** - * Test get/set policy for BluetoothDevice - */ + /** Test get/set policy for BluetoothDevice */ @Test public void testGetSetPolicy() { - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - Assert.assertEquals("Initial device policy", + Assert.assertEquals( + "Initial device policy", BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mService.getConnectionPolicy(mDevice)); - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - Assert.assertEquals("Setting device policy to POLICY_FORBIDDEN", + Assert.assertEquals( + "Setting device policy to POLICY_FORBIDDEN", BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, mService.getConnectionPolicy(mDevice)); - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - Assert.assertEquals("Setting device policy to POLICY_ALLOWED", + Assert.assertEquals( + "Setting device policy to POLICY_ALLOWED", BluetoothProfile.CONNECTION_POLICY_ALLOWED, mService.getConnectionPolicy(mDevice)); } - /** - * Test if getProfileConnectionPolicy works after the service is stopped. - */ + /** Test if getProfileConnectionPolicy works after the service is stopped. */ @Test public void testGetPolicyAfterStopped() { mService.stop(); - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - Assert.assertEquals("Initial device policy", + Assert.assertEquals( + "Initial device policy", BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mService.getConnectionPolicy(mDevice)); } - /** - * Test okToConnect method using various test cases - */ + /** Test okToConnect method using various test cases */ @Test public void testCanConnect() { int badPolicyValue = 1024; int badBondState = 42; - testCanConnectCase(mDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_NONE, badPolicyValue, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_BONDING, badPolicyValue, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_ALLOWED, true); - testCanConnectCase(mDevice, - BluetoothDevice.BOND_BONDED, badPolicyValue, false); - testCanConnectCase(mDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testCanConnectCase(mDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testCanConnectCase(mDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testCanConnectCase(mDevice, - badBondState, badPolicyValue, false); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); + testCanConnectCase(mDevice, BluetoothDevice.BOND_NONE, badPolicyValue, false); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); + testCanConnectCase(mDevice, BluetoothDevice.BOND_BONDING, badPolicyValue, false); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + true); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testCanConnectCase( + mDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + true); + testCanConnectCase(mDevice, BluetoothDevice.BOND_BONDED, badPolicyValue, false); + testCanConnectCase( + mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); + testCanConnectCase( + mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); + testCanConnectCase( + mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); + testCanConnectCase(mDevice, badBondState, badPolicyValue, false); } - /** - * Test that an outgoing connection to device - */ + /** Test that an outgoing connection to device */ @Test public void testConnectAndDump() { // Update the device policy so okToConnect() returns true when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager); - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); // Return Battery UUID - doReturn(new ParcelUuid[]{BluetoothUuid.BATTERY}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.BATTERY}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Send a connect request Assert.assertTrue("Connect expected to succeed", mService.connect(mDevice)); @@ -214,15 +227,12 @@ public class BatteryServiceTest { mService.dump(new StringBuilder()); } - /** - * Test that an outgoing connection to device with POLICY_FORBIDDEN is rejected - */ + /** Test that an outgoing connection to device with POLICY_FORBIDDEN is rejected */ @Test public void testForbiddenPolicy_FailsToConnect() { // Set the device policy to POLICY_FORBIDDEN so connect() should fail when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager); - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.BATTERY)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Send a connect request @@ -231,8 +241,8 @@ public class BatteryServiceTest { @Test public void getConnectionState_whenNoDevicesAreConnected_returnsDisconnectedState() { - Assert.assertEquals(mService.getConnectionState(mDevice), - BluetoothProfile.STATE_DISCONNECTED); + Assert.assertEquals( + mService.getConnectionState(mDevice), BluetoothProfile.STATE_DISCONNECTED); } @Test @@ -250,20 +260,21 @@ public class BatteryServiceTest { @Test public void setConnectionPolicy() { - Assert.assertTrue(mService.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)); + Assert.assertTrue( + mService.setConnectionPolicy( + mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)); } /** - * Helper function to test okToConnect() method + * Helper function to test okToConnect() method * - * @param device test device - * @param bondState bond state value, could be invalid - * @param policy value, could be invalid - * @param expected expected result from okToConnect() + * @param device test device + * @param bondState bond state value, could be invalid + * @param policy value, could be invalid + * @param expected expected result from okToConnect() */ - private void testCanConnectCase(BluetoothDevice device, int bondState, int policy, - boolean expected) { + private void testCanConnectCase( + BluetoothDevice device, int bondState, int policy, boolean expected) { doReturn(bondState).when(mAdapterService).getBondState(device); when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager); when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.BATTERY)) diff --git a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryStateMachineTest.java index 6436fbe8788..caf512457fa 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryStateMachineTest.java @@ -62,8 +62,7 @@ import org.mockito.junit.MockitoRule; @LargeTest @RunWith(JUnit4.class) public class BatteryStateMachineTest { - @Rule - public final MockitoRule mockito = MockitoJUnit.rule(); + @Rule public final MockitoRule mockito = MockitoJUnit.rule(); private BluetoothAdapter mAdapter; private Context mTargetContext; @@ -90,8 +89,9 @@ public class BatteryStateMachineTest { // Set up thread and looper mHandlerThread = new HandlerThread("BatteryStateMachineTestHandlerThread"); mHandlerThread.start(); - mBatteryStateMachine = new StubBatteryStateMachine(mTestDevice, - mBatteryService, mHandlerThread.getLooper()); + mBatteryStateMachine = + new StubBatteryStateMachine( + mTestDevice, mBatteryService, mHandlerThread.getLooper()); // Override the timeout value to speed up the test mBatteryStateMachine.sConnectTimeoutMs = CONNECTION_TIMEOUT_MS; mBatteryStateMachine.start(); @@ -105,13 +105,11 @@ public class BatteryStateMachineTest { reset(mBatteryService); } - /** - * Test that default state is disconnected - */ + /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, - mBatteryStateMachine.getConnectionState()); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mBatteryStateMachine.getConnectionState()); } /** @@ -127,9 +125,7 @@ public class BatteryStateMachineTest { mBatteryStateMachine.mShouldAllowGatt = allow; } - /** - * Test that an incoming connection with policy forbidding connection is rejected - */ + /** Test that an incoming connection with policy forbidding connection is rejected */ @Test public void testOkToConnectFails() { allowConnection(false); @@ -142,7 +138,8 @@ public class BatteryStateMachineTest { .handleConnectionStateChanged(any(BatteryStateMachine.class), anyInt(), anyInt()); // Check that we are in Disconnected state - Assert.assertThat(mBatteryStateMachine.getCurrentState(), + Assert.assertThat( + mBatteryStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BatteryStateMachine.Disconnected.class)); } @@ -158,7 +155,8 @@ public class BatteryStateMachineTest { .handleConnectionStateChanged(any(BatteryStateMachine.class), anyInt(), anyInt()); // Check that we are in Disconnected state - Assert.assertThat(mBatteryStateMachine.getCurrentState(), + Assert.assertThat( + mBatteryStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BatteryStateMachine.Disconnected.class)); assertNull(mBatteryStateMachine.mBluetoothGatt); } @@ -172,11 +170,13 @@ public class BatteryStateMachineTest { mBatteryStateMachine.sendMessage(BatteryStateMachine.CONNECT); verify(mBatteryService, timeout(TIMEOUT_MS)) - .handleConnectionStateChanged(any(BatteryStateMachine.class), + .handleConnectionStateChanged( + any(BatteryStateMachine.class), eq(BluetoothProfile.STATE_DISCONNECTED), eq(BluetoothProfile.STATE_CONNECTING)); - Assert.assertThat(mBatteryStateMachine.getCurrentState(), + Assert.assertThat( + mBatteryStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BatteryStateMachine.Connecting.class)); assertNotNull(mBatteryStateMachine.mGattCallback); @@ -184,11 +184,13 @@ public class BatteryStateMachineTest { GATT_SUCCESS, BluetoothProfile.STATE_CONNECTED); verify(mBatteryService, timeout(TIMEOUT_MS)) - .handleConnectionStateChanged(any(BatteryStateMachine.class), + .handleConnectionStateChanged( + any(BatteryStateMachine.class), eq(BluetoothProfile.STATE_CONNECTING), eq(BluetoothProfile.STATE_CONNECTED)); - Assert.assertThat(mBatteryStateMachine.getCurrentState(), + Assert.assertThat( + mBatteryStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BatteryStateMachine.Connected.class)); } @@ -200,14 +202,16 @@ public class BatteryStateMachineTest { mBatteryStateMachine.sendMessage(BatteryStateMachine.CONNECT); verify(mBatteryService, timeout(TIMEOUT_MS)) - .handleConnectionStateChanged(any(BatteryStateMachine.class), + .handleConnectionStateChanged( + any(BatteryStateMachine.class), eq(BluetoothProfile.STATE_DISCONNECTED), eq(BluetoothProfile.STATE_CONNECTING)); mBatteryStateMachine.sendMessage(BatteryStateMachine.DISCONNECT); verify(mBatteryService, timeout(TIMEOUT_MS)) - .handleConnectionStateChanged(any(BatteryStateMachine.class), + .handleConnectionStateChanged( + any(BatteryStateMachine.class), eq(BluetoothProfile.STATE_CONNECTING), eq(BluetoothProfile.STATE_DISCONNECTED)); } @@ -262,8 +266,7 @@ public class BatteryStateMachineTest { reconnect(); int badState = -1; - mBatteryStateMachine.sendMessage( - BatteryStateMachine.CONNECTION_STATE_CHANGED, badState); + mBatteryStateMachine.sendMessage(BatteryStateMachine.CONNECTION_STATE_CHANGED, badState); assertThat(mBatteryStateMachine.getCurrentState()) .isInstanceOf(BatteryStateMachine.Connected.class); @@ -378,4 +381,3 @@ public class BatteryStateMachineTest { } } } - diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BaseDataTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BaseDataTest.java index 8b3909b8d77..445be0e2b5f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BaseDataTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BaseDataTest.java @@ -102,7 +102,7 @@ public class BaseDataTest { BaseData data = BaseData.parseBaseData(serviceData); BaseData.BaseInformation level = data.getLevelOne(); - assertThat(level.presentationDelay).isEqualTo(new byte[] { 0x01, 0x02, 0x03 }); + assertThat(level.presentationDelay).isEqualTo(new byte[] {0x01, 0x02, 0x03}); assertThat(level.numSubGroups).isEqualTo(1); assertThat(data.getLevelTwo().size()).isEqualTo(1); diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java index 51e1820bb2a..1ed76c09cbf 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java @@ -104,9 +104,7 @@ import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.stream.Collectors; -/** - * Tests for {@link BassClientService} - */ +/** Tests for {@link BassClientService} */ @MediumTest @RunWith(AndroidJUnit4.class) public class BassClientServiceTest { @@ -142,7 +140,6 @@ public class BassClientServiceTest { private static final int TEST_SOURCE_ID = 10; private static final int TEST_NUM_SOURCES = 2; - private static final int TEST_MAX_NUM_DEVICES = 3; private final HashMap mStateMachines = new HashMap<>(); @@ -177,18 +174,23 @@ public class BassClientServiceTest { BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { BluetoothLeAudioCodecConfigMetadata codecMetadata = new BluetoothLeAudioCodecConfigMetadata.Builder() - .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_LEFT).build(); + .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_LEFT) + .build(); BluetoothLeAudioContentMetadata contentMetadata = new BluetoothLeAudioContentMetadata.Builder() - .setProgramInfo(TEST_PROGRAM_INFO).setLanguage(TEST_LANGUAGE).build(); - BluetoothLeBroadcastSubgroup.Builder builder = new BluetoothLeBroadcastSubgroup.Builder() - .setCodecId(TEST_CODEC_ID) - .setCodecSpecificConfig(codecMetadata) - .setContentMetadata(contentMetadata); + .setProgramInfo(TEST_PROGRAM_INFO) + .setLanguage(TEST_LANGUAGE) + .build(); + BluetoothLeBroadcastSubgroup.Builder builder = + new BluetoothLeBroadcastSubgroup.Builder() + .setCodecId(TEST_CODEC_ID) + .setCodecSpecificConfig(codecMetadata) + .setContentMetadata(contentMetadata); BluetoothLeAudioCodecConfigMetadata channelCodecMetadata = new BluetoothLeAudioCodecConfigMetadata.Builder() - .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_RIGHT).build(); + .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_RIGHT) + .build(); // builder expect at least one channel BluetoothLeBroadcastChannel channel = @@ -202,10 +204,12 @@ public class BassClientServiceTest { } BluetoothLeBroadcastMetadata createBroadcastMetadata(int broadcastId) { - BluetoothDevice testDevice = mBluetoothAdapter.getRemoteLeDevice(TEST_MAC_ADDRESS, - BluetoothDevice.ADDRESS_TYPE_RANDOM); + BluetoothDevice testDevice = + mBluetoothAdapter.getRemoteLeDevice( + TEST_MAC_ADDRESS, BluetoothDevice.ADDRESS_TYPE_RANDOM); - BluetoothLeBroadcastMetadata.Builder builder = new BluetoothLeBroadcastMetadata.Builder() + BluetoothLeBroadcastMetadata.Builder builder = + new BluetoothLeBroadcastMetadata.Builder() .setEncrypted(false) .setSourceDevice(testDevice, BluetoothDevice.ADDRESS_TYPE_RANDOM) .setSourceAdvertisingSid(TEST_ADVERTISER_SID) @@ -236,21 +240,27 @@ public class BassClientServiceTest { any(), any(), anyInt(), anyInt(), any(), any()); doNothing().when(mMethodProxy).periodicAdvertisingManagerUnregisterSync(any(), any()); - doReturn(new ParcelUuid[]{BluetoothUuid.BASS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.BASS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // This line must be called to make sure relevant objects are initialized properly mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Mock methods in AdapterService - doReturn(FAKE_SERVICE_UUIDS).when(mAdapterService) + doReturn(FAKE_SERVICE_UUIDS) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - doReturn(BluetoothDevice.BOND_BONDED).when(mAdapterService) + doReturn(BluetoothDevice.BOND_BONDED) + .when(mAdapterService) .getBondState(any(BluetoothDevice.class)); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); - doAnswer(invocation -> { - Set keys = mStateMachines.keySet(); - return keys.toArray(new BluetoothDevice[keys.size()]); - }).when(mAdapterService).getBondedDevices(); + doAnswer( + invocation -> { + Set keys = mStateMachines.keySet(); + return keys.toArray(new BluetoothDevice[keys.size()]); + }) + .when(mAdapterService) + .getBondedDevices(); // Mock methods in BassObjectsFactory doAnswer( @@ -271,7 +281,8 @@ public class BassClientServiceTest { }) .when(mObjectsFactory) .makeStateMachine(any(), any(), any(), any()); - doReturn(mBluetoothLeScannerWrapper).when(mObjectsFactory) + doReturn(mBluetoothLeScannerWrapper) + .when(mObjectsFactory) .getBluetoothLeScannerWrapper(any()); mBassClientService = new BassClientService(mTargetContext); @@ -339,8 +350,7 @@ public class BassClientServiceTest { } try { - BluetoothDevice device = intent.getParcelableExtra( - BluetoothDevice.EXTRA_DEVICE); + BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); assertThat(device).isNotNull(); LinkedBlockingQueue queue = mIntentQueue.get(device); assertThat(queue).isNotNull(); @@ -351,9 +361,7 @@ public class BassClientServiceTest { } } - /** - * Test to verify that BassClientService can be successfully started - */ + /** Test to verify that BassClientService can be successfully started */ @Test public void testGetBassClientService() { assertThat(mBassClientService).isEqualTo(BassClientService.getBassClientService()); @@ -363,53 +371,46 @@ public class BassClientServiceTest { .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); } - /** - * Test if getProfileConnectionPolicy works after the service is stopped. - */ + /** Test if getProfileConnectionPolicy works after the service is stopped. */ @Test public void testGetPolicyAfterStopped() { mBassClientService.stop(); - when(mDatabaseManager - .getProfileConnectionPolicy(mCurrentDevice, - BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)) + when(mDatabaseManager.getProfileConnectionPolicy( + mCurrentDevice, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - Assert.assertEquals("Initial device policy", + Assert.assertEquals( + "Initial device policy", BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mBassClientService.getConnectionPolicy(mCurrentDevice)); } /** - * Test connecting to a test device. - * - service.connect() should return false - * - bassClientStateMachine.sendMessage(CONNECT) should be called. + * Test connecting to a test device. - service.connect() should return false - + * bassClientStateMachine.sendMessage(CONNECT) should be called. */ @Test public void testConnect() { - when(mDatabaseManager.getProfileConnectionPolicy(any(BluetoothDevice.class), - eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) + when(mDatabaseManager.getProfileConnectionPolicy( + any(BluetoothDevice.class), + eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); mCurrentDevice = TestUtils.getTestDevice(mBluetoothAdapter, 0); assertThat(mBassClientService.connect(mCurrentDevice)).isTrue(); verify(mObjectsFactory) .makeStateMachine( - eq(mCurrentDevice), - eq(mBassClientService), - eq(mAdapterService), - any()); + eq(mCurrentDevice), eq(mBassClientService), eq(mAdapterService), any()); BassClientStateMachine stateMachine = mStateMachines.get(mCurrentDevice); assertThat(stateMachine).isNotNull(); verify(stateMachine).sendMessage(BassClientStateMachine.CONNECT); } - /** - * Test connecting to a null device. - * - service.connect() should return false. - */ + /** Test connecting to a null device. - service.connect() should return false. */ @Test public void testConnect_nullDevice() { - when(mDatabaseManager.getProfileConnectionPolicy(any(BluetoothDevice.class), - eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) + when(mDatabaseManager.getProfileConnectionPolicy( + any(BluetoothDevice.class), + eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); BluetoothDevice nullDevice = null; @@ -417,13 +418,14 @@ public class BassClientServiceTest { } /** - * Test connecting to a device when the connection policy is forbidden. - * - service.connect() should return false. + * Test connecting to a device when the connection policy is forbidden. - service.connect() + * should return false. */ @Test public void testConnect_whenConnectionPolicyIsForbidden() { - when(mDatabaseManager.getProfileConnectionPolicy(any(BluetoothDevice.class), - eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) + when(mDatabaseManager.getProfileConnectionPolicy( + any(BluetoothDevice.class), + eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); mCurrentDevice = TestUtils.getTestDevice(mBluetoothAdapter, 0); assertThat(mCurrentDevice).isNotNull(); @@ -467,9 +469,10 @@ public class BassClientServiceTest { } private void prepareConnectedDeviceGroup() { - when(mDatabaseManager.getProfileConnectionPolicy(any(BluetoothDevice.class), + when(mDatabaseManager.getProfileConnectionPolicy( + any(BluetoothDevice.class), eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); mCurrentDevice = TestUtils.getTestDevice(mBluetoothAdapter, 0); mCurrentDevice1 = TestUtils.getTestDevice(mBluetoothAdapter, 1); @@ -481,9 +484,11 @@ public class BassClientServiceTest { List groupDevices = new ArrayList<>(); groupDevices.add(mCurrentDevice); groupDevices.add(mCurrentDevice1); - doReturn(groupDevices).when(mCsipService) + doReturn(groupDevices) + .when(mCsipService) .getGroupDevicesOrdered(mCurrentDevice, BluetoothUuid.CAP); - doReturn(groupDevices).when(mCsipService) + doReturn(groupDevices) + .when(mCsipService) .getGroupDevicesOrdered(mCurrentDevice1, BluetoothUuid.CAP); // Prepare connected devices @@ -491,38 +496,45 @@ public class BassClientServiceTest { assertThat(mBassClientService.connect(mCurrentDevice1)).isTrue(); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { // Verify the call verify(sm).sendMessage(eq(BassClientStateMachine.CONNECT)); // Notify the service about the connection event BluetoothDevice dev = sm.getDevice(); - doCallRealMethod().when(sm) - .broadcastConnectionState(eq(dev), any(Integer.class), any(Integer.class)); + doCallRealMethod() + .when(sm) + .broadcastConnectionState(eq(dev), any(Integer.class), any(Integer.class)); sm.mService = mBassClientService; sm.mDevice = dev; - sm.broadcastConnectionState(dev, BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + sm.broadcastConnectionState( + dev, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); doReturn(BluetoothProfile.STATE_CONNECTED).when(sm).getConnectionState(); doReturn(true).when(sm).isConnected(); // Inject initial broadcast source state BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, - BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, - null); + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, + BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + null); injectRemoteSourceStateRemoval(sm, TEST_SOURCE_ID); - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, - BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, - null); + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, + BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + null); injectRemoteSourceStateRemoval(sm, TEST_SOURCE_ID + 1); } } @@ -926,16 +938,16 @@ public class BassClientServiceTest { syncHandle, testDevice, TEST_ADVERTISER_SID, 0, 200, BluetoothGatt.GATT_SUCCESS); } - private void verifyConnectionStateIntent(int timeoutMs, BluetoothDevice device, int newState, - int prevState) { + private void verifyConnectionStateIntent( + int timeoutMs, BluetoothDevice device, int newState, int prevState) { Intent intent = TestUtils.waitForIntent(timeoutMs, mIntentQueue.get(device)); assertThat(intent).isNotNull(); assertThat(BluetoothLeBroadcastAssistant.ACTION_CONNECTION_STATE_CHANGED) .isEqualTo(intent.getAction()); assertThat(device).isEqualTo(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); assertThat(newState).isEqualTo(intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - assertThat(prevState).isEqualTo(intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, - -1)); + assertThat(prevState) + .isEqualTo(intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)); } private void handleHandoverSupport() { @@ -955,40 +967,48 @@ public class BassClientServiceTest { // Verify all group members getting ADD_BCAST_SOURCE message assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); - Message msg = messageCaptor.getAllValues().stream() - .filter(m -> (m.what == BassClientStateMachine.ADD_BCAST_SOURCE) - && (m.obj == meta)) - .findFirst() - .orElse(null); + Message msg = + messageCaptor.getAllValues().stream() + .filter( + m -> + (m.what == BassClientStateMachine.ADD_BCAST_SOURCE) + && (m.obj == meta)) + .findFirst() + .orElse(null); assertThat(msg).isNotNull(); } } - private BluetoothLeBroadcastReceiveState injectRemoteSourceState(BassClientStateMachine sm, - BluetoothLeBroadcastMetadata meta, int sourceId, int paSynState, int encryptionState, - byte[] badCode, long bisSyncState) { - BluetoothLeBroadcastReceiveState recvState = new BluetoothLeBroadcastReceiveState( - sourceId, - meta.getSourceAddressType(), - meta.getSourceDevice(), - meta.getSourceAdvertisingSid(), - meta.getBroadcastId(), - paSynState, - encryptionState, - badCode, - meta.getSubgroups().size(), - // Bis sync states - meta.getSubgroups().stream() - .map(e -> bisSyncState) - .collect(Collectors.toList()), - meta.getSubgroups().stream() + private BluetoothLeBroadcastReceiveState injectRemoteSourceState( + BassClientStateMachine sm, + BluetoothLeBroadcastMetadata meta, + int sourceId, + int paSynState, + int encryptionState, + byte[] badCode, + long bisSyncState) { + BluetoothLeBroadcastReceiveState recvState = + new BluetoothLeBroadcastReceiveState( + sourceId, + meta.getSourceAddressType(), + meta.getSourceDevice(), + meta.getSourceAdvertisingSid(), + meta.getBroadcastId(), + paSynState, + encryptionState, + badCode, + meta.getSubgroups().size(), + // Bis sync states + meta.getSubgroups().stream() + .map(e -> bisSyncState) + .collect(Collectors.toList()), + meta.getSubgroups().stream() .map(e -> e.getContentMetadata()) - .collect(Collectors.toList()) - ); + .collect(Collectors.toList())); doReturn(meta).when(sm).getCurrentBroadcastMetadata(eq(sourceId)); List stateList = sm.getAllSources(); @@ -1004,28 +1024,46 @@ public class BassClientServiceTest { } private BluetoothLeBroadcastReceiveState injectRemoteSourceStateSourceAdded( - BassClientStateMachine sm, BluetoothLeBroadcastMetadata meta, int sourceId, - int paSynState, int encryptionState, byte[] badCode) { + BassClientStateMachine sm, + BluetoothLeBroadcastMetadata meta, + int sourceId, + int paSynState, + int encryptionState, + byte[] badCode) { BluetoothLeBroadcastReceiveState recvState = - injectRemoteSourceState(sm, meta, sourceId, paSynState, encryptionState, badCode, + injectRemoteSourceState( + sm, + meta, + sourceId, + paSynState, + encryptionState, + badCode, (long) 0x00000002); - mBassClientService.getCallbacks().notifySourceAdded(sm.getDevice(), recvState, - BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); + mBassClientService + .getCallbacks() + .notifySourceAdded( + sm.getDevice(), recvState, BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); TestUtils.waitForLooperToFinishScheduledTask(mBassClientService.getCallbacks().getLooper()); return recvState; } private BluetoothLeBroadcastReceiveState injectRemoteSourceStateChanged( - BassClientStateMachine sm, BluetoothLeBroadcastMetadata meta, int sourceId, - int paSynState, int encryptionState, byte[] badCode, long bisSyncState) { + BassClientStateMachine sm, + BluetoothLeBroadcastMetadata meta, + int sourceId, + int paSynState, + int encryptionState, + byte[] badCode, + long bisSyncState) { BluetoothLeBroadcastReceiveState recvState = - injectRemoteSourceState(sm, meta, sourceId, paSynState, encryptionState, badCode, - bisSyncState); + injectRemoteSourceState( + sm, meta, sourceId, paSynState, encryptionState, badCode, bisSyncState); - mBassClientService.getCallbacks().notifyReceiveStateChanged(sm.getDevice(), - recvState.getSourceId(), recvState); + mBassClientService + .getCallbacks() + .notifyReceiveStateChanged(sm.getDevice(), recvState.getSourceId(), recvState); TestUtils.waitForLooperToFinishScheduledTask(mBassClientService.getCallbacks().getLooper()); return recvState; @@ -1034,35 +1072,37 @@ public class BassClientServiceTest { private void injectRemoteSourceStateRemoval(BassClientStateMachine sm, int sourceId) { List stateList = sm.getAllSources(); if (stateList == null) { - stateList = new ArrayList(); + stateList = new ArrayList(); } - stateList.replaceAll(e -> { - if (e.getSourceId() != sourceId) return e; - return new BluetoothLeBroadcastReceiveState( - sourceId, - BluetoothDevice.ADDRESS_TYPE_PUBLIC, - mBluetoothAdapter.getRemoteLeDevice("00:00:00:00:00:00", - BluetoothDevice.ADDRESS_TYPE_PUBLIC), - 0, - 0, - BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, - null, - 0, - Arrays.asList(new Long[0]), - Arrays.asList(new BluetoothLeAudioContentMetadata[0]) - ); - }); + stateList.replaceAll( + e -> { + if (e.getSourceId() != sourceId) return e; + return new BluetoothLeBroadcastReceiveState( + sourceId, + BluetoothDevice.ADDRESS_TYPE_PUBLIC, + mBluetoothAdapter.getRemoteLeDevice( + "00:00:00:00:00:00", BluetoothDevice.ADDRESS_TYPE_PUBLIC), + 0, + 0, + BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, + BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + null, + 0, + Arrays.asList(new Long[0]), + Arrays.asList(new BluetoothLeAudioContentMetadata[0])); + }); doReturn(stateList).when(sm).getAllSources(); - mBassClientService.getCallbacks().notifySourceRemoved(sm.getDevice(), sourceId, - BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); + mBassClientService + .getCallbacks() + .notifySourceRemoved( + sm.getDevice(), sourceId, BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); TestUtils.waitForLooperToFinishScheduledTask(mBassClientService.getCallbacks().getLooper()); } /** - * Test whether service.addSource() does send proper messages to all the - * state machines within the Csip coordinated group + * Test whether service.addSource() does send proper messages to all the state machines within + * the Csip coordinated group */ @Test public void testAddSourceForGroup() { @@ -1074,10 +1114,7 @@ public class BassClientServiceTest { verifyAddSourceForGroup(meta); } - - /** - * Test whether service.addSource() source id can be propagated through callback correctly - */ + /** Test whether service.addSource() source id can be propagated through callback correctly */ @Test public void testAddSourceCallbackForGroup() { prepareConnectedDeviceGroup(); @@ -1086,43 +1123,56 @@ public class BassClientServiceTest { onSyncEstablished(mSourceDevice, TEST_SYNC_HANDLE); BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); verifyAddSourceForGroup(meta); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); // verify source id try { - verify(mCallback, timeout(TIMEOUT_MS).atLeastOnce()). - onSourceAdded(eq(mCurrentDevice), eq(TEST_SOURCE_ID), - eq(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST)); + verify(mCallback, timeout(TIMEOUT_MS).atLeastOnce()) + .onSourceAdded( + eq(mCurrentDevice), + eq(TEST_SOURCE_ID), + eq(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); // verify source id try { - verify(mCallback, timeout(TIMEOUT_MS).atLeastOnce()). - onSourceAdded(eq(mCurrentDevice1), eq(TEST_SOURCE_ID + 1), - eq(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST)); + verify(mCallback, timeout(TIMEOUT_MS).atLeastOnce()) + .onSourceAdded( + eq(mCurrentDevice1), + eq(TEST_SOURCE_ID + 1), + eq(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } } } - /** - * Test whether service.modifySource() does send proper messages to all the - * state machines within the Csip coordinated group + + /** + * Test whether service.modifySource() does send proper messages to all the state machines + * within the Csip coordinated group */ @Test public void testModifySourceForGroup() { @@ -1132,20 +1182,28 @@ public class BassClientServiceTest { onSyncEstablished(mSourceDevice, TEST_SYNC_HANDLE); BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); verifyAddSourceForGroup(meta); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } } @@ -1153,18 +1211,20 @@ public class BassClientServiceTest { // Update broadcast source using other member of the same group BluetoothLeBroadcastMetadata metaUpdate = new BluetoothLeBroadcastMetadata.Builder(meta) - .setBroadcastId(TEST_BROADCAST_ID + 1).build(); + .setBroadcastId(TEST_BROADCAST_ID + 1) + .build(); mBassClientService.modifySource(mCurrentDevice1, TEST_SOURCE_ID + 1, metaUpdate); // Verify all group members getting UPDATE_BCAST_SOURCE message on proper sources assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); - Optional msg = messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) - .findFirst(); + Optional msg = + messageCaptor.getAllValues().stream() + .filter(m -> m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) + .findFirst(); assertThat(msg.isPresent()).isEqualTo(true); assertThat(msg.get().obj).isEqualTo(metaUpdate); @@ -1178,8 +1238,8 @@ public class BassClientServiceTest { } /** - * Test whether service.removeSource() does send proper messages to all the - * state machines within the Csip coordinated group + * Test whether service.removeSource() does send proper messages to all the state machines + * within the Csip coordinated group */ @Test public void testRemoveSourceForGroup() { @@ -1189,20 +1249,28 @@ public class BassClientServiceTest { onSyncEstablished(mSourceDevice, TEST_SYNC_HANDLE); BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); verifyAddSourceForGroup(meta); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } } @@ -1212,13 +1280,14 @@ public class BassClientServiceTest { // Verify all group members getting REMOVE_BCAST_SOURCE message assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); - Optional msg = messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.REMOVE_BCAST_SOURCE) - .findFirst(); + Optional msg = + messageCaptor.getAllValues().stream() + .filter(m -> m.what == BassClientStateMachine.REMOVE_BCAST_SOURCE) + .findFirst(); assertThat(msg.isPresent()).isEqualTo(true); // Verify using the right sourceId on each device @@ -1316,9 +1385,7 @@ public class BassClientServiceTest { } } - /** - * Test whether the group operation flag is set on addSource() and removed on removeSource - */ + /** Test whether the group operation flag is set on addSource() and removed on removeSource */ @Test public void testGroupStickyFlagSetUnset() { prepareConnectedDeviceGroup(); @@ -1328,20 +1395,28 @@ public class BassClientServiceTest { BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); verifyAddSourceForGroup(meta); // Inject source added - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } } @@ -1349,13 +1424,14 @@ public class BassClientServiceTest { // Remove broadcast source mBassClientService.removeSource(mCurrentDevice, TEST_SOURCE_ID); // Inject source removed - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); - Optional msg = messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.REMOVE_BCAST_SOURCE) - .findFirst(); + Optional msg = + messageCaptor.getAllValues().stream() + .filter(m -> m.what == BassClientStateMachine.REMOVE_BCAST_SOURCE) + .findFirst(); assertThat(msg.isPresent()).isEqualTo(true); if (sm.getDevice().equals(mCurrentDevice)) { @@ -1376,19 +1452,21 @@ public class BassClientServiceTest { // Verrify that one device got the message... verify(mStateMachines.get(mCurrentDevice), atLeast(1)).sendMessage(messageCaptor.capture()); - msg = messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) - .findFirst(); + msg = + messageCaptor.getAllValues().stream() + .filter(m -> m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) + .findFirst(); assertThat(msg.isPresent()).isTrue(); assertThat(msg.orElse(null)).isNotNull(); - //... but not the other one, since the sticky group flag should have been removed + // ... but not the other one, since the sticky group flag should have been removed messageCaptor = ArgumentCaptor.forClass(Message.class); verify(mStateMachines.get(mCurrentDevice1), atLeast(1)) .sendMessage(messageCaptor.capture()); - msg = messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) - .findFirst(); + msg = + messageCaptor.getAllValues().stream() + .filter(m -> m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) + .findFirst(); assertThat(msg.isPresent()).isFalse(); } @@ -1450,8 +1528,8 @@ public class BassClientServiceTest { } /** - * Test that after multiple calls to service.addSource() with a group operation flag set, - * there are two call to service.removeSource() needed to clear the flag + * Test that after multiple calls to service.addSource() with a group operation flag set, there + * are two call to service.removeSource() needed to clear the flag */ @Test public void testAddRemoveMultipleSourcesForGroup() { @@ -1462,20 +1540,28 @@ public class BassClientServiceTest { onSyncEstablished(mSourceDevice, TEST_SYNC_HANDLE); verifyAddSourceForGroup(meta); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else { throw new AssertionError("Unexpected device"); @@ -1485,25 +1571,34 @@ public class BassClientServiceTest { // Add another broadcast source BluetoothLeBroadcastMetadata meta1 = new BluetoothLeBroadcastMetadata.Builder(meta) - .setBroadcastId(TEST_BROADCAST_ID + 1).build(); + .setBroadcastId(TEST_BROADCAST_ID + 1) + .build(); onScanResult(mSourceDevice2, TEST_BROADCAST_ID + 1); onSyncEstablished(mSourceDevice2, TEST_SYNC_HANDLE + 1); verifyAddSourceForGroup(meta1); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta1, TEST_SOURCE_ID + 2, + injectRemoteSourceStateSourceAdded( + sm, + meta1, + TEST_SOURCE_ID + 2, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta1.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta1.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta1, TEST_SOURCE_ID + 3, + injectRemoteSourceStateSourceAdded( + sm, + meta1, + TEST_SOURCE_ID + 3, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta1.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta1.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else { throw new AssertionError("Unexpected device"); @@ -1513,13 +1608,14 @@ public class BassClientServiceTest { // Remove the first broadcast source mBassClientService.removeSource(mCurrentDevice, TEST_SOURCE_ID); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); - Optional msg = messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.REMOVE_BCAST_SOURCE) - .findFirst(); + Optional msg = + messageCaptor.getAllValues().stream() + .filter(m -> m.what == BassClientStateMachine.REMOVE_BCAST_SOURCE) + .findFirst(); assertThat(msg.isPresent()).isEqualTo(true); // Verify using the right sourceId on each device @@ -1538,21 +1634,22 @@ public class BassClientServiceTest { BluetoothLeBroadcastMetadata metaUpdate = createBroadcastMetadata(TEST_BROADCAST_ID + 3); mBassClientService.modifySource(mCurrentDevice1, TEST_SOURCE_ID + 3, metaUpdate); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); - Optional msg = messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) - .findFirst(); + Optional msg = + messageCaptor.getAllValues().stream() + .filter(m -> m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) + .findFirst(); assertThat(msg.isPresent()).isEqualTo(true); assertThat(msg.get().obj).isEqualTo(metaUpdate); // Verify using the right sourceId on each device if (sm.getDevice().equals(mCurrentDevice)) { - assertThat(msg.get().arg1).isEqualTo(TEST_SOURCE_ID + 2); + assertThat(msg.get().arg1).isEqualTo(TEST_SOURCE_ID + 2); } else if (sm.getDevice().equals(mCurrentDevice1)) { - assertThat(msg.get().arg1).isEqualTo(TEST_SOURCE_ID + 3); + assertThat(msg.get().arg1).isEqualTo(TEST_SOURCE_ID + 3); } else { throw new AssertionError("Unexpected device"); } @@ -1562,22 +1659,32 @@ public class BassClientServiceTest { // REMOVE_BCAST_SOURCE message for the second source mBassClientService.removeSource(mCurrentDevice, TEST_SOURCE_ID + 2); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); if (sm.getDevice().equals(mCurrentDevice)) { - Optional msg = messageCaptor.getAllValues().stream() - .filter(m -> (m.what == BassClientStateMachine.REMOVE_BCAST_SOURCE) - && (m.arg1 == TEST_SOURCE_ID + 2)) - .findFirst(); + Optional msg = + messageCaptor.getAllValues().stream() + .filter( + m -> + (m.what + == BassClientStateMachine + .REMOVE_BCAST_SOURCE) + && (m.arg1 == TEST_SOURCE_ID + 2)) + .findFirst(); assertThat(msg.isPresent()).isEqualTo(true); injectRemoteSourceStateRemoval(sm, TEST_SOURCE_ID + 2); } else if (sm.getDevice().equals(mCurrentDevice1)) { - Optional msg = messageCaptor.getAllValues().stream() - .filter(m -> (m.what == BassClientStateMachine.REMOVE_BCAST_SOURCE) - && (m.arg1 == TEST_SOURCE_ID + 3)) - .findFirst(); + Optional msg = + messageCaptor.getAllValues().stream() + .filter( + m -> + (m.what + == BassClientStateMachine + .REMOVE_BCAST_SOURCE) + && (m.arg1 == TEST_SOURCE_ID + 3)) + .findFirst(); assertThat(msg.isPresent()).isEqualTo(true); injectRemoteSourceStateRemoval(sm, TEST_SOURCE_ID + 3); } else { @@ -1586,32 +1693,40 @@ public class BassClientServiceTest { } // Fake the autonomous source change - or other client setting the source - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { clearInvocations(sm); BluetoothLeBroadcastMetadata metaOther = createBroadcastMetadata(TEST_BROADCAST_ID + 20); - injectRemoteSourceStateSourceAdded(sm, metaOther, TEST_SOURCE_ID + 20, + injectRemoteSourceStateSourceAdded( + sm, + metaOther, + TEST_SOURCE_ID + 20, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } // Modify this source and verify it is not group managed BluetoothLeBroadcastMetadata metaUpdate2 = createBroadcastMetadata(TEST_BROADCAST_ID + 30); mBassClientService.modifySource(mCurrentDevice1, TEST_SOURCE_ID + 20, metaUpdate2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { verify(sm, never()).sendMessage(any()); } else if (sm.getDevice().equals(mCurrentDevice1)) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, times(1)).sendMessage(messageCaptor.capture()); - List msgs = messageCaptor.getAllValues().stream() - .filter(m -> (m.what == BassClientStateMachine.UPDATE_BCAST_SOURCE) - && (m.arg1 == TEST_SOURCE_ID + 20)) - .collect(Collectors.toList()); + List msgs = + messageCaptor.getAllValues().stream() + .filter( + m -> + (m.what + == BassClientStateMachine + .UPDATE_BCAST_SOURCE) + && (m.arg1 == TEST_SOURCE_ID + 20)) + .collect(Collectors.toList()); assertThat(msgs.size()).isEqualTo(1); } else { throw new AssertionError("Unexpected device"); @@ -1636,20 +1751,28 @@ public class BassClientServiceTest { // Prepare valid source for group BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); verifyAddSourceForGroup(meta); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } } @@ -1657,7 +1780,7 @@ public class BassClientServiceTest { // Verify errors are reported for the entire group mBassClientService.modifySource(mCurrentDevice, TEST_SOURCE_ID, null); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { BluetoothDevice dev = sm.getDevice(); try { verify(mCallback, after(TIMEOUT_MS)) @@ -1671,14 +1794,14 @@ public class BassClientServiceTest { } assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { doReturn(BluetoothProfile.STATE_DISCONNECTED).when(sm).getConnectionState(); } // Verify errors are reported for the entire group mBassClientService.removeSource(mCurrentDevice, TEST_SOURCE_ID); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { BluetoothDevice dev = sm.getDevice(); try { verify(mCallback, after(TIMEOUT_MS)) @@ -1693,17 +1816,20 @@ public class BassClientServiceTest { } /** - * Test that an outgoing connection to two device that have BASS UUID is successful - * and a connection state change intent is sent + * Test that an outgoing connection to two device that have BASS UUID is successful and a + * connection state change intent is sent */ @Test public void testConnectedIntent() { prepareConnectedDeviceGroup(); assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { BluetoothDevice dev = sm.getDevice(); - verifyConnectionStateIntent(TIMEOUT_MS, dev, BluetoothProfile.STATE_CONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + dev, + BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); } @@ -2713,19 +2839,60 @@ public class BassClientServiceTest { final int testSyncHandle1 = 1; final int testSyncHandle2 = 2; final int testSyncHandle3 = 3; - byte[] scanRecord = new byte[]{ - 0x02, 0x01, 0x1a, // advertising flags - 0x05, 0x02, 0x52, 0x18, 0x0a, 0x11, // 16 bit service uuids - 0x04, 0x09, 0x50, 0x65, 0x64, // name - 0x02, 0x0A, (byte) 0xec, // tx power level - 0x05, 0x30, 0x54, 0x65, 0x73, 0x74, // broadcast name: Test - 0x06, 0x16, 0x52, 0x18, 0x50, 0x64, 0x65, // service data - 0x08, 0x16, 0x56, 0x18, 0x07, 0x03, 0x06, 0x07, 0x08, - // service data - public broadcast, - // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 - 0x05, (byte) 0xff, (byte) 0xe0, 0x00, 0x02, 0x15, // manufacturer specific data - 0x03, 0x50, 0x01, 0x02, // an unknown data type won't cause trouble - }; + byte[] scanRecord = + new byte[] { + 0x02, + 0x01, + 0x1a, // advertising flags + 0x05, + 0x02, + 0x52, + 0x18, + 0x0a, + 0x11, // 16 bit service uuids + 0x04, + 0x09, + 0x50, + 0x65, + 0x64, // name + 0x02, + 0x0A, + (byte) 0xec, // tx power level + 0x05, + 0x30, + 0x54, + 0x65, + 0x73, + 0x74, // broadcast name: Test + 0x06, + 0x16, + 0x52, + 0x18, + 0x50, + 0x64, + 0x65, // service data + 0x08, + 0x16, + 0x56, + 0x18, + 0x07, + 0x03, + 0x06, + 0x07, + 0x08, + // service data - public broadcast, + // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 + 0x05, + (byte) 0xff, + (byte) 0xe0, + 0x00, + 0x02, + 0x15, // manufacturer specific data + 0x03, + 0x50, + 0x01, + 0x02, // an unknown data type won't cause trouble + }; ScanRecord record = ScanRecord.parseFromBytes(scanRecord); prepareConnectedDeviceGroup(); @@ -2752,8 +2919,9 @@ public class BassClientServiceTest { assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice).size()).isEqualTo(4); assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice1).size()).isEqualTo(4); - BluetoothDevice testDevice4 = mBluetoothAdapter.getRemoteLeDevice( - "00:01:02:03:04:05", BluetoothDevice.ADDRESS_TYPE_RANDOM); + BluetoothDevice testDevice4 = + mBluetoothAdapter.getRemoteLeDevice( + "00:01:02:03:04:05", BluetoothDevice.ADDRESS_TYPE_RANDOM); ScanResult scanResult1 = new ScanResult(testDevice4, 0, 0, 0, 0, 0, 0, 0, record, 0); mBassClientService.selectSource(mCurrentDevice, scanResult1, false); mBassClientService.selectSource(mCurrentDevice1, scanResult1, false); @@ -2761,9 +2929,10 @@ public class BassClientServiceTest { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); - Optional msg = messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.REACHED_MAX_SOURCE_LIMIT) - .findFirst(); + Optional msg = + messageCaptor.getAllValues().stream() + .filter(m -> m.what == BassClientStateMachine.REACHED_MAX_SOURCE_LIMIT) + .findFirst(); assertThat(msg.isPresent()).isEqualTo(true); } @@ -2809,7 +2978,9 @@ public class BassClientServiceTest { null, null); - assertThat(mBassClientService.getPeriodicAdvertisementResult(testDevice, testBroadcastIdInvalid)) + assertThat( + mBassClientService.getPeriodicAdvertisementResult( + testDevice, testBroadcastIdInvalid)) .isEqualTo(null); PeriodicAdvertisementResult paResult = mBassClientService.getPeriodicAdvertisementResult(testDevice, testBroadcastId); @@ -2880,20 +3051,28 @@ public class BassClientServiceTest { onSyncEstablished(mSourceDevice, TEST_SYNC_HANDLE); BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); verifyAddSourceForGroup(meta); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); } } @@ -2994,7 +3173,7 @@ public class BassClientServiceTest { // Verify all group members getting UPDATE_BCAST_SOURCE/ADD SOURCE resuming syncmessage assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); long count; @@ -3052,38 +3231,56 @@ public class BassClientServiceTest { onSyncEstablished(mSourceDevice, TEST_SYNC_HANDLE); BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); verifyAddSourceForGroup(meta); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); // Update receiver state - injectRemoteSourceStateChanged(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateChanged( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, - null, (long) 0x00000001); + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + null, + (long) 0x00000001); verify(mLeAudioService).activeBroadcastAssistantNotification(eq(true)); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateSourceAdded(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateSourceAdded( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, null); // Update receiver state - injectRemoteSourceStateChanged(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateChanged( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, - null, (long) 0x00000002); + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + null, + (long) 0x00000002); } } @@ -3151,7 +3348,7 @@ public class BassClientServiceTest { // Verify all group members getting UPDATE_BCAST_SOURCE ressuming syncmessage assertThat(mStateMachines.size()).isEqualTo(2); - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); long count; @@ -3201,22 +3398,32 @@ public class BassClientServiceTest { } // Update receiver state with lost BIS sync - for (BassClientStateMachine sm: mStateMachines.values()) { + for (BassClientStateMachine sm : mStateMachines.values()) { if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateChanged(sm, meta, TEST_SOURCE_ID, + injectRemoteSourceStateChanged( + sm, + meta, + TEST_SOURCE_ID, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, - null, (long) 0x00000000); + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + null, + (long) 0x00000000); verify(mLeAudioService).activeBroadcastAssistantNotification(eq(false)); } else if (sm.getDevice().equals(mCurrentDevice1)) { - injectRemoteSourceStateChanged(sm, meta, TEST_SOURCE_ID + 1, + injectRemoteSourceStateChanged( + sm, + meta, + TEST_SOURCE_ID + 1, BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - meta.isEncrypted() ? - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING : - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, - null, (long) 0x00000000); + meta.isEncrypted() + ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING + : BluetoothLeBroadcastReceiveState + .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + null, + (long) 0x00000000); } } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java index 5ee89dd3e88..1077fe4c16d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java @@ -129,8 +129,7 @@ import java.util.UUID; @MediumTest @RunWith(JUnit4.class) public class BassClientStateMachineTest { - @Rule - public final MockitoRule mockito = MockitoJUnit.rule(); + @Rule public final MockitoRule mockito = MockitoJUnit.rule(); @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); @@ -165,8 +164,9 @@ public class BassClientStateMachineTest { TestUtils.setAdapterService(mAdapterService); BluetoothMethodProxy.setInstanceForTesting(mMethodProxy); - doNothing().when(mMethodProxy).periodicAdvertisingManagerTransferSync( - any(), any(), anyInt(), anyInt()); + doNothing() + .when(mMethodProxy) + .periodicAdvertisingManagerTransferSync(any(), any(), anyInt(), anyInt()); // Get a device for testing mTestDevice = TestUtils.getTestDevice(mAdapter, 0); @@ -214,13 +214,11 @@ public class BassClientStateMachineTest { TestUtils.clearAdapterService(mAdapterService); } - /** - * Test that default state is disconnected - */ + /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, - mBassClientStateMachine.getConnectionState()); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mBassClientStateMachine.getConnectionState()); } /** @@ -236,9 +234,7 @@ public class BassClientStateMachineTest { mBassClientStateMachine.mShouldAllowGatt = allow; } - /** - * Test that an incoming connection with policy forbidding connection is rejected - */ + /** Test that an incoming connection with policy forbidding connection is rejected */ @Test public void testOkToConnectFails() { allowConnection(false); @@ -248,11 +244,12 @@ public class BassClientStateMachineTest { mBassClientStateMachine.sendMessage(CONNECT); // Verify that no connection state broadcast is executed - verify(mBassClientService, after(WAIT_MS).never()).sendBroadcast(any(Intent.class), - anyString()); + verify(mBassClientService, after(WAIT_MS).never()) + .sendBroadcast(any(Intent.class), anyString()); // Check that we are in Disconnected state - Assert.assertThat(mBassClientStateMachine.getCurrentState(), + Assert.assertThat( + mBassClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BassClientStateMachine.Disconnected.class)); } @@ -265,11 +262,12 @@ public class BassClientStateMachineTest { mBassClientStateMachine.sendMessage(CONNECT); // Verify that no connection state broadcast is executed - verify(mBassClientService, after(WAIT_MS).never()).sendBroadcast(any(Intent.class), - anyString()); + verify(mBassClientService, after(WAIT_MS).never()) + .sendBroadcast(any(Intent.class), anyString()); // Check that we are in Disconnected state - Assert.assertThat(mBassClientStateMachine.getCurrentState(), + Assert.assertThat( + mBassClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BassClientStateMachine.Disconnected.class)); assertNull(mBassClientStateMachine.mBluetoothGatt); } @@ -284,12 +282,14 @@ public class BassClientStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mBassClientService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - intentArgument1.capture(), anyString(), any(Bundle.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify(mBassClientService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertThat(mBassClientStateMachine.getCurrentState(), + Assert.assertThat( + mBassClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BassClientStateMachine.Connecting.class)); assertNotNull(mBassClientStateMachine.mGattCallback); @@ -299,10 +299,11 @@ public class BassClientStateMachineTest { // Verify that the expected number of broadcasts are executed: // - two calls to broadcastConnectionState(): Disconnected -> Connecting -> Connected ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mBassClientService, timeout(TIMEOUT_MS).times(2)).sendBroadcast( - intentArgument2.capture(), anyString(), any(Bundle.class)); + verify(mBassClientService, timeout(TIMEOUT_MS).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); - Assert.assertThat(mBassClientStateMachine.getCurrentState(), + Assert.assertThat( + mBassClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BassClientStateMachine.Connected.class)); } @@ -316,22 +317,26 @@ public class BassClientStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mBassClientService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - intentArgument1.capture(), anyString(), any(Bundle.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify(mBassClientService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertThat(mBassClientStateMachine.getCurrentState(), + Assert.assertThat( + mBassClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BassClientStateMachine.Connecting.class)); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mBassClientService, timeout(TIMEOUT_MS).times( - 2)).sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + verify(mBassClientService, timeout(TIMEOUT_MS).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertThat(mBassClientStateMachine.getCurrentState(), + Assert.assertThat( + mBassClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(BassClientStateMachine.Disconnected.class)); } @@ -411,8 +416,8 @@ public class BassClientStateMachineTest { // --> connected // Make bluetoothGatt non-null so state will transit - mBassClientStateMachine.mBluetoothGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + mBassClientStateMachine.mBluetoothGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBroadcastScanControlPoint = new BluetoothGattCharacteristic( BassConstants.BASS_BCAST_AUDIO_SCAN_CTRL_POINT, @@ -468,8 +473,8 @@ public class BassClientStateMachineTest { @Test public void acquireAllBassChars() { - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; // Do nothing when mBluetoothGatt.getService returns null mBassClientStateMachine.acquireAllBassChars(); @@ -520,8 +525,8 @@ public class BassClientStateMachineTest { assertThat(mBassClientStateMachine.getDevice()).isEqualTo(mTestDevice); assertThat(mBassClientStateMachine.hasPendingSourceOperation()).isFalse(); assertThat(mBassClientStateMachine.hasPendingSourceOperation(1)).isFalse(); - assertThat(mBassClientStateMachine.isEmpty(new byte[] { 0 })).isTrue(); - assertThat(mBassClientStateMachine.isEmpty(new byte[] { 1 })).isFalse(); + assertThat(mBassClientStateMachine.isEmpty(new byte[] {0})).isTrue(); + assertThat(mBassClientStateMachine.isEmpty(new byte[] {1})).isFalse(); assertThat(mBassClientStateMachine.isPendingRemove(invalidSourceId)).isFalse(); } @@ -529,15 +534,42 @@ public class BassClientStateMachineTest { public void parseScanRecord_withoutBaseData_callCancelActiveSync() { mSetFlagsRule.disableFlags( Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE); - byte[] scanRecord = new byte[]{ - 0x02, 0x01, 0x1a, // advertising flags - 0x05, 0x02, 0x0b, 0x11, 0x0a, 0x11, // 16 bit service uuids - 0x04, 0x09, 0x50, 0x65, 0x64, // name - 0x02, 0x0A, (byte) 0xec, // tx power level - 0x05, 0x16, 0x0b, 0x11, 0x50, 0x64, // service data - 0x05, (byte) 0xff, (byte) 0xe0, 0x00, 0x02, 0x15, // manufacturer specific data - 0x03, 0x50, 0x01, 0x02, // an unknown data type won't cause trouble - }; + byte[] scanRecord = + new byte[] { + 0x02, + 0x01, + 0x1a, // advertising flags + 0x05, + 0x02, + 0x0b, + 0x11, + 0x0a, + 0x11, // 16 bit service uuids + 0x04, + 0x09, + 0x50, + 0x65, + 0x64, // name + 0x02, + 0x0A, + (byte) 0xec, // tx power level + 0x05, + 0x16, + 0x0b, + 0x11, + 0x50, + 0x64, // service data + 0x05, + (byte) 0xff, + (byte) 0xe0, + 0x00, + 0x02, + 0x15, // manufacturer specific data + 0x03, + 0x50, + 0x01, + 0x02, // an unknown data type won't cause trouble + }; // need this to ensure expected mock behavior for getActiveSyncedSource when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); @@ -622,8 +654,8 @@ public class BassClientStateMachineTest { throws InterruptedException { mBassClientStateMachine.connectGatt(true); BluetoothGattCallback cb = mBassClientStateMachine.mGattCallback; - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; // disallow connection @@ -659,8 +691,8 @@ public class BassClientStateMachineTest { initToConnectingState(); mBassClientStateMachine.connectGatt(true); BluetoothGattCallback cb = mBassClientStateMachine.mGattCallback; - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; allowConnection(false); @@ -678,8 +710,8 @@ public class BassClientStateMachineTest { public void gattCallbackOnServicesDiscovered() { mBassClientStateMachine.connectGatt(true); BluetoothGattCallback cb = mBassClientStateMachine.mGattCallback; - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; // Do nothing if mDiscoveryInitiated is false. @@ -704,9 +736,7 @@ public class BassClientStateMachineTest { verify(btGatt).requestMtu(anyInt()); } - /** - * This also tests BassClientStateMachine#processBroadcastReceiverState. - */ + /** This also tests BassClientStateMachine#processBroadcastReceiverState. */ @Test public void gattCallbackOnCharacteristicRead() { mBassClientStateMachine.mShouldHandleMessage = false; @@ -716,8 +746,8 @@ public class BassClientStateMachineTest { BassClientService.Callbacks callbacks = Mockito.mock(BassClientService.Callbacks.class); BluetoothGattCharacteristic characteristic = Mockito.mock(BluetoothGattCharacteristic.class); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); when(characteristic.getUuid()).thenReturn(BassConstants.BASS_BCAST_RECEIVER_STATE); when(mBassClientService.getCallbacks()).thenReturn(callbacks); @@ -735,7 +765,6 @@ public class BassClientStateMachineTest { assertThat(mBassClientStateMachine.mMsgAgr1).isEqualTo(GATT_FAILURE); mBassClientStateMachine.mMsgWhats.clear(); - // Characteristic read failed and mBluetoothGatt is not null. mBassClientStateMachine.mBluetoothGatt = btGatt; when(characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG)).thenReturn(desc); @@ -747,7 +776,7 @@ public class BassClientStateMachineTest { // Tests for processBroadcastReceiverState int sourceId = 1; - byte[] value = new byte[] { }; + byte[] value = new byte[] {}; mBassClientStateMachine.mNumOfBroadcastReceiverStates = 2; mBassClientStateMachine.mPendingOperation = REMOVE_BCAST_SOURCE; mBassClientStateMachine.mPendingSourceId = (byte) sourceId; @@ -902,7 +931,7 @@ public class BassClientStateMachineTest { mBassClientStateMachine.mNumOfBroadcastReceiverStates = 1; Mockito.clearInvocations(characteristic); - when(characteristic.getValue()).thenReturn(new byte[] { }); + when(characteristic.getValue()).thenReturn(new byte[] {}); cb.onCharacteristicChanged(null, characteristic); verify(characteristic, atLeast(1)).getUuid(); verify(characteristic, atLeast(1)).getValue(); @@ -918,7 +947,8 @@ public class BassClientStateMachineTest { mBassClientStateMachine.connectGatt(true); BluetoothGattCallback cb = mBassClientStateMachine.mGattCallback; - BluetoothGattCharacteristic characteristic =Mockito.mock(BluetoothGattCharacteristic.class); + BluetoothGattCharacteristic characteristic = + Mockito.mock(BluetoothGattCharacteristic.class); when(characteristic.getUuid()).thenReturn(BassConstants.BASS_BCAST_AUDIO_SCAN_CTRL_POINT); cb.onCharacteristicWrite(null, characteristic, GATT_SUCCESS); @@ -947,8 +977,8 @@ public class BassClientStateMachineTest { cb.onMtuChanged(null, 10, GATT_SUCCESS); assertThat(mBassClientStateMachine.mMTUChangeRequested).isTrue(); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; cb.onMtuChanged(null, 10, GATT_SUCCESS); @@ -959,8 +989,8 @@ public class BassClientStateMachineTest { public void sendConnectMessage_inDisconnectedState() { initToDisconnectedState(); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; sendMessageAndVerifyTransition( @@ -974,8 +1004,8 @@ public class BassClientStateMachineTest { public void sendDisconnectMessage_inDisconnectedState() { initToDisconnectedState(); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; mBassClientStateMachine.sendMessage(DISCONNECT); @@ -988,8 +1018,8 @@ public class BassClientStateMachineTest { public void sendStateChangedMessage_inDisconnectedState() { initToDisconnectedState(); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; Message msgToConnectingState = @@ -1086,8 +1116,9 @@ public class BassClientStateMachineTest { public void sendConnectTimeMessage_inConnectingState() { initToConnectingState(); - Message timeoutWithDifferentDevice = mBassClientStateMachine.obtainMessage(CONNECT_TIMEOUT, - mAdapter.getRemoteDevice("00:00:00:00:00:00")); + Message timeoutWithDifferentDevice = + mBassClientStateMachine.obtainMessage( + CONNECT_TIMEOUT, mAdapter.getRemoteDevice("00:00:00:00:00:00")); mBassClientStateMachine.sendMessage(timeoutWithDifferentDevice); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mBassClientService, never()).sendBroadcast(any(Intent.class), anyString(), any()); @@ -1130,8 +1161,8 @@ public class BassClientStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mBassClientService, never()).sendBroadcast(any(Intent.class), anyString(), any()); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; sendMessageAndVerifyTransition( mBassClientStateMachine.obtainMessage(DISCONNECT), @@ -1167,34 +1198,35 @@ public class BassClientStateMachineTest { @Test public void sendReadBassCharacteristicsMessage_inConnectedState() { initToConnectedState(); - BluetoothGattCharacteristic gattCharacteristic = Mockito.mock( - BluetoothGattCharacteristic.class); + BluetoothGattCharacteristic gattCharacteristic = + Mockito.mock(BluetoothGattCharacteristic.class); mBassClientStateMachine.sendMessage(READ_BASS_CHARACTERISTICS, gattCharacteristic); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mBassClientService, never()).sendBroadcast(any(Intent.class), anyString(), any()); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; - sendMessageAndVerifyTransition(mBassClientStateMachine.obtainMessage( - READ_BASS_CHARACTERISTICS, gattCharacteristic), + sendMessageAndVerifyTransition( + mBassClientStateMachine.obtainMessage( + READ_BASS_CHARACTERISTICS, gattCharacteristic), BassClientStateMachine.ConnectedProcessing.class); } @Test public void sendStartScanOffloadMessage_inConnectedState() { initToConnectedState(); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; mBassClientStateMachine.sendMessage(START_SCAN_OFFLOAD); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mBassClientService, never()).sendBroadcast(any(Intent.class), anyString(), any()); - BluetoothGattCharacteristic scanControlPoint = Mockito.mock( - BluetoothGattCharacteristic.class); + BluetoothGattCharacteristic scanControlPoint = + Mockito.mock(BluetoothGattCharacteristic.class); mBassClientStateMachine.mBroadcastScanControlPoint = scanControlPoint; sendMessageAndVerifyTransition( @@ -1207,16 +1239,16 @@ public class BassClientStateMachineTest { @Test public void sendStopScanOffloadMessage_inConnectedState() { initToConnectedState(); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; mBassClientStateMachine.sendMessage(STOP_SCAN_OFFLOAD); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mBassClientService, never()).sendBroadcast(any(Intent.class), anyString(), any()); - BluetoothGattCharacteristic scanControlPoint = Mockito.mock( - BluetoothGattCharacteristic.class); + BluetoothGattCharacteristic scanControlPoint = + Mockito.mock(BluetoothGattCharacteristic.class); mBassClientStateMachine.mBroadcastScanControlPoint = scanControlPoint; sendMessageAndVerifyTransition( @@ -1255,30 +1287,79 @@ public class BassClientStateMachineTest { Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE); initToConnectedState(); - byte[] scanRecord = new byte[]{ - 0x02, 0x01, 0x1a, // advertising flags - 0x05, 0x02, 0x52, 0x18, 0x0a, 0x11, // 16 bit service uuids - 0x04, 0x09, 0x50, 0x65, 0x64, // name - 0x02, 0x0A, (byte) 0xec, // tx power level - 0x05, 0x30, 0x54, 0x65, 0x73, 0x74, // broadcast name: Test - 0x06, 0x16, 0x52, 0x18, 0x50, 0x64, 0x65, // service data - 0x08, 0x16, 0x56, 0x18, 0x07, 0x03, 0x06, 0x07, 0x08, - // service data - public broadcast, - // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 - 0x05, (byte) 0xff, (byte) 0xe0, 0x00, 0x02, 0x15, // manufacturer specific data - 0x03, 0x50, 0x01, 0x02, // an unknown data type won't cause trouble - }; + byte[] scanRecord = + new byte[] { + 0x02, + 0x01, + 0x1a, // advertising flags + 0x05, + 0x02, + 0x52, + 0x18, + 0x0a, + 0x11, // 16 bit service uuids + 0x04, + 0x09, + 0x50, + 0x65, + 0x64, // name + 0x02, + 0x0A, + (byte) 0xec, // tx power level + 0x05, + 0x30, + 0x54, + 0x65, + 0x73, + 0x74, // broadcast name: Test + 0x06, + 0x16, + 0x52, + 0x18, + 0x50, + 0x64, + 0x65, // service data + 0x08, + 0x16, + 0x56, + 0x18, + 0x07, + 0x03, + 0x06, + 0x07, + 0x08, + // service data - public broadcast, + // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 + 0x05, + (byte) 0xff, + (byte) 0xe0, + 0x00, + 0x02, + 0x15, // manufacturer specific data + 0x03, + 0x50, + 0x01, + 0x02, // an unknown data type won't cause trouble + }; ScanRecord record = ScanRecord.parseFromBytes(scanRecord); - doNothing().when(mMethodProxy).periodicAdvertisingManagerRegisterSync( - any(), any(), anyInt(), anyInt(), any(), any()); + doNothing() + .when(mMethodProxy) + .periodicAdvertisingManagerRegisterSync( + any(), any(), anyInt(), anyInt(), any(), any()); ScanResult scanResult = new ScanResult(mTestDevice, 0, 0, 0, 0, 0, 0, 0, record, 0); - mBassClientStateMachine.sendMessage( - SELECT_BCAST_SOURCE, BassConstants.AUTO, 0, scanResult); + mBassClientStateMachine.sendMessage(SELECT_BCAST_SOURCE, BassConstants.AUTO, 0, scanResult); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - verify(mBassClientService).updatePeriodicAdvertisementResultMap( - any(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), - any(), eq(TEST_BROADCAST_NAME)); + verify(mBassClientService) + .updatePeriodicAdvertisementResultMap( + any(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + any(), + eq(TEST_BROADCAST_NAME)); } @Test @@ -1298,11 +1379,11 @@ public class BassClientStateMachineTest { verify(mBassClientService).getCallbacks(); verify(callbacks).notifySourceAddFailed(any(), any(), anyInt()); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; - BluetoothGattCharacteristic scanControlPoint = Mockito.mock( - BluetoothGattCharacteristic.class); + BluetoothGattCharacteristic scanControlPoint = + Mockito.mock(BluetoothGattCharacteristic.class); mBassClientStateMachine.mBroadcastScanControlPoint = scanControlPoint; sendMessageAndVerifyTransition( @@ -1431,10 +1512,10 @@ public class BassClientStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(callbacks).notifySourceModifyFailed(any(), anyInt(), anyInt()); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); - BluetoothGattCharacteristic scanControlPoint = Mockito.mock( - BluetoothGattCharacteristic.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); + BluetoothGattCharacteristic scanControlPoint = + Mockito.mock(BluetoothGattCharacteristic.class); mBassClientStateMachine.mBluetoothGatt = btGatt; mBassClientStateMachine.mBroadcastScanControlPoint = scanControlPoint; mBassClientStateMachine.mPendingOperation = 0; @@ -1523,45 +1604,45 @@ public class BassClientStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); mBassClientStateMachine.mShouldHandleMessage = true; - BluetoothLeBroadcastReceiveState recvState = new BluetoothLeBroadcastReceiveState( - 2, - BluetoothDevice.ADDRESS_TYPE_PUBLIC, - mAdapter.getRemoteLeDevice("00:00:00:00:00:00", - BluetoothDevice.ADDRESS_TYPE_PUBLIC), - 0, - 0, - BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_CODE_REQUIRED, - null, - 0, - Arrays.asList(new Long[0]), - Arrays.asList(new BluetoothLeAudioContentMetadata[0]) - ); + BluetoothLeBroadcastReceiveState recvState = + new BluetoothLeBroadcastReceiveState( + 2, + BluetoothDevice.ADDRESS_TYPE_PUBLIC, + mAdapter.getRemoteLeDevice( + "00:00:00:00:00:00", BluetoothDevice.ADDRESS_TYPE_PUBLIC), + 0, + 0, + BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, + BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_CODE_REQUIRED, + null, + 0, + Arrays.asList(new Long[0]), + Arrays.asList(new BluetoothLeAudioContentMetadata[0])); mBassClientStateMachine.mSetBroadcastCodePending = false; mBassClientStateMachine.sendMessage(SET_BCAST_CODE, recvState); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); assertThat(mBassClientStateMachine.mSetBroadcastCodePending).isTrue(); - recvState = new BluetoothLeBroadcastReceiveState( - sourceId, - BluetoothDevice.ADDRESS_TYPE_PUBLIC, - mAdapter.getRemoteLeDevice("00:00:00:00:00:00", - BluetoothDevice.ADDRESS_TYPE_PUBLIC), - 0, - 0, - BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, - BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_CODE_REQUIRED, - null, - 0, - Arrays.asList(new Long[0]), - Arrays.asList(new BluetoothLeAudioContentMetadata[0]) - ); + recvState = + new BluetoothLeBroadcastReceiveState( + sourceId, + BluetoothDevice.ADDRESS_TYPE_PUBLIC, + mAdapter.getRemoteLeDevice( + "00:00:00:00:00:00", BluetoothDevice.ADDRESS_TYPE_PUBLIC), + 0, + 0, + BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, + BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_CODE_REQUIRED, + null, + 0, + Arrays.asList(new Long[0]), + Arrays.asList(new BluetoothLeAudioContentMetadata[0])); mBassClientStateMachine.sendMessage(SET_BCAST_CODE, recvState); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; - BluetoothGattCharacteristic scanControlPoint = Mockito.mock( - BluetoothGattCharacteristic.class); + BluetoothGattCharacteristic scanControlPoint = + Mockito.mock(BluetoothGattCharacteristic.class); mBassClientStateMachine.mBroadcastScanControlPoint = scanControlPoint; sendMessageAndVerifyTransition( @@ -1664,11 +1745,11 @@ public class BassClientStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(callbacks).notifySourceRemoveFailed(any(), anyInt(), anyInt()); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; - BluetoothGattCharacteristic scanControlPoint = Mockito.mock( - BluetoothGattCharacteristic.class); + BluetoothGattCharacteristic scanControlPoint = + Mockito.mock(BluetoothGattCharacteristic.class); mBassClientStateMachine.mBroadcastScanControlPoint = scanControlPoint; sendMessageAndVerifyTransition( @@ -1739,9 +1820,7 @@ public class BassClientStateMachineTest { assertNull(mBassClientStateMachine.mBluetoothGatt); } - /** - * This also tests BassClientStateMachine#sendPendingCallbacks - */ + /** This also tests BassClientStateMachine#sendPendingCallbacks */ @Test public void sendGattTxnProcessedMessage_inConnectedProcessingState() { initToConnectedProcessingState(); @@ -1848,38 +1927,31 @@ public class BassClientStateMachineTest { mBassClientStateMachine.sendMessage(START_SCAN_OFFLOAD); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(START_SCAN_OFFLOAD)) - .isTrue(); + assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(START_SCAN_OFFLOAD)).isTrue(); mBassClientStateMachine.sendMessage(STOP_SCAN_OFFLOAD); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(STOP_SCAN_OFFLOAD)) - .isTrue(); + assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(STOP_SCAN_OFFLOAD)).isTrue(); mBassClientStateMachine.sendMessage(SELECT_BCAST_SOURCE); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(SELECT_BCAST_SOURCE)) - .isTrue(); + assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(SELECT_BCAST_SOURCE)).isTrue(); mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(ADD_BCAST_SOURCE)) - .isTrue(); + assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(ADD_BCAST_SOURCE)).isTrue(); mBassClientStateMachine.sendMessage(SET_BCAST_CODE); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(SET_BCAST_CODE)) - .isTrue(); + assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(SET_BCAST_CODE)).isTrue(); mBassClientStateMachine.sendMessage(REMOVE_BCAST_SOURCE); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(REMOVE_BCAST_SOURCE)) - .isTrue(); + assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(REMOVE_BCAST_SOURCE)).isTrue(); mBassClientStateMachine.sendMessage(PSYNC_ACTIVE_TIMEOUT); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(PSYNC_ACTIVE_TIMEOUT)) - .isTrue(); + assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(PSYNC_ACTIVE_TIMEOUT)).isTrue(); mBassClientStateMachine.sendMessage(REACHED_MAX_SOURCE_LIMIT); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1982,19 +2054,60 @@ public class BassClientStateMachineTest { final int testSyncHandle = 1; initToConnectedState(); - byte[] scanRecord = new byte[]{ - 0x02, 0x01, 0x1a, // advertising flags - 0x05, 0x02, 0x52, 0x18, 0x0a, 0x11, // 16 bit service uuids - 0x04, 0x09, 0x50, 0x65, 0x64, // name - 0x02, 0x0A, (byte) 0xec, // tx power level - 0x05, 0x30, 0x54, 0x65, 0x73, 0x74, // broadcast name: Test - 0x06, 0x16, 0x52, 0x18, 0x2A, 0x00, 0x00, // service data, broadcast id 42 - 0x08, 0x16, 0x56, 0x18, 0x07, 0x03, 0x06, 0x07, 0x08, - // service data - public broadcast, - // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 - 0x05, (byte) 0xff, (byte) 0xe0, 0x00, 0x02, 0x15, // manufacturer specific data - 0x03, 0x50, 0x01, 0x02, // an unknown data type won't cause trouble - }; + byte[] scanRecord = + new byte[] { + 0x02, + 0x01, + 0x1a, // advertising flags + 0x05, + 0x02, + 0x52, + 0x18, + 0x0a, + 0x11, // 16 bit service uuids + 0x04, + 0x09, + 0x50, + 0x65, + 0x64, // name + 0x02, + 0x0A, + (byte) 0xec, // tx power level + 0x05, + 0x30, + 0x54, + 0x65, + 0x73, + 0x74, // broadcast name: Test + 0x06, + 0x16, + 0x52, + 0x18, + 0x2A, + 0x00, + 0x00, // service data, broadcast id 42 + 0x08, + 0x16, + 0x56, + 0x18, + 0x07, + 0x03, + 0x06, + 0x07, + 0x08, + // service data - public broadcast, + // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 + 0x05, + (byte) 0xff, + (byte) 0xe0, + 0x00, + 0x02, + 0x15, // manufacturer specific data + 0x03, + 0x50, + 0x01, + 0x02, // an unknown data type won't cause trouble + }; ScanRecord record = ScanRecord.parseFromBytes(scanRecord); ScanResult scanResult = new ScanResult(mTestDevice, 0, 0, 0, 0, 0, 0, 0, record, 0); @@ -2011,18 +2124,25 @@ public class BassClientStateMachineTest { mBassClientStateMachine.sendMessage(SELECT_BCAST_SOURCE, BassConstants.AUTO, 0, scanResult); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); // validate syncing to the same broadcast id will be skipped - verify(mBassClientService, never()).updatePeriodicAdvertisementResultMap( - any(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), - any(), any()); + verify(mBassClientService, never()) + .updatePeriodicAdvertisementResultMap( + any(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), any(), any()); // need this to ensure expected mock behavior for getActiveSyncedSource when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); mBassClientStateMachine.sendMessage(SELECT_BCAST_SOURCE, BassConstants.AUTO, 0, scanResult); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - verify(mBassClientService).updatePeriodicAdvertisementResultMap( - any(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), - any(), eq(TEST_BROADCAST_NAME)); + verify(mBassClientService) + .updatePeriodicAdvertisementResultMap( + any(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + any(), + eq(TEST_BROADCAST_NAME)); } @Test @@ -2045,25 +2165,79 @@ public class BassClientStateMachineTest { verify(mBassClientService).getCallbacks(); verify(callbacks).notifySourceAddFailed(any(), any(), anyInt()); - byte[] scanRecord = new byte[]{ - 0x02, 0x01, 0x1a, // advertising flags - 0x05, 0x02, 0x52, 0x18, 0x0a, 0x11, // 16 bit service uuids - 0x04, 0x09, 0x50, 0x65, 0x64, // name - 0x02, 0x0A, (byte) 0xec, // tx power level - 0x05, 0x30, 0x54, 0x65, 0x73, 0x74, // broadcast name: Test - 0x06, 0x16, 0x52, 0x18, 0x2A, 0x00, 0x00, // service data, broadcast id 42 - 0x08, 0x16, 0x56, 0x18, 0x07, 0x03, 0x06, 0x07, 0x08, - // service data - public broadcast, - // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 - 0x05, (byte) 0xff, (byte) 0xe0, 0x00, 0x02, 0x15, // manufacturer specific data - 0x03, 0x50, 0x01, 0x02, // an unknown data type won't cause trouble - }; + byte[] scanRecord = + new byte[] { + 0x02, + 0x01, + 0x1a, // advertising flags + 0x05, + 0x02, + 0x52, + 0x18, + 0x0a, + 0x11, // 16 bit service uuids + 0x04, + 0x09, + 0x50, + 0x65, + 0x64, // name + 0x02, + 0x0A, + (byte) 0xec, // tx power level + 0x05, + 0x30, + 0x54, + 0x65, + 0x73, + 0x74, // broadcast name: Test + 0x06, + 0x16, + 0x52, + 0x18, + 0x2A, + 0x00, + 0x00, // service data, broadcast id 42 + 0x08, + 0x16, + 0x56, + 0x18, + 0x07, + 0x03, + 0x06, + 0x07, + 0x08, + // service data - public broadcast, + // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 + 0x05, + (byte) 0xff, + (byte) 0xe0, + 0x00, + 0x02, + 0x15, // manufacturer specific data + 0x03, + 0x50, + 0x01, + 0x02, // an unknown data type won't cause trouble + }; ScanRecord record = ScanRecord.parseFromBytes(scanRecord); - ScanResult scanResult = new ScanResult(mAdapter.getRemoteLeDevice("00:11:22:33:44:55", - BluetoothDevice.ADDRESS_TYPE_RANDOM), 0, 0, 0, 0, 0, 0, 0, record, 0); + ScanResult scanResult = + new ScanResult( + mAdapter.getRemoteLeDevice( + "00:11:22:33:44:55", BluetoothDevice.ADDRESS_TYPE_RANDOM), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + record, + 0); when(mBassClientService.getCachedBroadcast(anyInt())).thenReturn(scanResult); - doNothing().when(mMethodProxy).periodicAdvertisingManagerRegisterSync( - any(), any(), anyInt(), anyInt(), any(), any()); + doNothing() + .when(mMethodProxy) + .periodicAdvertisingManagerRegisterSync( + any(), any(), anyInt(), anyInt(), any(), any()); // validate add source will trigger select source and update mPendingSourceToAdd mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE, metadata); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -2270,12 +2444,13 @@ public class BassClientStateMachineTest { } private void moveConnectedStateToConnectedProcessingState() { - BluetoothGattCharacteristic gattCharacteristic = Mockito.mock( - BluetoothGattCharacteristic.class); - BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock( - BassClientStateMachine.BluetoothGattTestableWrapper.class); + BluetoothGattCharacteristic gattCharacteristic = + Mockito.mock(BluetoothGattCharacteristic.class); + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; - sendMessageAndVerifyTransition(mBassClientStateMachine.obtainMessage( + sendMessageAndVerifyTransition( + mBassClientStateMachine.obtainMessage( READ_BASS_CHARACTERISTICS, gattCharacteristic), BassClientStateMachine.ConnectedProcessing.class); Mockito.clearInvocations(mBassClientService); @@ -2337,14 +2512,15 @@ public class BassClientStateMachineTest { BluetoothDevice testDevice = mAdapter.getRemoteLeDevice(testMacAddress, BluetoothDevice.ADDRESS_TYPE_RANDOM); - BluetoothLeBroadcastMetadata.Builder builder = new BluetoothLeBroadcastMetadata.Builder() - .setEncrypted(false) - .setSourceDevice(testDevice, BluetoothDevice.ADDRESS_TYPE_RANDOM) - .setSourceAdvertisingSid(testAdvertiserSid) - .setBroadcastId(testBroadcastId) - .setBroadcastCode(new byte[] { 0x00, 0x01, 0x00, 0x02 }) - .setPaSyncInterval(testPaSyncInterval) - .setPresentationDelayMicros(testPresentationDelayMs); + BluetoothLeBroadcastMetadata.Builder builder = + new BluetoothLeBroadcastMetadata.Builder() + .setEncrypted(false) + .setSourceDevice(testDevice, BluetoothDevice.ADDRESS_TYPE_RANDOM) + .setSourceAdvertisingSid(testAdvertiserSid) + .setBroadcastId(testBroadcastId) + .setBroadcastCode(new byte[] {0x00, 0x01, 0x00, 0x02}) + .setPaSyncInterval(testPaSyncInterval) + .setPresentationDelayMicros(testPresentationDelayMs); // builder expect at least one subgroup builder.addSubgroup(createBroadcastSubgroup()); return builder.build(); @@ -2362,18 +2538,23 @@ public class BassClientStateMachineTest { BluetoothLeAudioCodecConfigMetadata codecMetadata = new BluetoothLeAudioCodecConfigMetadata.Builder() - .setAudioLocation(testAudioLocationFrontLeft).build(); + .setAudioLocation(testAudioLocationFrontLeft) + .build(); BluetoothLeAudioContentMetadata contentMetadata = new BluetoothLeAudioContentMetadata.Builder() - .setProgramInfo(testProgramInfo).setLanguage(testLanguage).build(); - BluetoothLeBroadcastSubgroup.Builder builder = new BluetoothLeBroadcastSubgroup.Builder() - .setCodecId(testCodecId) - .setCodecSpecificConfig(codecMetadata) - .setContentMetadata(contentMetadata); + .setProgramInfo(testProgramInfo) + .setLanguage(testLanguage) + .build(); + BluetoothLeBroadcastSubgroup.Builder builder = + new BluetoothLeBroadcastSubgroup.Builder() + .setCodecId(testCodecId) + .setCodecSpecificConfig(codecMetadata) + .setContentMetadata(contentMetadata); BluetoothLeAudioCodecConfigMetadata channelCodecMetadata = new BluetoothLeAudioCodecConfigMetadata.Builder() - .setAudioLocation(testAudioLocationFrontRight).build(); + .setAudioLocation(testAudioLocationFrontRight) + .build(); // builder expect at least one channel BluetoothLeBroadcastChannel channel = diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java index 0f7034a0756..2921d739350 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java @@ -83,17 +83,17 @@ public class BleBroadcastAssistantBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] { STATE_DISCONNECTED }; + int[] states = new int[] {STATE_DISCONNECTED}; mBinder.getDevicesMatchingConnectionStates(states); verify(mService).getDevicesMatchingConnectionStates(states); doThrow(new RuntimeException()).when(mService).getDevicesMatchingConnectionStates(states); - assertThat(mBinder.getDevicesMatchingConnectionStates(states)).isEqualTo( - Collections.emptyList()); + assertThat(mBinder.getDevicesMatchingConnectionStates(states)) + .isEqualTo(Collections.emptyList()); mBinder.cleanup(); - assertThat(mBinder.getDevicesMatchingConnectionStates(states)).isEqualTo( - Collections.emptyList()); + assertThat(mBinder.getDevicesMatchingConnectionStates(states)) + .isEqualTo(Collections.emptyList()); } @Test @@ -114,7 +114,8 @@ public class BleBroadcastAssistantBinderTest { mBinder.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); verify(mService).setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); - doThrow(new RuntimeException()).when(mService) + doThrow(new RuntimeException()) + .when(mService) .setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); assertThat(mBinder.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED)) .isFalse(); @@ -175,7 +176,7 @@ public class BleBroadcastAssistantBinderTest { @Test public void startSearchingForSources() { - List filters = Collections.EMPTY_LIST; + List filters = Collections.EMPTY_LIST; mBinder.startSearchingForSources(filters); verify(mService).startSearchingForSources(filters); diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java index 239d68ba666..e2a5b4d4d08 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java @@ -51,9 +51,16 @@ public class PeriodicAdvertisementResultTest { int broadcastId = 5; PublicBroadcastData pbData = generatePublicBroadcastData(); String broadcastName = TEST_BROADCAST_NAME; - PeriodicAdvertisementResult result = new PeriodicAdvertisementResult( - mDevice, addressType, syncHandle, advSid, paInterval, broadcastId, - pbData, broadcastName); + PeriodicAdvertisementResult result = + new PeriodicAdvertisementResult( + mDevice, + addressType, + syncHandle, + advSid, + paInterval, + broadcastId, + pbData, + broadcastName); assertThat(result.getAddressType()).isEqualTo(addressType); assertThat(result.getSyncHandle()).isEqualTo(syncHandle); @@ -73,9 +80,16 @@ public class PeriodicAdvertisementResultTest { int broadcastId = 5; PublicBroadcastData pbData = null; String broadcastName = null; - PeriodicAdvertisementResult result = new PeriodicAdvertisementResult( - mDevice, addressType, syncHandle, advSid, paInterval, broadcastId, - pbData, broadcastName); + PeriodicAdvertisementResult result = + new PeriodicAdvertisementResult( + mDevice, + addressType, + syncHandle, + advSid, + paInterval, + broadcastId, + pbData, + broadcastName); int newAddressType = 6; result.updateAddressType(newAddressType); @@ -115,25 +129,30 @@ public class PeriodicAdvertisementResultTest { int broadcastId = 5; PublicBroadcastData pbData = generatePublicBroadcastData(); String broadcastName = TEST_BROADCAST_NAME; - PeriodicAdvertisementResult result = new PeriodicAdvertisementResult( - mDevice, addressType, syncHandle, advSid, paInterval, broadcastId, - pbData, broadcastName); + PeriodicAdvertisementResult result = + new PeriodicAdvertisementResult( + mDevice, + addressType, + syncHandle, + advSid, + paInterval, + broadcastId, + pbData, + broadcastName); result.print(); } - /** - * Helper to generate test data for public broadcast. - */ + /** Helper to generate test data for public broadcast. */ private PublicBroadcastData generatePublicBroadcastData() { PublicBroadcastData.PublicBroadcastInfo info = new PublicBroadcastData.PublicBroadcastInfo(); info.isEncrypted = true; - info.audioConfigQuality = ( - BluetoothLeBroadcastMetadata.AUDIO_CONFIG_QUALITY_STANDARD | - BluetoothLeBroadcastMetadata.AUDIO_CONFIG_QUALITY_HIGH); + info.audioConfigQuality = + (BluetoothLeBroadcastMetadata.AUDIO_CONFIG_QUALITY_STANDARD + | BluetoothLeBroadcastMetadata.AUDIO_CONFIG_QUALITY_HIGH); info.metaDataLength = 3; - info.metaData = new byte[] { 0x06, 0x07, 0x08 }; + info.metaData = new byte[] {0x06, 0x07, 0x08}; return new PublicBroadcastData(info); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java index 9a307b8704d..c9b49864631 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java @@ -39,11 +39,11 @@ public class PublicBroadcastDataTest { info.print(); info.isEncrypted = true; - info.audioConfigQuality = ( - BluetoothLeBroadcastMetadata.AUDIO_CONFIG_QUALITY_STANDARD | - BluetoothLeBroadcastMetadata.AUDIO_CONFIG_QUALITY_HIGH); + info.audioConfigQuality = + (BluetoothLeBroadcastMetadata.AUDIO_CONFIG_QUALITY_STANDARD + | BluetoothLeBroadcastMetadata.AUDIO_CONFIG_QUALITY_HIGH); info.metaDataLength = 3; - info.metaData = new byte[] { 0x06, 0x07, 0x08 }; + info.metaData = new byte[] {0x06, 0x07, 0x08}; info.print(); } @@ -51,33 +51,40 @@ public class PublicBroadcastDataTest { public void parsePublicBroadcastData() { assertThat(PublicBroadcastData.parsePublicBroadcastData(null)).isNull(); - byte[] serviceDataInvalid = new byte[] { - (byte) 0x02, // features, non-encrypted, standard quality prsent - }; + byte[] serviceDataInvalid = + new byte[] { + (byte) 0x02, // features, non-encrypted, standard quality prsent + }; assertThat(PublicBroadcastData.parsePublicBroadcastData(serviceDataInvalid)).isNull(); - byte[] serviceDataInvalid2 = new byte[] { - (byte) 0x02, // features, non-encrypted, standard quality prsent - (byte) 0x03, // metaDataLength - (byte) 0x06, (byte) 0x07, // invalid metaData - }; + byte[] serviceDataInvalid2 = + new byte[] { + (byte) 0x02, // features, non-encrypted, standard quality prsent + (byte) 0x03, // metaDataLength + (byte) 0x06, + (byte) 0x07, // invalid metaData + }; assertThat(PublicBroadcastData.parsePublicBroadcastData(serviceDataInvalid2)).isNull(); - byte[] serviceData = new byte[] { - (byte) 0x07, // features - (byte) 0x03, // metaDataLength - (byte) 0x06, (byte) 0x07, (byte) 0x08, // metaData - }; + byte[] serviceData = + new byte[] { + (byte) 0x07, // features + (byte) 0x03, // metaDataLength + (byte) 0x06, + (byte) 0x07, + (byte) 0x08, // metaData + }; PublicBroadcastData data = PublicBroadcastData.parsePublicBroadcastData(serviceData); assertThat(data.isEncrypted()).isTrue(); assertThat(data.getAudioConfigQuality()).isEqualTo(3); assertThat(data.getMetadataLength()).isEqualTo(3); - assertThat(data.getMetadata()).isEqualTo(new byte[] { 0x06, 0x07, 0x08 }); + assertThat(data.getMetadata()).isEqualTo(new byte[] {0x06, 0x07, 0x08}); - byte[] serviceDataNoMetaData = new byte[] { - (byte) 0x02, // features, non-encrypted, standard quality prsent - (byte) 0x00, // metaDataLength - }; + byte[] serviceDataNoMetaData = + new byte[] { + (byte) 0x02, // features, non-encrypted, standard quality prsent + (byte) 0x00, // metaDataLength + }; PublicBroadcastData dataNoMetaData = PublicBroadcastData.parsePublicBroadcastData(serviceDataNoMetaData); assertThat(dataNoMetaData.isEncrypted()).isFalse(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java index a83e4bf7e5b..c0f0c2f2dd7 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java @@ -152,8 +152,8 @@ public class ActiveDeviceManagerTest { mOriginalDualModeAudioState = Utils.isDualModeAudioEnabled(); when(mA2dpService.setActiveDevice(any())).thenReturn(true); - when(mHeadsetService.getHfpCallAudioPolicy(any())).thenReturn( - new BluetoothSinkAudioPolicy.Builder().build()); + when(mHeadsetService.getHfpCallAudioPolicy(any())) + .thenReturn(new BluetoothSinkAudioPolicy.Builder().build()); when(mHeadsetService.setActiveDevice(any())).thenReturn(true); when(mHearingAidService.setActiveDevice(any())).thenReturn(true); when(mLeAudioService.setActiveDevice(any())).thenReturn(true); @@ -171,20 +171,30 @@ public class ActiveDeviceManagerTest { when(mHearingAidService.getConnectedPeerDevices(mHearingAidHiSyncId)) .thenReturn(connectedHearingAidDevices); - when(mA2dpService.getFallbackDevice()).thenAnswer(invocation -> { - if (!mDeviceConnectionStack.isEmpty() && Objects.equals(mA2dpDevice, - mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1))) { - return mA2dpDevice; - } - return null; - }); - when(mHeadsetService.getFallbackDevice()).thenAnswer(invocation -> { - if (!mDeviceConnectionStack.isEmpty() && Objects.equals(mHeadsetDevice, - mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1))) { - return mHeadsetDevice; - } - return null; - }); + when(mA2dpService.getFallbackDevice()) + .thenAnswer( + invocation -> { + if (!mDeviceConnectionStack.isEmpty() + && Objects.equals( + mA2dpDevice, + mDeviceConnectionStack.get( + mDeviceConnectionStack.size() - 1))) { + return mA2dpDevice; + } + return null; + }); + when(mHeadsetService.getFallbackDevice()) + .thenAnswer( + invocation -> { + if (!mDeviceConnectionStack.isEmpty() + && Objects.equals( + mHeadsetDevice, + mDeviceConnectionStack.get( + mDeviceConnectionStack.size() - 1))) { + return mHeadsetDevice; + } + return null; + }); } @After @@ -201,9 +211,7 @@ public class ActiveDeviceManagerTest { @Test public void testSetUpAndTearDown() {} - /** - * One A2DP is connected. - */ + /** One A2DP is connected. */ @Test public void onlyA2dpConnected_setA2dpActive() { a2dpConnected(mA2dpDevice, false); @@ -233,9 +241,7 @@ public class ActiveDeviceManagerTest { verify(mHeadsetService).setActiveDevice(mA2dpHeadsetDevice); } - /** - * Two A2DP are connected. Should set the second one active. - */ + /** Two A2DP are connected. Should set the second one active. */ @Test public void secondA2dpConnected_setSecondA2dpActive() { a2dpConnected(mA2dpDevice, false); @@ -245,9 +251,7 @@ public class ActiveDeviceManagerTest { verify(mA2dpService, timeout(TIMEOUT_MS)).setActiveDevice(mSecondaryAudioDevice); } - /** - * One A2DP is connected and disconnected later. Should then set active device to null. - */ + /** One A2DP is connected and disconnected later. Should then set active device to null. */ @Test public void lastA2dpDisconnected_clearA2dpActive() { a2dpConnected(mA2dpDevice, false); @@ -257,9 +261,7 @@ public class ActiveDeviceManagerTest { verify(mA2dpService, timeout(TIMEOUT_MS)).removeActiveDevice(true); } - /** - * Two A2DP are connected and active device is explicitly set. - */ + /** Two A2DP are connected and active device is explicitly set. */ @Test public void a2dpActiveDeviceSelected_setActive() { a2dpConnected(mA2dpDevice, false); @@ -276,8 +278,8 @@ public class ActiveDeviceManagerTest { } /** - * Two A2DP devices are connected and the current active is then disconnected. - * Should then set active device to fallback device. + * Two A2DP devices are connected and the current active is then disconnected. Should then set + * active device to fallback device. */ @Test public void a2dpSecondDeviceDisconnected_fallbackDeviceActive() { @@ -292,18 +294,14 @@ public class ActiveDeviceManagerTest { verify(mA2dpService, timeout(TIMEOUT_MS)).setActiveDevice(mA2dpDevice); } - /** - * One Headset is connected. - */ + /** One Headset is connected. */ @Test public void onlyHeadsetConnected_setHeadsetActive() { headsetConnected(mHeadsetDevice, false); verify(mHeadsetService, timeout(TIMEOUT_MS)).setActiveDevice(mHeadsetDevice); } - /** - * Two Headset are connected. Should set the second one active. - */ + /** Two Headset are connected. Should set the second one active. */ @Test public void secondHeadsetConnected_setSecondHeadsetActive() { headsetConnected(mHeadsetDevice, false); @@ -313,9 +311,7 @@ public class ActiveDeviceManagerTest { verify(mHeadsetService, timeout(TIMEOUT_MS)).setActiveDevice(mSecondaryAudioDevice); } - /** - * One Headset is connected and disconnected later. Should then set active device to null. - */ + /** One Headset is connected and disconnected later. Should then set active device to null. */ @Test public void lastHeadsetDisconnected_clearHeadsetActive() { headsetConnected(mHeadsetDevice, false); @@ -325,9 +321,7 @@ public class ActiveDeviceManagerTest { verify(mHeadsetService, timeout(TIMEOUT_MS)).setActiveDevice(isNull()); } - /** - * Two Headset are connected and active device is explicitly set. - */ + /** Two Headset are connected and active device is explicitly set. */ @Test public void headsetActiveDeviceSelected_setActive() { headsetConnected(mHeadsetDevice, false); @@ -344,8 +338,8 @@ public class ActiveDeviceManagerTest { } /** - * Two Headsets are connected and the current active is then disconnected. - * Should then set active device to fallback device. + * Two Headsets are connected and the current active is then disconnected. Should then set + * active device to fallback device. */ @Test public void headsetSecondDeviceDisconnected_fallbackDeviceActive() { @@ -576,19 +570,18 @@ public class ActiveDeviceManagerTest { verify(mHeadsetService, never()).setActiveDevice(any()); } - /** - * A headset device with connecting audio policy set to NOT ALLOWED. - */ + /** A headset device with connecting audio policy set to NOT ALLOWED. */ @Test public void notAllowedConnectingPolicyHeadsetConnected_noSetActiveDevice() { // setting connecting policy to NOT ALLOWED when(mHeadsetService.getHfpCallAudioPolicy(mHeadsetDevice)) - .thenReturn(new BluetoothSinkAudioPolicy.Builder() - .setCallEstablishPolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .setActiveDevicePolicyAfterConnection( - BluetoothSinkAudioPolicy.POLICY_NOT_ALLOWED) - .setInBandRingtonePolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .build()); + .thenReturn( + new BluetoothSinkAudioPolicy.Builder() + .setCallEstablishPolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .setActiveDevicePolicyAfterConnection( + BluetoothSinkAudioPolicy.POLICY_NOT_ALLOWED) + .setInBandRingtonePolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .build()); headsetConnected(mHeadsetDevice, false); verify(mHeadsetService, never()).setActiveDevice(mHeadsetDevice); @@ -596,14 +589,13 @@ public class ActiveDeviceManagerTest { @Test public void twoHearingAidDevicesConnected_WithTheSameHiSyncId() { - Assume.assumeTrue("Ignore test when HearingAidService is not enabled", - HearingAidService.isEnabled()); + Assume.assumeTrue( + "Ignore test when HearingAidService is not enabled", HearingAidService.isEnabled()); List connectedHearingAidDevices = new ArrayList<>(); connectedHearingAidDevices.add(mHearingAidDevice); connectedHearingAidDevices.add(mSecondaryAudioDevice); - when(mHearingAidService.getHiSyncId(mSecondaryAudioDevice)) - .thenReturn(mHearingAidHiSyncId); + when(mHearingAidService.getHiSyncId(mSecondaryAudioDevice)).thenReturn(mHearingAidHiSyncId); when(mHearingAidService.getConnectedPeerDevices(mHearingAidHiSyncId)) .thenReturn(connectedHearingAidDevices); @@ -613,9 +605,7 @@ public class ActiveDeviceManagerTest { verify(mHearingAidService, never()).setActiveDevice(mSecondaryAudioDevice); } - /** - * A combo (A2DP + Headset) device is connected. Then a Hearing Aid is connected. - */ + /** A combo (A2DP + Headset) device is connected. Then a Hearing Aid is connected. */ @Test public void hearingAidActive_clearA2dpAndHeadsetActive() { a2dpConnected(mA2dpHeadsetDevice, true); @@ -629,9 +619,7 @@ public class ActiveDeviceManagerTest { verify(mHeadsetService, timeout(TIMEOUT_MS)).setActiveDevice(null); } - /** - * A Hearing Aid is connected. Then a combo (A2DP + Headset) device is connected. - */ + /** A Hearing Aid is connected. Then a combo (A2DP + Headset) device is connected. */ @Test public void hearingAidActive_dontSetA2dpAndHeadsetActive() { hearingAidActiveDeviceChanged(mHearingAidDevice); @@ -643,9 +631,7 @@ public class ActiveDeviceManagerTest { verify(mHeadsetService, never()).setActiveDevice(mA2dpHeadsetDevice); } - /** - * A Hearing Aid is connected. Then an A2DP active device is explicitly set. - */ + /** A Hearing Aid is connected. Then an A2DP active device is explicitly set. */ @Test public void hearingAidActive_setA2dpActiveExplicitly() { when(mHearingAidService.removeActiveDevice(anyBoolean())).thenReturn(true); @@ -662,9 +648,7 @@ public class ActiveDeviceManagerTest { Assert.assertTrue(mActiveDeviceManager.getHearingAidActiveDevices().isEmpty()); } - /** - * A Hearing Aid is connected. Then a Headset active device is explicitly set. - */ + /** A Hearing Aid is connected. Then a Headset active device is explicitly set. */ @Test public void hearingAidActive_setHeadsetActiveExplicitly() { when(mHearingAidService.removeActiveDevice(anyBoolean())).thenReturn(true); @@ -688,9 +672,7 @@ public class ActiveDeviceManagerTest { assertThat(mActiveDeviceManager.getHearingAidActiveDevices()).isEmpty(); } - /** - * One LE Audio is connected. - */ + /** One LE Audio is connected. */ @Test public void onlyLeAudioConnected_setHeadsetActive() { when(mLeAudioService.isGroupAvailableForStream(anyInt())).thenReturn(true); @@ -706,9 +688,7 @@ public class ActiveDeviceManagerTest { verify(mLeAudioService, never()).setActiveDevice(mLeAudioDevice); } - /** - * Two LE Audio are connected. Should set the second one active. - */ + /** Two LE Audio are connected. Should set the second one active. */ @Test public void secondLeAudioConnected_setSecondLeAudioActive() { when(mLeAudioService.isGroupAvailableForStream(anyInt())).thenReturn(true); @@ -719,9 +699,7 @@ public class ActiveDeviceManagerTest { verify(mLeAudioService, timeout(TIMEOUT_MS)).setActiveDevice(mSecondaryAudioDevice); } - /** - * One LE Audio is connected and disconnected later. Should then set active device to null. - */ + /** One LE Audio is connected and disconnected later. Should then set active device to null. */ @Test public void lastLeAudioDisconnected_clearLeAudioActive() { when(mLeAudioService.isGroupAvailableForStream(anyInt())).thenReturn(true); @@ -732,9 +710,7 @@ public class ActiveDeviceManagerTest { verify(mLeAudioService, timeout(TIMEOUT_MS)).removeActiveDevice(false); } - /** - * Two LE Audio are connected and active device is explicitly set. - */ + /** Two LE Audio are connected and active device is explicitly set. */ @Test public void leAudioActiveDeviceSelected_setActive() { when(mLeAudioService.isGroupAvailableForStream(anyInt())).thenReturn(true); @@ -753,8 +729,8 @@ public class ActiveDeviceManagerTest { } /** - * Two LE Audio are connected and the current active is then disconnected. - * Should then set active device to fallback device. + * Two LE Audio are connected and the current active is then disconnected. Should then set + * active device to fallback device. */ @Test public void leAudioSecondDeviceDisconnected_fallbackDeviceActive() { @@ -769,9 +745,7 @@ public class ActiveDeviceManagerTest { verify(mLeAudioService, timeout(TIMEOUT_MS)).setActiveDevice(mLeAudioDevice); } - /** - * A combo (A2DP + Headset) device is connected. Then an LE Audio is connected. - */ + /** A combo (A2DP + Headset) device is connected. Then an LE Audio is connected. */ @Test public void leAudioActive_clearA2dpAndHeadsetActive() { a2dpConnected(mA2dpHeadsetDevice, true); @@ -785,9 +759,7 @@ public class ActiveDeviceManagerTest { verify(mHeadsetService, timeout(TIMEOUT_MS)).setActiveDevice(isNull()); } - /** - * An LE Audio is connected. Then a combo (A2DP + Headset) device is connected. - */ + /** An LE Audio is connected. Then a combo (A2DP + Headset) device is connected. */ @Test public void leAudioActive_setA2dpAndHeadsetActive() { leAudioActiveDeviceChanged(mLeAudioDevice); @@ -799,9 +771,7 @@ public class ActiveDeviceManagerTest { verify(mHeadsetService, atLeastOnce()).setActiveDevice(mA2dpHeadsetDevice); } - /** - * An LE Audio is connected. Then an A2DP active device is explicitly set. - */ + /** An LE Audio is connected. Then an A2DP active device is explicitly set. */ @Test public void leAudioActive_setA2dpActiveExplicitly() { leAudioActiveDeviceChanged(mLeAudioDevice); @@ -815,9 +785,7 @@ public class ActiveDeviceManagerTest { Assert.assertNull(mActiveDeviceManager.getLeAudioActiveDevice()); } - /** - * An LE Audio is connected. Then a Headset active device is explicitly set. - */ + /** An LE Audio is connected. Then a Headset active device is explicitly set. */ @Test public void leAudioActive_setHeadsetActiveExplicitly() { leAudioActiveDeviceChanged(mLeAudioDevice); @@ -832,8 +800,8 @@ public class ActiveDeviceManagerTest { } /** - * An LE Audio connected. An A2DP connected. The A2DP disconnected. - * Then the LE Audio should be the active one. + * An LE Audio connected. An A2DP connected. The A2DP disconnected. Then the LE Audio should be + * the active one. */ @Test public void leAudioAndA2dpConnectedThenA2dpDisconnected_fallbackToLeAudio() { @@ -852,8 +820,8 @@ public class ActiveDeviceManagerTest { } /** - * An LE Audio set connected. The not active bud disconnected. - * Then the active device should not change and hasFallback should be set to false. + * An LE Audio set connected. The not active bud disconnected. Then the active device should not + * change and hasFallback should be set to false. */ @Test public void leAudioSetConnectedThenNotActiveOneDisconnected_noFallback() { @@ -876,9 +844,9 @@ public class ActiveDeviceManagerTest { } /** - * An LE Audio set connected. The active bud disconnected. Set active device - * returns false indicating an issue (the other bud is also disconnected). - * Then the active device should be removed and hasFallback should be set to false. + * An LE Audio set connected. The active bud disconnected. Set active device returns false + * indicating an issue (the other bud is also disconnected). Then the active device should be + * removed and hasFallback should be set to false. */ @Test public void leAudioSetConnectedThenActiveOneDisconnected_noFallback() { @@ -904,9 +872,9 @@ public class ActiveDeviceManagerTest { } /** - * An LE Audio set connected. The active bud disconnected. Set active device - * returns true indicating the other bud is going to be the active device. - * Then the active device should change and hasFallback should be set to true. + * An LE Audio set connected. The active bud disconnected. Set active device returns true + * indicating the other bud is going to be the active device. Then the active device should + * change and hasFallback should be set to true. */ @Test public void leAudioSetConnectedThenActiveOneDisconnected_hasFallback() { @@ -959,8 +927,8 @@ public class ActiveDeviceManagerTest { } /** - * An A2DP connected. An LE Audio connected. The LE Audio disconnected. - * Then the A2DP should be the active one. + * An A2DP connected. An LE Audio connected. The LE Audio disconnected. Then the A2DP should be + * the active one. */ @Test public void a2dpAndLeAudioConnectedThenLeAudioDisconnected_fallbackToA2dp() { @@ -981,8 +949,8 @@ public class ActiveDeviceManagerTest { } /** - * Two Hearing Aid are connected and the current active is then disconnected. - * Should then set active device to fallback device. + * Two Hearing Aid are connected and the current active is then disconnected. Should then set + * active device to fallback device. */ @Test public void hearingAidSecondDeviceDisconnected_fallbackDeviceActive() { @@ -1005,8 +973,8 @@ public class ActiveDeviceManagerTest { } /** - * Hearing aid is connected, but active device is different BT. - * When the active device is disconnected, the hearing aid should be the active one. + * Hearing aid is connected, but active device is different BT. When the active device is + * disconnected, the hearing aid should be the active one. */ @Test public void activeDeviceDisconnected_fallbackToHearingAid() { @@ -1032,13 +1000,10 @@ public class ActiveDeviceManagerTest { a2dpDisconnected(mA2dpDevice); verify(mA2dpService, timeout(TIMEOUT_MS).atLeast(1)).removeActiveDevice(false); - verify(mHearingAidService, timeout(TIMEOUT_MS).times(2)) - .setActiveDevice(mHearingAidDevice); + verify(mHearingAidService, timeout(TIMEOUT_MS).times(2)).setActiveDevice(mHearingAidDevice); } - /** - * One LE Hearing Aid is connected. - */ + /** One LE Hearing Aid is connected. */ @Test public void onlyLeHearingAidConnected_setLeAudioActive() { leHearingAidConnected(mLeHearingAidDevice); @@ -1052,10 +1017,7 @@ public class ActiveDeviceManagerTest { verify(mLeAudioService, timeout(TIMEOUT_MS)).setActiveDevice(mLeHearingAidDevice); } - /** - * LE audio is connected after LE Hearing Aid device. - * Keep LE hearing Aid active. - */ + /** LE audio is connected after LE Hearing Aid device. Keep LE hearing Aid active. */ @Test public void leAudioConnectedAfterLeHearingAid_setLeAudioActiveShouldNotBeCalled() { leHearingAidConnected(mLeHearingAidDevice); @@ -1071,9 +1033,8 @@ public class ActiveDeviceManagerTest { } /** - * Test connect/disconnect of devices. - * Hearing Aid, LE Hearing Aid, A2DP connected, then LE hearing Aid and hearing aid - * disconnected. + * Test connect/disconnect of devices. Hearing Aid, LE Hearing Aid, A2DP connected, then LE + * hearing Aid and hearing aid disconnected. */ @Test public void activeDeviceChange_withHearingAidLeHearingAidAndA2dpDevices() { @@ -1186,8 +1147,8 @@ public class ActiveDeviceManagerTest { } /** - * Verifies that other profiles do not have their active device cleared when we fail to make - * a newly connected device active. + * Verifies that other profiles do not have their active device cleared when we fail to make a + * newly connected device active. */ @Test public void setActiveDeviceFailsUponConnection() { @@ -1242,9 +1203,7 @@ public class ActiveDeviceManagerTest { verify(mHearingAidService, times(1)).removeActiveDevice(anyBoolean()); } - /** - * A wired audio device is connected. Then all active devices are set to null. - */ + /** A wired audio device is connected. Then all active devices are set to null. */ @Test public void wiredAudioDeviceConnected_setAllActiveDevicesNull() { a2dpConnected(mA2dpDevice, false); @@ -1315,9 +1274,7 @@ public class ActiveDeviceManagerTest { verify(mLeAudioService, never()).setActiveDevice(any()); } - /** - * Helper to indicate A2dp connected for a device. - */ + /** Helper to indicate A2dp connected for a device. */ private void a2dpConnected(BluetoothDevice device, boolean supportHfp) { mDatabaseManager.setProfileConnectionPolicy( device, @@ -1336,13 +1293,13 @@ public class ActiveDeviceManagerTest { BluetoothProfile.STATE_CONNECTED); } - /** - * Helper to indicate A2dp disconnected for a device. - */ + /** Helper to indicate A2dp disconnected for a device. */ private void a2dpDisconnected(BluetoothDevice device) { mDeviceConnectionStack.remove(device); - mMostRecentDevice = (mDeviceConnectionStack.size() > 0) - ? mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1) : null; + mMostRecentDevice = + (mDeviceConnectionStack.size() > 0) + ? mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1) + : null; mActiveDeviceManager.profileConnectionStateChanged( BluetoothProfile.A2DP, @@ -1403,9 +1360,7 @@ public class ActiveDeviceManagerTest { mActiveDeviceManager.profileActiveDeviceChanged(BluetoothProfile.HEADSET, device); } - /** - * Helper to indicate Hearing Aid connected for a device. - */ + /** Helper to indicate Hearing Aid connected for a device. */ private void hearingAidConnected(BluetoothDevice device) { mDeviceConnectionStack.add(device); mMostRecentDevice = device; @@ -1417,13 +1372,13 @@ public class ActiveDeviceManagerTest { BluetoothProfile.STATE_CONNECTED); } - /** - * Helper to indicate Hearing Aid disconnected for a device. - */ + /** Helper to indicate Hearing Aid disconnected for a device. */ private void hearingAidDisconnected(BluetoothDevice device) { mDeviceConnectionStack.remove(device); - mMostRecentDevice = (mDeviceConnectionStack.size() > 0) - ? mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1) : null; + mMostRecentDevice = + (mDeviceConnectionStack.size() > 0) + ? mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1) + : null; mActiveDeviceManager.profileConnectionStateChanged( BluetoothProfile.HEARING_AID, @@ -1432,9 +1387,7 @@ public class ActiveDeviceManagerTest { BluetoothProfile.STATE_DISCONNECTED); } - /** - * Helper to indicate Hearing Aid active device changed for a device. - */ + /** Helper to indicate Hearing Aid active device changed for a device. */ private void hearingAidActiveDeviceChanged(BluetoothDevice device) { mDeviceConnectionStack.remove(device); mDeviceConnectionStack.add(device); @@ -1443,9 +1396,7 @@ public class ActiveDeviceManagerTest { mActiveDeviceManager.profileActiveDeviceChanged(BluetoothProfile.HEARING_AID, device); } - /** - * Helper to indicate LE Audio connected for a device. - */ + /** Helper to indicate LE Audio connected for a device. */ private void leAudioConnected(BluetoothDevice device) { mMostRecentDevice = device; @@ -1456,13 +1407,13 @@ public class ActiveDeviceManagerTest { BluetoothProfile.STATE_CONNECTED); } - /** - * Helper to indicate LE Audio disconnected for a device. - */ + /** Helper to indicate LE Audio disconnected for a device. */ private void leAudioDisconnected(BluetoothDevice device) { mDeviceConnectionStack.remove(device); - mMostRecentDevice = (mDeviceConnectionStack.size() > 0) - ? mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1) : null; + mMostRecentDevice = + (mDeviceConnectionStack.size() > 0) + ? mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1) + : null; mActiveDeviceManager.profileConnectionStateChanged( BluetoothProfile.LE_AUDIO, @@ -1471,9 +1422,7 @@ public class ActiveDeviceManagerTest { BluetoothProfile.STATE_DISCONNECTED); } - /** - * Helper to indicate LE Audio active device changed for a device. - */ + /** Helper to indicate LE Audio active device changed for a device. */ private void leAudioActiveDeviceChanged(BluetoothDevice device) { mDeviceConnectionStack.remove(device); mDeviceConnectionStack.add(device); @@ -1482,9 +1431,7 @@ public class ActiveDeviceManagerTest { mActiveDeviceManager.profileActiveDeviceChanged(BluetoothProfile.LE_AUDIO, device); } - /** - * Helper to indicate LE Hearing Aid connected for a device. - */ + /** Helper to indicate LE Hearing Aid connected for a device. */ private void leHearingAidConnected(BluetoothDevice device) { mDeviceConnectionStack.add(device); mMostRecentDevice = device; @@ -1499,8 +1446,10 @@ public class ActiveDeviceManagerTest { /** Helper to indicate LE Hearing Aid disconnected for a device. */ private void leHearingAidDisconnected(BluetoothDevice device) { mDeviceConnectionStack.remove(device); - mMostRecentDevice = (mDeviceConnectionStack.size() > 0) - ? mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1) : null; + mMostRecentDevice = + (mDeviceConnectionStack.size() > 0) + ? mDeviceConnectionStack.get(mDeviceConnectionStack.size() - 1) + : null; mActiveDeviceManager.profileConnectionStateChanged( BluetoothProfile.HAP_CLIENT, diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceBinderTest.java index d98ee994177..02dd5930e4a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceBinderTest.java @@ -70,7 +70,7 @@ public class AdapterServiceBinderTest { @Test public void dump() { FileDescriptor fd = new FileDescriptor(); - String[] args = new String[] { }; + String[] args = new String[] {}; mBinder.dump(fd, args); verify(mService).dump(any(), any(), any()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceRestartTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceRestartTest.java index 93a6688fe46..35fd88ac562 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceRestartTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceRestartTest.java @@ -148,12 +148,14 @@ public class AdapterServiceRestartTest { Context targetContext = InstrumentationRegistry.getTargetContext(); mMockContentResolver = new MockContentResolver(targetContext); - mMockContentResolver.addProvider(Settings.AUTHORITY, new MockContentProvider() { - @Override - public Bundle call(String method, String request, Bundle args) { - return Bundle.EMPTY; - } - }); + mMockContentResolver.addProvider( + Settings.AUTHORITY, + new MockContentProvider() { + @Override + public Bundle call(String method, String request, Bundle args) { + return Bundle.EMPTY; + } + }); mPowerManager = targetContext.getSystemService(PowerManager.class); mPermissionCheckerManager = targetContext.getSystemService(PermissionCheckerManager.class); @@ -170,8 +172,8 @@ public class AdapterServiceRestartTest { when(mMockContext.getApplicationInfo()).thenReturn(mMockApplicationInfo); when(mMockContext.getContentResolver()).thenReturn(mMockContentResolver); when(mMockContext.getApplicationContext()).thenReturn(mMockContext); - when(mMockContext.createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0)).thenReturn( - mMockContext); + when(mMockContext.createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0)) + .thenReturn(mMockContext); when(mMockContext.getResources()).thenReturn(mMockResources); when(mMockContext.getUserId()).thenReturn(Process.BLUETOOTH_UID); when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); @@ -204,10 +206,10 @@ public class AdapterServiceRestartTest { "AdapterServiceTestPrefs", Context.MODE_PRIVATE)); doAnswer( - invocation -> { - Object[] args = invocation.getArguments(); - return targetContext.getDatabasePath((String) args[0]); - }) + invocation -> { + Object[] args = invocation.getArguments(); + return targetContext.getDatabasePath((String) args[0]); + }) .when(mMockContext) .getDatabasePath(anyString()); @@ -221,7 +223,8 @@ public class AdapterServiceRestartTest { when(mIBluetoothCallback.asBinder()).thenReturn(mBinder); - doReturn(Process.BLUETOOTH_UID).when(mMockPackageManager) + doReturn(Process.BLUETOOTH_UID) + .when(mMockPackageManager) .getPackageUidAsUser(any(), anyInt(), anyInt()); when(mMockMetricsLogger.init(any())).thenReturn(true); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java index 78d69150547..28b3294a726 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java @@ -181,7 +181,6 @@ public class AdapterServiceTest { private static final int NATIVE_INIT_MS = 8000; private static final int NATIVE_DISABLE_MS = 8000; - private PackageManager mMockPackageManager; private MockContentResolver mMockContentResolver; private int mForegroundUserId; @@ -248,12 +247,14 @@ public class AdapterServiceTest { Context targetContext = InstrumentationRegistry.getTargetContext(); mMockContentResolver = new MockContentResolver(targetContext); - mMockContentResolver.addProvider(Settings.AUTHORITY, new MockContentProvider() { - @Override - public Bundle call(String method, String request, Bundle args) { - return Bundle.EMPTY; - } - }); + mMockContentResolver.addProvider( + Settings.AUTHORITY, + new MockContentProvider() { + @Override + public Bundle call(String method, String request, Bundle args) { + return Bundle.EMPTY; + } + }); mBluetoothManager = targetContext.getSystemService(BluetoothManager.class); mCompanionDeviceManager = targetContext.getSystemService(CompanionDeviceManager.class); @@ -268,8 +269,8 @@ public class AdapterServiceTest { when(mMockContext.getApplicationInfo()).thenReturn(mMockApplicationInfo); when(mMockContext.getContentResolver()).thenReturn(mMockContentResolver); when(mMockContext.getApplicationContext()).thenReturn(mMockContext); - when(mMockContext.createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0)).thenReturn( - mMockContext); + when(mMockContext.createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0)) + .thenReturn(mMockContext); when(mMockContext.getResources()).thenReturn(mMockResources); when(mMockContext.getUserId()).thenReturn(Process.BLUETOOTH_UID); when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); @@ -304,10 +305,10 @@ public class AdapterServiceTest { "AdapterServiceTestPrefs", Context.MODE_PRIVATE)); doAnswer( - invocation -> { - Object[] args = invocation.getArguments(); - return targetContext.getDatabasePath((String) args[0]); - }) + invocation -> { + Object[] args = invocation.getArguments(); + return targetContext.getDatabasePath((String) args[0]); + }) .when(mMockContext) .getDatabasePath(anyString()); @@ -319,7 +320,8 @@ public class AdapterServiceTest { when(mIBluetoothCallback.asBinder()).thenReturn(mBinder); - doReturn(Process.BLUETOOTH_UID).when(mMockPackageManager) + doReturn(Process.BLUETOOTH_UID) + .when(mMockPackageManager) .getPackageUidAsUser(any(), anyInt(), anyInt()); when(mMockGattService.getName()).thenReturn("GattService"); @@ -573,10 +575,7 @@ public class AdapterServiceTest { Log.e(TAG, "doDisable() complete success"); } - /** - * Test: Turn Bluetooth on. - * Check whether the AdapterService gets started. - */ + /** Test: Turn Bluetooth on. Check whether the AdapterService gets started. */ @Test public void testEnable() { doEnable(false); @@ -598,10 +597,7 @@ public class AdapterServiceTest { assertThat(mAdapterService.getScanMode()).isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE); } - /** - * Test: Turn Bluetooth on/off. - * Check whether the AdapterService gets started and stopped. - */ + /** Test: Turn Bluetooth on/off. Check whether the AdapterService gets started and stopped. */ @Test public void testEnableDisable() { doEnable(false); @@ -609,8 +605,8 @@ public class AdapterServiceTest { } /** - * Test: Turn Bluetooth on/off with only GATT supported. - * Check whether the AdapterService gets started and stopped. + * Test: Turn Bluetooth on/off with only GATT supported. Check whether the AdapterService gets + * started and stopped. */ @Test public void testEnableDisableOnlyGatt() { @@ -633,10 +629,7 @@ public class AdapterServiceTest { doDisable(true); } - /** - * Test: Don't start GATT - * Check whether the AdapterService quits gracefully - */ + /** Test: Don't start GATT Check whether the AdapterService quits gracefully */ @Test public void testGattStartTimeout() { assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF); @@ -671,10 +664,7 @@ public class AdapterServiceTest { assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF); } - /** - * Test: Don't stop GATT - * Check whether the AdapterService quits gracefully - */ + /** Test: Don't stop GATT Check whether the AdapterService quits gracefully */ @Test public void testGattStopTimeout() { doEnable(false); @@ -841,10 +831,7 @@ public class AdapterServiceTest { mAdapterService.unregisterRemoteCallback(callback); } - /** - * Test: Don't start a classic profile - * Check whether the AdapterService quits gracefully - */ + /** Test: Don't start a classic profile Check whether the AdapterService quits gracefully */ @Test public void testProfileStartTimeout() { assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF); @@ -922,15 +909,12 @@ public class AdapterServiceTest { assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF); } - /** - * Test: Toggle snoop logging setting - * Check whether the AdapterService restarts fully - */ + /** Test: Toggle snoop logging setting Check whether the AdapterService restarts fully */ @Test public void testSnoopLoggingChange() { BluetoothProperties.snoop_log_mode_values snoopSetting = BluetoothProperties.snoop_log_mode() - .orElse(BluetoothProperties.snoop_log_mode_values.EMPTY); + .orElse(BluetoothProperties.snoop_log_mode_values.EMPTY); BluetoothProperties.snoop_log_mode(BluetoothProperties.snoop_log_mode_values.DISABLED); doEnable(false); @@ -974,11 +958,10 @@ public class AdapterServiceTest { BluetoothProperties.snoop_log_mode(snoopSetting); } - /** - * Test: Obfuscate a null Bluetooth - * Check if returned value from {@link AdapterService#obfuscateAddress(BluetoothDevice)} is - * an empty array when device address is null + * Test: Obfuscate a null Bluetooth Check if returned value from {@link + * AdapterService#obfuscateAddress(BluetoothDevice)} is an empty array when device address is + * null */ @Test public void testObfuscateBluetoothAddress_NullAddress() { @@ -1069,7 +1052,8 @@ public class AdapterServiceTest { } // Trigger address consolidate callback - remoteDevices.addressConsolidateCallback(Utils.getBytesFromAddress(TEST_BT_ADDR_1), + remoteDevices.addressConsolidateCallback( + Utils.getBytesFromAddress(TEST_BT_ADDR_1), Utils.getBytesFromAddress(TEST_BT_ADDR_2)); // Verify we can get correct identity address @@ -1127,9 +1111,8 @@ public class AdapterServiceTest { } /** - * Test: Get id for null address - * Check if returned value from {@link AdapterService#getMetricId(BluetoothDevice)} is - * 0 when device address is null + * Test: Get id for null address Check if returned value from {@link + * AdapterService#getMetricId(BluetoothDevice)} is 0 when device address is null */ @Test public void testGetMetricId_NullAddress() { @@ -1183,8 +1166,8 @@ public class AdapterServiceTest { FileDescriptor fd = new FileDescriptor(); PrintWriter writer = mock(PrintWriter.class); - mAdapterService.dump(fd, writer, new String[]{}); - mAdapterService.dump(fd, writer, new String[]{"set-test-mode", "enabled"}); + mAdapterService.dump(fd, writer, new String[] {}); + mAdapterService.dump(fd, writer, new String[] {"set-test-mode", "enabled"}); doReturn(new byte[0]).when(mNativeInterface).dumpMetrics(); mAdapterService.dump(fd, writer, new String[] {"--proto-bin"}); mAdapterService.dump(fd, writer, new String[] {"random", "arguments"}); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/BondStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/BondStateMachineTest.java index 0e779facba9..e3a2f9d91af 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/BondStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/BondStateMachineTest.java @@ -59,8 +59,9 @@ public class BondStateMachineTest { BluetoothDevice.DEVICE_TYPE_DUAL, BluetoothDevice.DEVICE_TYPE_LE }; - private static final ParcelUuid[] TEST_UUIDS = - {ParcelUuid.fromString("0000111E-0000-1000-8000-00805F9B34FB")}; + private static final ParcelUuid[] TEST_UUIDS = { + ParcelUuid.fromString("0000111E-0000-1000-8000-00805F9B34FB") + }; private static final int BOND_NONE = BluetoothDevice.BOND_NONE; private static final int BOND_BONDING = BluetoothDevice.BOND_BONDING; @@ -97,12 +98,11 @@ public class BondStateMachineTest { mRemoteDevices = new RemoteDevices(mAdapterService, mHandlerThread.getLooper()); mRemoteDevices.reset(); - when(mAdapterService.getResources()).thenReturn( - mTargetContext.getResources()); + when(mAdapterService.getResources()).thenReturn(mTargetContext.getResources()); mAdapterProperties = new AdapterProperties(mAdapterService); mAdapterProperties.init(mRemoteDevices); - mBondStateMachine = BondStateMachine.make(mAdapterService, mAdapterProperties, - mRemoteDevices); + mBondStateMachine = + BondStateMachine.make(mAdapterService, mAdapterProperties, mRemoteDevices); } @After @@ -142,11 +142,11 @@ public class BondStateMachineTest { verify(mNativeInterface, times(1)).removeBond(eq(TEST_BT_ADDR_BYTES)); verify(mNativeInterface, times(1)).removeBond(eq(TEST_BT_ADDR_BYTES_2)); - mBondStateMachine.bondStateChangeCallback(AbstractionLayer.BT_STATUS_SUCCESS, - TEST_BT_ADDR_BYTES, BOND_NONE, 0); + mBondStateMachine.bondStateChangeCallback( + AbstractionLayer.BT_STATUS_SUCCESS, TEST_BT_ADDR_BYTES, BOND_NONE, 0); TestUtils.waitForLooperToFinishScheduledTask(mBondStateMachine.getHandler().getLooper()); - mBondStateMachine.bondStateChangeCallback(AbstractionLayer.BT_STATUS_SUCCESS, - TEST_BT_ADDR_BYTES_2, BOND_NONE, 0); + mBondStateMachine.bondStateChangeCallback( + AbstractionLayer.BT_STATUS_SUCCESS, TEST_BT_ADDR_BYTES_2, BOND_NONE, 0); TestUtils.waitForLooperToFinishScheduledTask(mBondStateMachine.getHandler().getLooper()); // Try to pair these two devices again, createBondNative() should be invoked. @@ -173,12 +173,16 @@ public class BondStateMachineTest { mRemoteDevices.reset(); mBondStateMachine.mPendingBondedDevices.clear(); - BluetoothDevice device1 = BluetoothAdapter.getDefaultAdapter().getRemoteLeDevice( - Utils.getAddressStringFromByte(TEST_BT_ADDR_BYTES), - BluetoothDevice.ADDRESS_TYPE_PUBLIC); - BluetoothDevice device2 = BluetoothAdapter.getDefaultAdapter().getRemoteLeDevice( - Utils.getAddressStringFromByte(TEST_BT_ADDR_BYTES_2), - BluetoothDevice.ADDRESS_TYPE_RANDOM); + BluetoothDevice device1 = + BluetoothAdapter.getDefaultAdapter() + .getRemoteLeDevice( + Utils.getAddressStringFromByte(TEST_BT_ADDR_BYTES), + BluetoothDevice.ADDRESS_TYPE_PUBLIC); + BluetoothDevice device2 = + BluetoothAdapter.getDefaultAdapter() + .getRemoteLeDevice( + Utils.getAddressStringFromByte(TEST_BT_ADDR_BYTES_2), + BluetoothDevice.ADDRESS_TYPE_RANDOM); // The createBond() request for two devices with different address types. Message createBondMsg1 = mBondStateMachine.obtainMessage(BondStateMachine.CREATE_BOND); @@ -257,219 +261,323 @@ public class BondStateMachineTest { testSendIntentNoPendingDevice( BOND_NONE, BOND_NONE, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_NONE, BOND_BONDING, false, BOND_BONDING, - true, BOND_NONE, BOND_BONDING, false); - testSendIntentNoPendingDevice(BOND_NONE, BOND_BONDED, false, BOND_BONDED, - true, BOND_NONE, BOND_BONDING, true); - testSendIntentNoPendingDevice(BOND_NONE, badBondState, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDING, BOND_NONE, false, BOND_NONE, - true, BOND_BONDING, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDING, BOND_BONDING, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDING, BOND_BONDED, false, BOND_BONDED, - false, BOND_NONE, BOND_NONE, true); - testSendIntentNoPendingDevice(BOND_BONDING, badBondState, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDED, BOND_NONE, false, BOND_NONE, - true, BOND_BONDED, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDED, BOND_BONDING, false, BOND_BONDING, - true, BOND_BONDED, BOND_BONDING, false); - testSendIntentNoPendingDevice(BOND_BONDED, BOND_BONDED, false, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDED, badBondState, false, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - - testSendIntentNoPendingDevice(BOND_NONE, BOND_NONE, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_NONE, BOND_BONDING, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_NONE, BOND_BONDED, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_NONE, badBondState, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDING, BOND_NONE, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDING, BOND_BONDING, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDING, BOND_BONDED, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDING, badBondState, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDED, BOND_NONE, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDED, BOND_BONDING, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDED, BOND_BONDED, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDevice(BOND_BONDED, badBondState, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_NONE, BOND_BONDING, false, BOND_BONDING, true, BOND_NONE, BOND_BONDING, false); + testSendIntentNoPendingDevice( + BOND_NONE, BOND_BONDED, false, BOND_BONDED, true, BOND_NONE, BOND_BONDING, true); + testSendIntentNoPendingDevice( + BOND_NONE, badBondState, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDING, BOND_NONE, false, BOND_NONE, true, BOND_BONDING, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDING, + BOND_BONDING, + false, + BOND_BONDING, + false, + BOND_NONE, + BOND_NONE, + false); + testSendIntentNoPendingDevice( + BOND_BONDING, BOND_BONDED, false, BOND_BONDED, false, BOND_NONE, BOND_NONE, true); + testSendIntentNoPendingDevice( + BOND_BONDING, + badBondState, + false, + BOND_BONDING, + false, + BOND_NONE, + BOND_NONE, + false); + testSendIntentNoPendingDevice( + BOND_BONDED, BOND_NONE, false, BOND_NONE, true, BOND_BONDED, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDED, + BOND_BONDING, + false, + BOND_BONDING, + true, + BOND_BONDED, + BOND_BONDING, + false); + testSendIntentNoPendingDevice( + BOND_BONDED, BOND_BONDED, false, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDED, badBondState, false, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + + testSendIntentNoPendingDevice( + BOND_NONE, BOND_NONE, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_NONE, BOND_BONDING, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_NONE, BOND_BONDED, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_NONE, badBondState, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDING, BOND_NONE, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDING, BOND_BONDING, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDING, BOND_BONDED, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDING, badBondState, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDED, BOND_NONE, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDED, BOND_BONDING, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDED, BOND_BONDED, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDevice( + BOND_BONDED, badBondState, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); // Uuid not available, mPendingBondedDevice contains a remote device. - testSendIntentPendingDevice(BOND_NONE, BOND_NONE, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_NONE, BOND_BONDING, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_NONE, BOND_BONDED, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_NONE, badBondState, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDING, BOND_NONE, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDING, BOND_BONDING, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDING, BOND_BONDED, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDING, badBondState, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDED, BOND_NONE, false, BOND_NONE, - true, BOND_BONDING, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDED, BOND_BONDING, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDED, BOND_BONDED, false, BOND_BONDED, - false, BOND_NONE, BOND_NONE, true); - testSendIntentPendingDevice(BOND_BONDED, badBondState, false, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - - testSendIntentPendingDevice(BOND_NONE, BOND_NONE, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_NONE, BOND_BONDING, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_NONE, BOND_BONDED, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_NONE, badBondState, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDING, BOND_NONE, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDING, BOND_BONDING, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDING, BOND_BONDED, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDING, badBondState, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDED, BOND_NONE, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDED, BOND_BONDING, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDevice(BOND_BONDED, BOND_BONDED, true, BOND_BONDED, - true, BOND_BONDING, BOND_BONDED, false); - testSendIntentPendingDevice(BOND_BONDED, badBondState, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_NONE, BOND_NONE, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_NONE, BOND_BONDING, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_NONE, BOND_BONDED, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_NONE, badBondState, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDING, BOND_NONE, false, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDING, + BOND_BONDING, + false, + BOND_BONDING, + false, + BOND_NONE, + BOND_NONE, + false); + testSendIntentPendingDevice( + BOND_BONDING, BOND_BONDED, false, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDING, + badBondState, + false, + BOND_BONDING, + false, + BOND_NONE, + BOND_NONE, + false); + testSendIntentPendingDevice( + BOND_BONDED, BOND_NONE, false, BOND_NONE, true, BOND_BONDING, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDED, BOND_BONDING, false, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDED, BOND_BONDED, false, BOND_BONDED, false, BOND_NONE, BOND_NONE, true); + testSendIntentPendingDevice( + BOND_BONDED, badBondState, false, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + + testSendIntentPendingDevice( + BOND_NONE, BOND_NONE, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_NONE, BOND_BONDING, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_NONE, BOND_BONDED, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_NONE, badBondState, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDING, BOND_NONE, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDING, BOND_BONDING, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDING, BOND_BONDED, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDING, badBondState, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDED, BOND_NONE, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDED, BOND_BONDING, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDevice( + BOND_BONDED, + BOND_BONDED, + true, + BOND_BONDED, + true, + BOND_BONDING, + BOND_BONDED, + false); + testSendIntentPendingDevice( + BOND_BONDED, badBondState, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); // Uuid available, mPendingBondedDevice is empty. - testSendIntentNoPendingDeviceWithUuid(BOND_NONE, BOND_NONE, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_NONE, BOND_BONDING, false, BOND_BONDING, - true, BOND_NONE, BOND_BONDING, false); - testSendIntentNoPendingDeviceWithUuid(BOND_NONE, BOND_BONDED, false, BOND_BONDED, - true, BOND_NONE, BOND_BONDED, false); - testSendIntentNoPendingDeviceWithUuid(BOND_NONE, badBondState, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDING, BOND_NONE, false, BOND_NONE, - true, BOND_BONDING, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDING, BOND_BONDING, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDING, BOND_BONDED, false, BOND_BONDED, - true, BOND_BONDING, BOND_BONDED, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDING, badBondState, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDED, BOND_NONE, false, BOND_NONE, - true, BOND_BONDED, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDED, BOND_BONDING, false, BOND_BONDING, - true, BOND_BONDED, BOND_BONDING, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDED, BOND_BONDED, false, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDED, badBondState, false, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - - testSendIntentNoPendingDeviceWithUuid(BOND_NONE, BOND_NONE, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_NONE, BOND_BONDING, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_NONE, BOND_BONDED, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_NONE, badBondState, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDING, BOND_NONE, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDING, BOND_BONDING, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDING, BOND_BONDED, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDING, badBondState, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDED, BOND_NONE, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDED, BOND_BONDING, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDED, BOND_BONDED, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentNoPendingDeviceWithUuid(BOND_BONDED, badBondState, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_NONE, BOND_NONE, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_NONE, BOND_BONDING, false, BOND_BONDING, true, BOND_NONE, BOND_BONDING, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_NONE, BOND_BONDED, false, BOND_BONDED, true, BOND_NONE, BOND_BONDED, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_NONE, badBondState, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDING, BOND_NONE, false, BOND_NONE, true, BOND_BONDING, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDING, + BOND_BONDING, + false, + BOND_BONDING, + false, + BOND_NONE, + BOND_NONE, + false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDING, + BOND_BONDED, + false, + BOND_BONDED, + true, + BOND_BONDING, + BOND_BONDED, + false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDING, + badBondState, + false, + BOND_BONDING, + false, + BOND_NONE, + BOND_NONE, + false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDED, BOND_NONE, false, BOND_NONE, true, BOND_BONDED, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDED, + BOND_BONDING, + false, + BOND_BONDING, + true, + BOND_BONDED, + BOND_BONDING, + false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDED, BOND_BONDED, false, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDED, badBondState, false, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + + testSendIntentNoPendingDeviceWithUuid( + BOND_NONE, BOND_NONE, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_NONE, BOND_BONDING, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_NONE, BOND_BONDED, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_NONE, badBondState, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDING, BOND_NONE, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDING, BOND_BONDING, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDING, BOND_BONDED, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDING, badBondState, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDED, BOND_NONE, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDED, BOND_BONDING, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDED, BOND_BONDED, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentNoPendingDeviceWithUuid( + BOND_BONDED, badBondState, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); // Uuid available, mPendingBondedDevice contains a remote device. - testSendIntentPendingDeviceWithUuid(BOND_NONE, BOND_NONE, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_NONE, BOND_BONDING, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_NONE, BOND_BONDED, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_NONE, badBondState, false, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDING, BOND_NONE, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDING, BOND_BONDING, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDING, BOND_BONDED, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDING, badBondState, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDED, BOND_NONE, false, BOND_NONE, - true, BOND_BONDING, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDED, BOND_BONDING, false, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDED, BOND_BONDED, false, BOND_BONDED, - true, BOND_BONDING, BOND_BONDED, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDED, badBondState, false, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - - testSendIntentPendingDeviceWithUuid(BOND_NONE, BOND_NONE, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_NONE, BOND_BONDING, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_NONE, BOND_BONDED, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_NONE, badBondState, true, BOND_NONE, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDING, BOND_NONE, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDING, BOND_BONDING, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDING, BOND_BONDED, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDING, badBondState, true, BOND_BONDING, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDED, BOND_NONE, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDED, BOND_BONDING, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDED, BOND_BONDED, true, BOND_BONDED, - true, BOND_BONDING, BOND_BONDED, false); - testSendIntentPendingDeviceWithUuid(BOND_BONDED, badBondState, true, BOND_BONDED, - false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_NONE, BOND_NONE, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_NONE, BOND_BONDING, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_NONE, BOND_BONDED, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_NONE, badBondState, false, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDING, BOND_NONE, false, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDING, + BOND_BONDING, + false, + BOND_BONDING, + false, + BOND_NONE, + BOND_NONE, + false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDING, BOND_BONDED, false, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDING, + badBondState, + false, + BOND_BONDING, + false, + BOND_NONE, + BOND_NONE, + false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDED, BOND_NONE, false, BOND_NONE, true, BOND_BONDING, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDED, BOND_BONDING, false, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDED, + BOND_BONDED, + false, + BOND_BONDED, + true, + BOND_BONDING, + BOND_BONDED, + false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDED, badBondState, false, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + + testSendIntentPendingDeviceWithUuid( + BOND_NONE, BOND_NONE, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_NONE, BOND_BONDING, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_NONE, BOND_BONDED, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_NONE, badBondState, true, BOND_NONE, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDING, BOND_NONE, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDING, BOND_BONDING, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDING, BOND_BONDED, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDING, badBondState, true, BOND_BONDING, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDED, BOND_NONE, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDED, BOND_BONDING, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDED, + BOND_BONDED, + true, + BOND_BONDED, + true, + BOND_BONDING, + BOND_BONDED, + false); + testSendIntentPendingDeviceWithUuid( + BOND_BONDED, badBondState, true, BOND_BONDED, false, BOND_NONE, BOND_NONE, false); } - private void testSendIntentCase(int oldState, int newState, boolean isTriggerFromDelayMessage, - int expectedNewState, boolean shouldBroadcast, int broadcastOldState, - int broadcastNewState, boolean shouldDelayMessageExist) { + private void testSendIntentCase( + int oldState, + int newState, + boolean isTriggerFromDelayMessage, + int expectedNewState, + boolean shouldBroadcast, + int broadcastOldState, + int broadcastNewState, + boolean shouldDelayMessageExist) { ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); // Setup old state before start test. mDeviceProperties.mBondState = oldState; try { - mBondStateMachine.sendIntent(mDevice, newState, TEST_BOND_REASON, - isTriggerFromDelayMessage); + mBondStateMachine.sendIntent( + mDevice, newState, TEST_BOND_REASON, isTriggerFromDelayMessage); } catch (IllegalArgumentException e) { // Do nothing. } @@ -481,14 +589,19 @@ public class BondStateMachineTest { // Check for bond state Intent status. if (shouldBroadcast) { - verify(mAdapterService, times(++mVerifyCount)).sendBroadcastAsUser( - intentArgument.capture(), eq(UserHandle.ALL), - eq(BLUETOOTH_CONNECT), any(Bundle.class)); - verifyBondStateChangeIntent(broadcastOldState, broadcastNewState, - intentArgument.getValue()); + verify(mAdapterService, times(++mVerifyCount)) + .sendBroadcastAsUser( + intentArgument.capture(), eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verifyBondStateChangeIntent( + broadcastOldState, broadcastNewState, intentArgument.getValue()); } else { - verify(mAdapterService, times(mVerifyCount)).sendBroadcastAsUser(any(Intent.class), - any(UserHandle.class), anyString(), any(Bundle.class)); + verify(mAdapterService, times(mVerifyCount)) + .sendBroadcastAsUser( + any(Intent.class), + any(UserHandle.class), + anyString(), + any(Bundle.class)); } if (shouldDelayMessageExist) { @@ -624,11 +737,11 @@ public class BondStateMachineTest { Assert.assertEquals(BluetoothDevice.ACTION_BOND_STATE_CHANGED, intent.getAction()); Assert.assertEquals(mDevice, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); Assert.assertEquals(newState, intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1)); - Assert.assertEquals(oldState, intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, - -1)); + Assert.assertEquals( + oldState, intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1)); if (newState == BOND_NONE) { - Assert.assertEquals(TEST_BOND_REASON, - intent.getIntExtra(BluetoothDevice.EXTRA_UNBOND_REASON, -1)); + Assert.assertEquals( + TEST_BOND_REASON, intent.getIntExtra(BluetoothDevice.EXTRA_UNBOND_REASON, -1)); } else { Assert.assertEquals(-1, intent.getIntExtra(BluetoothDevice.EXTRA_UNBOND_REASON, -1)); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/CompanionManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/CompanionManagerTest.java index 3e9f37b74c5..30eb0f1b62d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/CompanionManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/CompanionManagerTest.java @@ -53,12 +53,9 @@ public class CompanionManagerTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private AdapterService mAdapterService; - @Mock - SharedPreferences mSharedPreferences; - @Mock - SharedPreferences.Editor mEditor; + @Mock private AdapterService mAdapterService; + @Mock SharedPreferences mSharedPreferences; + @Mock SharedPreferences.Editor mEditor; @Before public void setUp() throws Exception { @@ -72,8 +69,10 @@ public class CompanionManagerTest { doReturn(mHandlerThread.getLooper()).when(mAdapterService).getMainLooper(); // Mock SharedPreferences when(mSharedPreferences.edit()).thenReturn(mEditor); - doReturn(mSharedPreferences).when(mAdapterService).getSharedPreferences(eq( - CompanionManager.COMPANION_INFO), eq(Context.MODE_PRIVATE)); + doReturn(mSharedPreferences) + .when(mAdapterService) + .getSharedPreferences( + eq(CompanionManager.COMPANION_INFO), eq(Context.MODE_PRIVATE)); // Tell the AdapterService that it is a mock (see isMock documentation) doReturn(true).when(mAdapterService).isMock(); // Use the resources in the instrumentation instead of the mocked AdapterService @@ -147,20 +146,20 @@ public class CompanionManagerTest { private void checkReasonableConnParameterHelper(int priority) { // Max/Min values from the Bluetooth spec Version 5.3 | Vol 4, Part E | 7.8.18 - final int minInterval = 6; // 0x0006 + final int minInterval = 6; // 0x0006 final int maxInterval = 3200; // 0x0C80 - final int minLatency = 0; // 0x0000 - final int maxLatency = 499; // 0x01F3 - - int min = mCompanionManager.getGattConnParameters( - TEST_DEVICE, CompanionManager.GATT_CONN_INTERVAL_MIN, - priority); - int max = mCompanionManager.getGattConnParameters( - TEST_DEVICE, CompanionManager.GATT_CONN_INTERVAL_MAX, - priority); - int latency = mCompanionManager.getGattConnParameters( - TEST_DEVICE, CompanionManager.GATT_CONN_LATENCY, - priority); + final int minLatency = 0; // 0x0000 + final int maxLatency = 499; // 0x01F3 + + int min = + mCompanionManager.getGattConnParameters( + TEST_DEVICE, CompanionManager.GATT_CONN_INTERVAL_MIN, priority); + int max = + mCompanionManager.getGattConnParameters( + TEST_DEVICE, CompanionManager.GATT_CONN_INTERVAL_MAX, priority); + int latency = + mCompanionManager.getGattConnParameters( + TEST_DEVICE, CompanionManager.GATT_CONN_LATENCY, priority); Assert.assertTrue(max >= min); Assert.assertTrue(max >= minInterval); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java index f1de518872a..a715b357115 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java @@ -92,7 +92,6 @@ public class DataMigrationTest { when(mMockContext.getCacheDir()).thenReturn(mTargetContext.getCacheDir()); when(mMockContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mPrefs); - } @After @@ -108,17 +107,15 @@ public class DataMigrationTest { assertThat(DataMigration.migrationStatus(mMockContext)).isEqualTo(status); } - /** - * Test: execute Empty migration - */ + /** Test: execute Empty migration */ @Test public void testEmptyMigration() { BluetoothLegacyContentProvider fakeContentProvider = new BluetoothLegacyContentProvider(mMockContext); mMockContentResolver.addProvider(AUTHORITY, fakeContentProvider); - final int nCallCount = DataMigration.sharedPreferencesKeys.length - + 1; // +1 for default preferences + final int nCallCount = + DataMigration.sharedPreferencesKeys.length + 1; // +1 for default preferences final int nBundleCount = 2; // `bluetooth_db` && `btopp.db` assertRunStatus(DataMigration.MIGRATION_STATUS_COMPLETED); @@ -136,14 +133,21 @@ public class DataMigrationTest { BluetoothLegacyContentProvider(Context ctx) { super(ctx); } + int mCallCount = 0; int mBundleCount = 0; + @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + public Cursor query( + Uri uri, + String[] projection, + String selection, + String[] selectionArgs, String sortOrder) { mBundleCount++; return null; } + @Override public Bundle call(String method, String arg, Bundle extras) { mCallCount++; @@ -151,9 +155,7 @@ public class DataMigrationTest { } } - /** - * Test: execute migration without having a content provided registered - */ + /** Test: execute migration without having a content provided registered */ @Test public void testMissingProvider() { assertThat(DataMigration.isMigrationApkInstalled(mMockContext)).isFalse(); @@ -164,32 +166,25 @@ public class DataMigrationTest { assertThat(DataMigration.isMigrationApkInstalled(mMockContext)).isTrue(); } - /** - * Test: execute migration after too many attempt - */ + /** Test: execute migration after too many attempt */ @Test public void testTooManyAttempt() { - assertThat(mPrefs.getInt(DataMigration.MIGRATION_ATTEMPT_PROPERTY, -1)) - .isEqualTo(-1); + assertThat(mPrefs.getInt(DataMigration.MIGRATION_ATTEMPT_PROPERTY, -1)).isEqualTo(-1); for (int i = 0; i < DataMigration.MAX_ATTEMPT; i++) { - assertThat(DataMigration.incrementeMigrationAttempt(mMockContext)) - .isTrue(); + assertThat(DataMigration.incrementeMigrationAttempt(mMockContext)).isTrue(); assertThat(mPrefs.getInt(DataMigration.MIGRATION_ATTEMPT_PROPERTY, -1)) - .isEqualTo(i + 1); + .isEqualTo(i + 1); } - assertThat(DataMigration.incrementeMigrationAttempt(mMockContext)) - .isFalse(); + assertThat(DataMigration.incrementeMigrationAttempt(mMockContext)).isFalse(); assertThat(mPrefs.getInt(DataMigration.MIGRATION_ATTEMPT_PROPERTY, -1)) - .isEqualTo(DataMigration.MAX_ATTEMPT + 1); + .isEqualTo(DataMigration.MAX_ATTEMPT + 1); mMockContentResolver.addProvider(AUTHORITY, new MockContentProvider(mMockContext)); assertRunStatus(DataMigration.MIGRATION_STATUS_MAX_ATTEMPT); } - /** - * Test: execute migration of SharedPreferences - */ + /** Test: execute migration of SharedPreferences */ @Test public void testSharedPreferencesMigration() { BluetoothLegacySharedPreferencesContentProvider fakeContentProvider = @@ -224,8 +219,8 @@ public class DataMigrationTest { assertThat(DataMigration.sharedPreferencesMigration("empty", mMockContext)).isFalse(); - assertThat(DataMigration - .sharedPreferencesMigration("anything else", mMockContext)).isTrue(); + assertThat(DataMigration.sharedPreferencesMigration("anything else", mMockContext)) + .isTrue(); } private static class BluetoothLegacySharedPreferencesContentProvider @@ -233,15 +228,22 @@ public class DataMigrationTest { BluetoothLegacySharedPreferencesContentProvider(Context ctx) { super(ctx); } + String mLastMethod = null; int mCallCount = 0; int mBundleCount = 0; + @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + public Cursor query( + Uri uri, + String[] projection, + String selection, + String[] selectionArgs, String sortOrder) { mBundleCount++; return null; } + @Override public Bundle call(String method, String arg, Bundle extras) { mCallCount++; @@ -252,7 +254,7 @@ public class DataMigrationTest { final String key = "key" + arg; Bundle b = new Bundle(); b.putStringArrayList(DataMigration.KEY_LIST, new ArrayList(Arrays.asList(key))); - switch(arg) { + switch (arg) { case "Boolean": b.putBoolean(key, true); break; @@ -272,7 +274,7 @@ public class DataMigrationTest { b.putObject(key, null); break; case "Invalid": - // Put anything different from Boolean/Long/Integer/String + // Put anything different from Boolean/Long/Integer/String b.putFloat(key, 42f); break; case "empty": @@ -286,15 +288,13 @@ public class DataMigrationTest { } } - /** - * Test: execute migration of BLUETOOTH_DATABASE and OPP_DATABASE without correct data - */ + /** Test: execute migration of BLUETOOTH_DATABASE and OPP_DATABASE without correct data */ @Test public void testIncompleteDbMigration() { when(mMockContext.getDatabasePath("btopp.db")) - .thenReturn(mTargetContext.getDatabasePath("TestOppDb")); + .thenReturn(mTargetContext.getDatabasePath("TestOppDb")); when(mMockContext.getDatabasePath("bluetooth_db")) - .thenReturn(mTargetContext.getDatabasePath("TestBluetoothDb")); + .thenReturn(mTargetContext.getDatabasePath("TestBluetoothDb")); BluetoothLegacyDbContentProvider fakeContentProvider = new BluetoothLegacyDbContentProvider(mMockContext); @@ -308,17 +308,13 @@ public class DataMigrationTest { } private static final List> FAKE_SAMPLE = - Arrays.asList( - new Pair("wrong_key", "wrong_content") - ); + Arrays.asList(new Pair("wrong_key", "wrong_content")); - /** - * Test: execute migration of BLUETOOTH_DATABASE - */ + /** Test: execute migration of BLUETOOTH_DATABASE */ @Test public void testBluetoothDbMigration() { when(mMockContext.getDatabasePath("bluetooth_db")) - .thenReturn(mTargetContext.getDatabasePath("TestBluetoothDb")); + .thenReturn(mTargetContext.getDatabasePath("TestBluetoothDb")); BluetoothLegacyDbContentProvider fakeContentProvider = new BluetoothLegacyDbContentProvider(mMockContext); @@ -333,17 +329,16 @@ public class DataMigrationTest { Log.d(TAG, "Metadata migrated: " + metadata); - assertWithMessage("Address mismatch") - .that(metadata.getAddress()).isEqualTo("my_address"); + assertWithMessage("Address mismatch").that(metadata.getAddress()).isEqualTo("my_address"); assertWithMessage("Connection policy mismatch") - .that(metadata.getProfileConnectionPolicy(BluetoothProfile.A2DP)) - .isEqualTo(CONNECTION_POLICY_FORBIDDEN); + .that(metadata.getProfileConnectionPolicy(BluetoothProfile.A2DP)) + .isEqualTo(CONNECTION_POLICY_FORBIDDEN); assertWithMessage("Custom metadata mismatch") - .that(metadata.getCustomizedMeta(BluetoothDevice.METADATA_UNTETHERED_LEFT_CHARGING)) - .isEqualTo(CUSTOM_META); + .that(metadata.getCustomizedMeta(BluetoothDevice.METADATA_UNTETHERED_LEFT_CHARGING)) + .isEqualTo(CUSTOM_META); } - private static final byte[] CUSTOM_META = new byte[]{ 42, 43, 44}; + private static final byte[] CUSTOM_META = new byte[] {42, 43, 44}; private static final List> BLUETOOTH_DATABASE_SAMPLE = Arrays.asList( @@ -401,16 +396,13 @@ public class DataMigrationTest { new Pair("untethered_right_low_battery_threshold", CUSTOM_META), new Pair("untethered_case_low_battery_threshold", CUSTOM_META), new Pair("spatial_audio", CUSTOM_META), - new Pair("fastpair_customized", CUSTOM_META) - ); + new Pair("fastpair_customized", CUSTOM_META)); - /** - * Test: execute migration of OPP_DATABASE - */ + /** Test: execute migration of OPP_DATABASE */ @Test public void testOppDbMigration() { when(mMockContext.getDatabasePath("btopp.db")) - .thenReturn(mTargetContext.getDatabasePath("TestOppDb")); + .thenReturn(mTargetContext.getDatabasePath("TestOppDb")); BluetoothLegacyDbContentProvider fakeContentProvider = new BluetoothLegacyDbContentProvider(mMockContext); @@ -438,23 +430,29 @@ public class DataMigrationTest { // Long new Pair(BluetoothShare.TOTAL_BYTES, 42L), - new Pair(BluetoothShare.TIMESTAMP, 42L) - ); + new Pair(BluetoothShare.TIMESTAMP, 42L)); private static class BluetoothLegacyDbContentProvider extends MockContentProvider { BluetoothLegacyDbContentProvider(Context ctx) { super(ctx); } + String mLastMethod = null; Cursor mCursor = null; int mCallCount = 0; int mBundleCount = 0; + @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + public Cursor query( + Uri uri, + String[] projection, + String selection, + String[] selectionArgs, String sortOrder) { mBundleCount++; return mCursor; } + @Override public Bundle call(String method, String arg, Bundle extras) { mCallCount++; diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java index 7acfcb494d0..e827751fb1e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java @@ -149,8 +149,7 @@ public class PhonePolicyTest { /** * Test that when new UUIDs are refreshed for a device then we set the priorities for various - * profiles accurately. The following profiles should have ON priorities: - * A2DP, HFP, HID and PAN + * profiles accurately. The following profiles should have ON priorities: A2DP, HFP, HID and PAN */ @Test public void testProcessInitProfilePriorities() { @@ -362,19 +361,25 @@ public class PhonePolicyTest { // Does not auto connect and allow HFP and A2DP to be connected processInitProfilePriorities_LeAudioHelper(true, false, false, false); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO, + .setProfileConnectionPolicy( + device, + BluetoothProfile.LE_AUDIO, BluetoothProfile.CONNECTION_POLICY_ALLOWED); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.A2DP, - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .setProfileConnectionPolicy( + device, BluetoothProfile.A2DP, BluetoothProfile.CONNECTION_POLICY_ALLOWED); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.HEADSET, + .setProfileConnectionPolicy( + device, + BluetoothProfile.HEADSET, BluetoothProfile.CONNECTION_POLICY_ALLOWED); // Auto connect to HFP and A2DP but disallow LE Audio processInitProfilePriorities_LeAudioHelper(false, true, false, false); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO, + .setProfileConnectionPolicy( + device, + BluetoothProfile.LE_AUDIO, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); verify(mA2dpService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) .setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); @@ -384,13 +389,17 @@ public class PhonePolicyTest { // Does not auto connect and disallow LE Audio to be connected processInitProfilePriorities_LeAudioHelper(false, false, false, false); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) - .setProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO, + .setProfileConnectionPolicy( + device, + BluetoothProfile.LE_AUDIO, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) - .setProfileConnectionPolicy(device, BluetoothProfile.A2DP, - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .setProfileConnectionPolicy( + device, BluetoothProfile.A2DP, BluetoothProfile.CONNECTION_POLICY_ALLOWED); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) - .setProfileConnectionPolicy(device, BluetoothProfile.HEADSET, + .setProfileConnectionPolicy( + device, + BluetoothProfile.HEADSET, BluetoothProfile.CONNECTION_POLICY_ALLOWED); } @@ -411,13 +420,17 @@ public class PhonePolicyTest { // Does not auto connect and allow HFP and A2DP to be connected processInitProfilePriorities_LeAudioHelper(true, false, true, false); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO, + .setProfileConnectionPolicy( + device, + BluetoothProfile.LE_AUDIO, BluetoothProfile.CONNECTION_POLICY_ALLOWED); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.A2DP, - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .setProfileConnectionPolicy( + device, BluetoothProfile.A2DP, BluetoothProfile.CONNECTION_POLICY_ALLOWED); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.HEADSET, + .setProfileConnectionPolicy( + device, + BluetoothProfile.HEADSET, BluetoothProfile.CONNECTION_POLICY_ALLOWED); // Auto connect to LE audio but disallow HFP and A2DP @@ -425,22 +438,32 @@ public class PhonePolicyTest { verify(mLeAudioService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) .setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.HEADSET, + .setProfileConnectionPolicy( + device, + BluetoothProfile.HEADSET, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .setProfileConnectionPolicy(device, BluetoothProfile.A2DP, + .setProfileConnectionPolicy( + device, + BluetoothProfile.A2DP, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Does not auto connect and disallow HFP and A2DP to be connected processInitProfilePriorities_LeAudioHelper(false, false, true, false); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) - .setProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO, + .setProfileConnectionPolicy( + device, + BluetoothProfile.LE_AUDIO, BluetoothProfile.CONNECTION_POLICY_ALLOWED); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) - .setProfileConnectionPolicy(device, BluetoothProfile.HEADSET, + .setProfileConnectionPolicy( + device, + BluetoothProfile.HEADSET, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) - .setProfileConnectionPolicy(device, BluetoothProfile.A2DP, + .setProfileConnectionPolicy( + device, + BluetoothProfile.A2DP, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); } @@ -733,10 +756,10 @@ public class PhonePolicyTest { when(mAdapterService.getBondState(bondedDevice)).thenReturn(BluetoothDevice.BOND_BONDED); // Return CONNECTION_POLICY_ALLOWED over HFP and A2DP - when(mHeadsetService.getConnectionPolicy(bondedDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(bondedDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(bondedDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(bondedDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); // Inject an event that the adapter is turned on. mPhonePolicy.onBluetoothStateChange(BluetoothAdapter.STATE_OFF, BluetoothAdapter.STATE_ON); @@ -746,9 +769,7 @@ public class PhonePolicyTest { verify(mHeadsetService).connect(eq(bondedDevice)); } - /** - * Test that when an active device is disconnected, we will not auto connect it - */ + /** Test that when an active device is disconnected, we will not auto connect it */ @Test public void testDisconnectNoAutoConnect() { // Return desired values from the mocked object(s) @@ -762,18 +783,18 @@ public class PhonePolicyTest { connectionOrder.add(getTestDevice(mAdapter, 2)); connectionOrder.add(getTestDevice(mAdapter, 3)); - when(mDatabaseManager.getMostRecentlyConnectedA2dpDevice()).thenReturn( - connectionOrder.get(0)); + when(mDatabaseManager.getMostRecentlyConnectedA2dpDevice()) + .thenReturn(connectionOrder.get(0)); // Make all devices auto connect - when(mHeadsetService.getConnectionPolicy(connectionOrder.get(0))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mHeadsetService.getConnectionPolicy(connectionOrder.get(1))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mHeadsetService.getConnectionPolicy(connectionOrder.get(2))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mHeadsetService.getConnectionPolicy(connectionOrder.get(3))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + when(mHeadsetService.getConnectionPolicy(connectionOrder.get(0))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(connectionOrder.get(1))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(connectionOrder.get(2))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(connectionOrder.get(3))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Make one of the device active mPhonePolicy.profileActiveDeviceChanged(BluetoothProfile.A2DP, connectionOrder.get(0)); @@ -801,8 +822,8 @@ public class PhonePolicyTest { verify(mDatabaseManager, never()).setConnection(eq(connectionOrder.get(3)), anyInt()); // Disconnect a2dp for the device from previous STATE_CONNECTED - when(mHeadsetService.getConnectionState(connectionOrder.get(1))).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); + when(mHeadsetService.getConnectionState(connectionOrder.get(1))) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); mPhonePolicy.profileConnectionStateChanged( BluetoothProfile.A2DP, connectionOrder.get(1), @@ -864,10 +885,10 @@ public class PhonePolicyTest { // Return PRIORITY_AUTO_CONNECT over HFP and A2DP. This would imply that the profiles are // auto-connectable. - when(mHeadsetService.getConnectionPolicy(bondedDevices[0])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(bondedDevices[0])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(bondedDevices[0])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(bondedDevices[0])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mAdapterService.getState()).thenReturn(BluetoothAdapter.STATE_ON); @@ -878,8 +899,8 @@ public class PhonePolicyTest { hsConnectedDevices.add(bondedDevices[0]); when(mHeadsetService.getConnectedDevices()).thenReturn(hsConnectedDevices); // Also the A2DP should say that its not connected for same device - when(mA2dpService.getConnectionState(bondedDevices[0])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(bondedDevices[0])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); // ACL is connected, lets simulate this. when(mAdapterService.getConnectionState(bondedDevices[0])) @@ -887,12 +908,15 @@ public class PhonePolicyTest { // We send a connection successful for one profile since the re-connect *only* works if we // have already connected successfully over one of the profiles - updateProfileConnectionStateHelper(bondedDevices[0], BluetoothProfile.HEADSET, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + updateProfileConnectionStateHelper( + bondedDevices[0], + BluetoothProfile.HEADSET, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTED); // Check that we get a call to A2DP connect - verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)).connect( - eq(bondedDevices[0])); + verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)) + .connect(eq(bondedDevices[0])); } /** @@ -958,15 +982,15 @@ public class PhonePolicyTest { when(mAdapterService.getConnectionState(testDevice)) .thenReturn(BluetoothProfile.STATE_CONNECTED); - when(mDatabaseManager.getMostRecentlyConnectedA2dpDevice()).thenReturn( - connectionOrder.get(0)); + when(mDatabaseManager.getMostRecentlyConnectedA2dpDevice()) + .thenReturn(connectionOrder.get(0)); // Return PRIORITY_AUTO_CONNECT over HFP and A2DP. This would imply that the profiles are // auto-connectable. - when(mHeadsetService.getConnectionPolicy(connectionOrder.get(0))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(connectionOrder.get(0))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(connectionOrder.get(0))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(connectionOrder.get(0))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mAdapterService.getState()).thenReturn(BluetoothAdapter.STATE_ON); @@ -977,22 +1001,28 @@ public class PhonePolicyTest { hsConnectedDevices.add(connectionOrder.get(0)); when(mHeadsetService.getConnectedDevices()).thenReturn(hsConnectedDevices); // Also the A2DP should say that its not connected for same device - when(mA2dpService.getConnectionState(connectionOrder.get(0))).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(connectionOrder.get(0))) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); // We send a connection success event for one profile since the re-connect *only* works if // we have already connected successfully over one of the profiles - updateProfileConnectionStateHelper(connectionOrder.get(0), BluetoothProfile.HEADSET, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + updateProfileConnectionStateHelper( + connectionOrder.get(0), + BluetoothProfile.HEADSET, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTED); // Check that we get a call to A2DP reconnect - verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)).connect( - connectionOrder.get(0)); + verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)) + .connect(connectionOrder.get(0)); // We send a connection failure event for the attempted profile, and keep the connected // profile connected. - updateProfileConnectionStateHelper(connectionOrder.get(0), BluetoothProfile.A2DP, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); + updateProfileConnectionStateHelper( + connectionOrder.get(0), + BluetoothProfile.A2DP, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTING); waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1000,17 +1030,23 @@ public class PhonePolicyTest { verify(mA2dpService, never()).setConnectionPolicy(eq(connectionOrder.get(0)), anyInt()); // Send a connection success event for one profile again without disconnecting all profiles - updateProfileConnectionStateHelper(connectionOrder.get(0), BluetoothProfile.HEADSET, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + updateProfileConnectionStateHelper( + connectionOrder.get(0), + BluetoothProfile.HEADSET, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTED); // Check that we won't get a call to A2DP reconnect again before all profiles disconnected - verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)).connect( - connectionOrder.get(0)); + verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)) + .connect(connectionOrder.get(0)); // Send a disconnection event for all connected profiles hsConnectedDevices.remove(connectionOrder.get(0)); - updateProfileConnectionStateHelper(connectionOrder.get(0), BluetoothProfile.HEADSET, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); + updateProfileConnectionStateHelper( + connectionOrder.get(0), + BluetoothProfile.HEADSET, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTED); waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1173,9 +1209,9 @@ public class PhonePolicyTest { /** * Test that a second device will auto-connect if there is already one connected device. * - * Even though we currently only set one device to be auto connect. The consumer of the auto - * connect property works independently so that we will connect to all devices that are in - * auto connect mode. + *

Even though we currently only set one device to be auto connect. The consumer of the auto + * connect property works independently so that we will connect to all devices that are in auto + * connect mode. */ @Test public void testAutoConnectMultipleDevices() { @@ -1196,10 +1232,10 @@ public class PhonePolicyTest { // Return PRIORITY_AUTO_CONNECT over HFP and A2DP. This would imply that the profiles // are auto-connectable. - when(mHeadsetService.getConnectionPolicy(testDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(testDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(testDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(testDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); // We want to trigger (in CONNECT_OTHER_PROFILES_TIMEOUT) a call to connect A2DP // To enable that we need to make sure that HeadsetService returns the device as list // of connected devices. @@ -1217,35 +1253,39 @@ public class PhonePolicyTest { when(mHeadsetService.getConnectedDevices()).thenReturn(hsConnectedDevices); when(mA2dpService.getConnectedDevices()).thenReturn(a2dpConnectedDevices); // Two of the A2DP devices are not connected - when(mA2dpService.getConnectionState(a2dpNotConnectedDevice1)).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - when(mA2dpService.getConnectionState(a2dpNotConnectedDevice2)).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(a2dpNotConnectedDevice1)) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(a2dpNotConnectedDevice2)) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); // We send a connection successful for one profile since the re-connect *only* works if we // have already connected successfully over one of the profiles - updateProfileConnectionStateHelper(a2dpNotConnectedDevice1, BluetoothProfile.HEADSET, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + updateProfileConnectionStateHelper( + a2dpNotConnectedDevice1, + BluetoothProfile.HEADSET, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTED); // We send a connection successful for one profile since the re-connect *only* works if we // have already connected successfully over one of the profiles - updateProfileConnectionStateHelper(a2dpNotConnectedDevice2, BluetoothProfile.HEADSET, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + updateProfileConnectionStateHelper( + a2dpNotConnectedDevice2, + BluetoothProfile.HEADSET, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTED); // Check that we get a call to A2DP connect - verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)).connect( - eq(a2dpNotConnectedDevice1)); - verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)).connect( - eq(a2dpNotConnectedDevice2)); + verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)) + .connect(eq(a2dpNotConnectedDevice1)); + verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)) + .connect(eq(a2dpNotConnectedDevice2)); } /** * Test that the connection policy of all devices are set as appropriate if there is one - * connected device. - * - The HFP and A2DP connect priority for connected devices is set to - * BluetoothProfile.PRIORITY_AUTO_CONNECT - * - The HFP and A2DP connect priority for bonded devices is set to - * BluetoothProfile.CONNECTION_POLICY_ALLOWED + * connected device. - The HFP and A2DP connect priority for connected devices is set to + * BluetoothProfile.PRIORITY_AUTO_CONNECT - The HFP and A2DP connect priority for bonded devices + * is set to BluetoothProfile.CONNECTION_POLICY_ALLOWED */ @Test public void testSetConnectionPolicyMultipleDevices() { @@ -1271,29 +1311,29 @@ public class PhonePolicyTest { if (i == 0) { hsConnectedDevices.add(testDevice); a2dpConnectedDevices.add(testDevice); - when(mHeadsetService.getConnectionPolicy(testDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(testDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(testDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(testDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); } if (i == 1) { hsConnectedDevices.add(testDevice); - when(mHeadsetService.getConnectionPolicy(testDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(testDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mA2dpService.getConnectionPolicy(testDevice)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); } if (i == 2) { a2dpConnectedDevices.add(testDevice); - when(mHeadsetService.getConnectionPolicy(testDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(testDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mA2dpService.getConnectionPolicy(testDevice)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); } if (i == 3) { // Device not connected - when(mHeadsetService.getConnectionPolicy(testDevice)).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(testDevice)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mA2dpService.getConnectionPolicy(testDevice)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); } @@ -1304,41 +1344,43 @@ public class PhonePolicyTest { when(mA2dpService.getConnectedDevices()).thenReturn(a2dpConnectedDevices); // Some of the devices are not connected // testDevices[0] - connected for both HFP and A2DP - when(mHeadsetService.getConnectionState(testDevices[0])).thenReturn( - BluetoothProfile.STATE_CONNECTED); - when(mA2dpService.getConnectionState(testDevices[0])).thenReturn( - BluetoothProfile.STATE_CONNECTED); + when(mHeadsetService.getConnectionState(testDevices[0])) + .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mA2dpService.getConnectionState(testDevices[0])) + .thenReturn(BluetoothProfile.STATE_CONNECTED); // testDevices[1] - connected only for HFP - will auto-connect for A2DP - when(mHeadsetService.getConnectionState(testDevices[1])).thenReturn( - BluetoothProfile.STATE_CONNECTED); - when(mA2dpService.getConnectionState(testDevices[1])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); + when(mHeadsetService.getConnectionState(testDevices[1])) + .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mA2dpService.getConnectionState(testDevices[1])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); // testDevices[2] - connected only for A2DP - will auto-connect for HFP - when(mHeadsetService.getConnectionState(testDevices[2])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - when(mA2dpService.getConnectionState(testDevices[2])).thenReturn( - BluetoothProfile.STATE_CONNECTED); + when(mHeadsetService.getConnectionState(testDevices[2])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(testDevices[2])) + .thenReturn(BluetoothProfile.STATE_CONNECTED); // testDevices[3] - not connected - when(mHeadsetService.getConnectionState(testDevices[3])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - when(mA2dpService.getConnectionState(testDevices[3])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - + when(mHeadsetService.getConnectionState(testDevices[3])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(testDevices[3])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); // Generate connection state changed for HFP for testDevices[1] and trigger // auto-connect for A2DP. - updateProfileConnectionStateHelper(testDevices[1], BluetoothProfile.HEADSET, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + updateProfileConnectionStateHelper( + testDevices[1], + BluetoothProfile.HEADSET, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTED); // Check that we get a call to A2DP connect - verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)).connect( - eq(testDevices[1])); + verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)) + .connect(eq(testDevices[1])); // testDevices[1] auto-connect completed for A2DP a2dpConnectedDevices.add(testDevices[1]); when(mA2dpService.getConnectedDevices()).thenReturn(a2dpConnectedDevices); - when(mA2dpService.getConnectionState(testDevices[1])).thenReturn( - BluetoothProfile.STATE_CONNECTED); + when(mA2dpService.getConnectionState(testDevices[1])) + .thenReturn(BluetoothProfile.STATE_CONNECTED); // Check the connect priorities for all devices // - testDevices[0] - connected for HFP and A2DP: setConnectionPolicy() should not be called @@ -1350,8 +1392,9 @@ public class PhonePolicyTest { // called verify(mHeadsetService, times(0)).setConnectionPolicy(eq(testDevices[0]), anyInt()); verify(mA2dpService, times(0)).setConnectionPolicy(eq(testDevices[0]), anyInt()); - verify(mHeadsetService, times(0)).setConnectionPolicy(eq(testDevices[1]), - eq(BluetoothProfile.PRIORITY_AUTO_CONNECT)); + verify(mHeadsetService, times(0)) + .setConnectionPolicy( + eq(testDevices[1]), eq(BluetoothProfile.PRIORITY_AUTO_CONNECT)); verify(mA2dpService, times(0)).setConnectionPolicy(eq(testDevices[1]), anyInt()); verify(mHeadsetService, times(0)).setConnectionPolicy(eq(testDevices[2]), anyInt()); verify(mA2dpService, times(0)).setConnectionPolicy(eq(testDevices[2]), anyInt()); @@ -1361,18 +1404,21 @@ public class PhonePolicyTest { // Generate connection state changed for A2DP for testDevices[2] and trigger // auto-connect for HFP. - updateProfileConnectionStateHelper(testDevices[2], BluetoothProfile.A2DP, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + updateProfileConnectionStateHelper( + testDevices[2], + BluetoothProfile.A2DP, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTED); // Check that we get a call to HFP connect - verify(mHeadsetService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)).connect( - eq(testDevices[2])); + verify(mHeadsetService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)) + .connect(eq(testDevices[2])); // testDevices[2] auto-connect completed for HFP hsConnectedDevices.add(testDevices[2]); when(mHeadsetService.getConnectedDevices()).thenReturn(hsConnectedDevices); - when(mHeadsetService.getConnectionState(testDevices[2])).thenReturn( - BluetoothProfile.STATE_CONNECTED); + when(mHeadsetService.getConnectionState(testDevices[2])) + .thenReturn(BluetoothProfile.STATE_CONNECTED); // Check the connect priorities for all devices // - testDevices[0] - connected for HFP and A2DP: setConnectionPolicy() should not be called @@ -1387,16 +1433,15 @@ public class PhonePolicyTest { verify(mHeadsetService, times(0)).setConnectionPolicy(eq(testDevices[1]), anyInt()); verify(mA2dpService, times(0)).setConnectionPolicy(eq(testDevices[1]), anyInt()); verify(mHeadsetService, times(0)).setConnectionPolicy(eq(testDevices[2]), anyInt()); - verify(mA2dpService, times(0)).setConnectionPolicy(eq(testDevices[2]), - eq(BluetoothProfile.PRIORITY_AUTO_CONNECT)); + verify(mA2dpService, times(0)) + .setConnectionPolicy( + eq(testDevices[2]), eq(BluetoothProfile.PRIORITY_AUTO_CONNECT)); verify(mHeadsetService, times(0)).setConnectionPolicy(eq(testDevices[3]), anyInt()); verify(mA2dpService, times(0)).setConnectionPolicy(eq(testDevices[3]), anyInt()); clearInvocations(mHeadsetService, mA2dpService); } - /** - * Test that we will not try to reconnect on a profile if all the connections failed - */ + /** Test that we will not try to reconnect on a profile if all the connections failed */ @Test public void testNoReconnectOnNoConnect() { // Return a list of bonded devices (just one) @@ -1406,10 +1451,10 @@ public class PhonePolicyTest { // Return PRIORITY_AUTO_CONNECT over HFP and A2DP. This would imply that the profiles are // auto-connectable. - when(mHeadsetService.getConnectionPolicy(bondedDevices[0])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(bondedDevices[0])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(bondedDevices[0])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(bondedDevices[0])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mAdapterService.getState()).thenReturn(BluetoothAdapter.STATE_ON); @@ -1418,23 +1463,23 @@ public class PhonePolicyTest { when(mA2dpService.getConnectedDevices()).thenReturn(Collections.emptyList()); // Both A2DP and HFP should say this device is not connected, except for the intent - when(mA2dpService.getConnectionState(bondedDevices[0])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - when(mHeadsetService.getConnectionState(bondedDevices[0])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(bondedDevices[0])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mHeadsetService.getConnectionState(bondedDevices[0])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); mPhonePolicy.handleAclConnected(bondedDevices[0]); waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); // Check that we don't get any calls to reconnect - verify(mA2dpService, after(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS).never()).connect( - eq(bondedDevices[0])); + verify(mA2dpService, after(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS).never()) + .connect(eq(bondedDevices[0])); verify(mHeadsetService, never()).connect(eq(bondedDevices[0])); } /** - * Test that we will not try to reconnect on a profile if all the connections failed - * with multiple devices + * Test that we will not try to reconnect on a profile if all the connections failed with + * multiple devices */ @Test public void testNoReconnectOnNoConnect_MultiDevice() { @@ -1446,32 +1491,32 @@ public class PhonePolicyTest { // Return PRIORITY_AUTO_CONNECT over HFP and A2DP. This would imply that the profiles are // auto-connectable. - when(mHeadsetService.getConnectionPolicy(bondedDevices[0])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(bondedDevices[0])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mHeadsetService.getConnectionPolicy(bondedDevices[1])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(bondedDevices[1])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(bondedDevices[0])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(bondedDevices[0])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(bondedDevices[1])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(bondedDevices[1])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mAdapterService.getState()).thenReturn(BluetoothAdapter.STATE_ON); // Return an a list with only the second device as connected - when(mHeadsetService.getConnectedDevices()).thenReturn( - Collections.singletonList(bondedDevices[1])); - when(mA2dpService.getConnectedDevices()).thenReturn( - Collections.singletonList(bondedDevices[1])); + when(mHeadsetService.getConnectedDevices()) + .thenReturn(Collections.singletonList(bondedDevices[1])); + when(mA2dpService.getConnectedDevices()) + .thenReturn(Collections.singletonList(bondedDevices[1])); // Both A2DP and HFP should say this device is not connected, except for the intent - when(mA2dpService.getConnectionState(bondedDevices[0])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - when(mHeadsetService.getConnectionState(bondedDevices[0])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - when(mA2dpService.getConnectionState(bondedDevices[1])).thenReturn( - BluetoothProfile.STATE_CONNECTED); - when(mHeadsetService.getConnectionState(bondedDevices[1])).thenReturn( - BluetoothProfile.STATE_CONNECTED); + when(mA2dpService.getConnectionState(bondedDevices[0])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mHeadsetService.getConnectionState(bondedDevices[0])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(bondedDevices[1])) + .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mHeadsetService.getConnectionState(bondedDevices[1])) + .thenReturn(BluetoothProfile.STATE_CONNECTED); // ACL is connected for both devices. when(mAdapterService.getConnectionState(bondedDevices[0])) @@ -1485,8 +1530,8 @@ public class PhonePolicyTest { waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); // Check that we don't get any calls to reconnect - verify(mA2dpService, after(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS).never()).connect( - eq(bondedDevices[0])); + verify(mA2dpService, after(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS).never()) + .connect(eq(bondedDevices[0])); verify(mHeadsetService, never()).connect(eq(bondedDevices[0])); } @@ -1503,29 +1548,29 @@ public class PhonePolicyTest { // Return PRIORITY_AUTO_CONNECT over HFP and A2DP. This would imply that the profiles are // auto-connectable. - when(mHeadsetService.getConnectionPolicy(bondedDevices[0])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(bondedDevices[0])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mHeadsetService.getConnectionPolicy(bondedDevices[1])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mA2dpService.getConnectionPolicy(bondedDevices[1])).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(bondedDevices[0])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(bondedDevices[0])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getConnectionPolicy(bondedDevices[1])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mA2dpService.getConnectionPolicy(bondedDevices[1])) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mAdapterService.getState()).thenReturn(BluetoothAdapter.STATE_ON); // Return an a list with only the second device as connected - when(mHeadsetService.getConnectedDevices()).thenReturn( - Collections.singletonList(bondedDevices[1])); + when(mHeadsetService.getConnectedDevices()) + .thenReturn(Collections.singletonList(bondedDevices[1])); when(mA2dpService.getConnectedDevices()).thenReturn(Collections.emptyList()); // Both A2DP and HFP should say this device is not connected, except for the intent - when(mA2dpService.getConnectionState(bondedDevices[0])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - when(mHeadsetService.getConnectionState(bondedDevices[0])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); - when(mA2dpService.getConnectionState(bondedDevices[1])).thenReturn( - BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(bondedDevices[0])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mHeadsetService.getConnectionState(bondedDevices[0])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mA2dpService.getConnectionState(bondedDevices[1])) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED); // ACL is connected, lets simulate this. when(mAdapterService.getConnectionState(bondedDevices[1])) @@ -1533,8 +1578,11 @@ public class PhonePolicyTest { // We send a connection successful for one profile since the re-connect *only* works if we // have already connected successfully over one of the profiles - updateProfileConnectionStateHelper(bondedDevices[1], BluetoothProfile.HEADSET, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + updateProfileConnectionStateHelper( + bondedDevices[1], + BluetoothProfile.HEADSET, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTED); // Check that we do get A2DP call to reconnect, because HEADSET just got connected verify(mA2dpService, timeout(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS)) @@ -1560,15 +1608,14 @@ public class PhonePolicyTest { mPhonePolicy.onUuidsDiscovered(device, null); // Check that we do not crash and not call any setPriority methods - verify(mHeadsetService, - after(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS).never()) + verify(mHeadsetService, after(CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS).never()) .setConnectionPolicy(eq(device), eq(BluetoothProfile.CONNECTION_POLICY_ALLOWED)); verify(mA2dpService, never()) .setConnectionPolicy(eq(device), eq(BluetoothProfile.CONNECTION_POLICY_ALLOWED)); } - private void updateProfileConnectionStateHelper(BluetoothDevice device, int profileId, - int nextState, int prevState) { + private void updateProfileConnectionStateHelper( + BluetoothDevice device, int profileId, int nextState, int prevState) { switch (profileId) { case BluetoothProfile.A2DP: when(mA2dpService.getConnectionState(device)).thenReturn(nextState); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/ProfileServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/ProfileServiceTest.java index fb4d3122efa..5755864ef80 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/ProfileServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/ProfileServiceTest.java @@ -130,7 +130,6 @@ public class ProfileServiceTest { } Assert.assertNotNull(Looper.myLooper()); - doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); doNothing().when(mAdapterService).addProfile(any()); doNothing().when(mAdapterService).removeProfile(any()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java index 5cbd92d4b3a..ec1e9774501 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java @@ -67,8 +67,9 @@ public class RemoteDevicesTest { mDevice1 = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(TEST_BT_ADDR_1); mHandlerThread = new HandlerThread("RemoteDevicesTestHandlerThread"); mHandlerThread.start(); - mTestLooperManager = InstrumentationRegistry.getInstrumentation() - .acquireLooperManager(mHandlerThread.getLooper()); + mTestLooperManager = + InstrumentationRegistry.getInstrumentation() + .acquireLooperManager(mHandlerThread.getLooper()); mBluetoothManager = mTargetContext.getSystemService(BluetoothManager.class); when(mAdapterService.getSystemService(Context.BLUETOOTH_SERVICE)) @@ -111,32 +112,34 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify that user can get battery level after the update Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), - batteryLevel); + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); // Verify that update same battery level for the same device does not trigger intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); verify(mAdapterService).sendBroadcast(any(), anyString(), any()); // Verify that updating battery level to different value triggers the intent again batteryLevel = 15; - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService, times(2)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService, times(2)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); // Verify that user can get battery level after the update - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), - batteryLevel); + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); verifyNoMoreInteractions(mAdapterService); } @@ -149,7 +152,7 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating with invalid battery level does not trigger the intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); verify(mAdapterService, never()).sendBroadcast(any(), anyString(), any()); // Verify that device property stays null after invalid update @@ -166,7 +169,7 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating invalid battery level does not trigger the intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); verify(mAdapterService, never()).sendBroadcast(any(), anyString(), any()); // Verify that device property stays null after invalid update @@ -181,7 +184,7 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that resetting battery level keeps device property null - mRemoteDevices.resetBatteryLevel(mDevice1, /*fromBas=*/ false); + mRemoteDevices.resetBatteryLevel(mDevice1, /* fromBas= */ false); Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); verifyNoMoreInteractions(mAdapterService); @@ -195,40 +198,43 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify that user can get battery level after the update Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), - batteryLevel); + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); // Verify that resetting battery level changes it back to BluetoothDevice // .BATTERY_LEVEL_UNKNOWN - mRemoteDevices.resetBatteryLevel(mDevice1, /*fromBas=*/ false); + mRemoteDevices.resetBatteryLevel(mDevice1, /* fromBas= */ false); // Verify BATTERY_LEVEL_CHANGED intent is sent after first reset - verify(mAdapterService, times(2)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); - verifyBatteryLevelChangedIntent(mDevice1, BluetoothDevice.BATTERY_LEVEL_UNKNOWN, - mIntentArgument); + verify(mAdapterService, times(2)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); + verifyBatteryLevelChangedIntent( + mDevice1, BluetoothDevice.BATTERY_LEVEL_UNKNOWN, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify value is reset in properties Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), BluetoothDevice.BATTERY_LEVEL_UNKNOWN); // Verify no intent is sent after second reset - mRemoteDevices.resetBatteryLevel(mDevice1, /*fromBas=*/ false); - verify(mAdapterService, times(2)).sendBroadcast(any(), anyString(), - any()); + mRemoteDevices.resetBatteryLevel(mDevice1, /* fromBas= */ false); + verify(mAdapterService, times(2)).sendBroadcast(any(), anyString(), any()); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent again - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService, times(3)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService, times(3)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); @@ -243,16 +249,17 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify that user can get battery level after the update Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), - batteryLevel); + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); // Verify that resetting battery level changes it back to BluetoothDevice // .BATTERY_LEVEL_UNKNOWN @@ -261,20 +268,23 @@ public class RemoteDevicesTest { BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED); // Verify BATTERY_LEVEL_CHANGED intent is sent after first reset - verify(mAdapterService, times(2)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); - verifyBatteryLevelChangedIntent(mDevice1, BluetoothDevice.BATTERY_LEVEL_UNKNOWN, - mIntentArgument); + verify(mAdapterService, times(2)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); + verifyBatteryLevelChangedIntent( + mDevice1, BluetoothDevice.BATTERY_LEVEL_UNKNOWN, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify value is reset in properties Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), BluetoothDevice.BATTERY_LEVEL_UNKNOWN); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent again - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService, times(3)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService, times(3)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); @@ -292,16 +302,17 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify that user can get battery level after the update Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), - batteryLevel); + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); // Verify that battery level is not reset mRemoteDevices.onHeadsetConnectionStateChanged( @@ -310,8 +321,8 @@ public class RemoteDevicesTest { BluetoothProfile.STATE_DISCONNECTED); Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(batteryLevel, - mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); + Assert.assertEquals( + batteryLevel, mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); // Recover the previous battery service if exists clearBatteryServiceForTesting(oldBatteryService); @@ -328,43 +339,54 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify that user can get battery level after the update Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(batteryLevel, - mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); + Assert.assertEquals( + batteryLevel, mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); // Verify that when device is completely disconnected, RemoteDevices reset battery level to // BluetoothDevice.BATTERY_LEVEL_UNKNOWN when(mAdapterService.getState()).thenReturn(BluetoothAdapter.STATE_ON); - mRemoteDevices.aclStateChangeCallback(0, Utils.getByteAddress(mDevice1), - AbstractionLayer.BT_ACL_STATE_DISCONNECTED, 2, 19, + mRemoteDevices.aclStateChangeCallback( + 0, + Utils.getByteAddress(mDevice1), + AbstractionLayer.BT_ACL_STATE_DISCONNECTED, + 2, + 19, BluetoothDevice.ERROR); // HCI code 19 remote terminated // Verify ACTION_ACL_DISCONNECTED and BATTERY_LEVEL_CHANGED intent are sent - verify(mAdapterService, times(3)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); + verify(mAdapterService, times(3)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verify(mAdapterService, times(2)).obfuscateAddress(mDevice1); - verifyBatteryLevelChangedIntent(mDevice1, BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + verifyBatteryLevelChangedIntent( + mDevice1, + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); - Assert.assertEquals(BLUETOOTH_CONNECT, + Assert.assertEquals( + BLUETOOTH_CONNECT, mStringArgument.getAllValues().get(mStringArgument.getAllValues().size() - 2)); - Assert.assertEquals(BluetoothDevice.ACTION_ACL_DISCONNECTED, - mIntentArgument.getValue().getAction()); + Assert.assertEquals( + BluetoothDevice.ACTION_ACL_DISCONNECTED, mIntentArgument.getValue().getAction()); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify value is reset in properties Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent again - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService, times(4)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService, times(4)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); } @@ -379,8 +401,9 @@ public class RemoteDevicesTest { // Verify that ACTION_HF_INDICATORS_VALUE_CHANGED intent updates battery level mRemoteDevices.onHfIndicatorValueChanged( mDevice1, HeadsetHalConstants.HF_INDICATOR_BATTERY_LEVEL_STATUS, batteryLevel); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); } @@ -411,8 +434,9 @@ public class RemoteDevicesTest { BluetoothAssignedNumbers.PLANTRONICS, BluetoothHeadset.AT_CMD_TYPE_SET, getXEventArray(3, 8)); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, 42, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); } @@ -437,8 +461,9 @@ public class RemoteDevicesTest { 3, 10 }); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, 60, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); } @@ -446,67 +471,101 @@ public class RemoteDevicesTest { @Test public void testGetBatteryLevelFromXEventVsc() { Assert.assertEquals(42, RemoteDevices.getBatteryLevelFromXEventVsc(getXEventArray(3, 8))); - Assert.assertEquals(100, - RemoteDevices.getBatteryLevelFromXEventVsc(getXEventArray(10, 11))); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + Assert.assertEquals( + 100, RemoteDevices.getBatteryLevelFromXEventVsc(getXEventArray(10, 11))); + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, RemoteDevices.getBatteryLevelFromXEventVsc(getXEventArray(1, 1))); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, RemoteDevices.getBatteryLevelFromXEventVsc(getXEventArray(3, 1))); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, RemoteDevices.getBatteryLevelFromXEventVsc(getXEventArray(-1, 1))); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, RemoteDevices.getBatteryLevelFromXEventVsc(getXEventArray(-1, -1))); } @Test public void testGetBatteryLevelFromAppleBatteryVsc() { - Assert.assertEquals(10, RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[]{ - 1, BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, 0 - })); - Assert.assertEquals(100, RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[]{ - 1, BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, 9 - })); - Assert.assertEquals(60, RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[]{ - 3, - BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, - 5, - 2, - 1, - 3, - 10 - })); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, - RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[]{ - 3, - BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, - 5, - 2, - 1, - 3 - })); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, - RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[]{ - 1, - BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, - 10 - })); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, - RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[]{ - 1, - BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, - -1 - })); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, - RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[]{ - 1, - BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, - "5" - })); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, - RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[]{1, 35, 37})); - Assert.assertEquals(BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + Assert.assertEquals( + 10, + RemoteDevices.getBatteryLevelFromAppleBatteryVsc( + new Object[] { + 1, + BluetoothHeadset + .VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + 0 + })); + Assert.assertEquals( + 100, + RemoteDevices.getBatteryLevelFromAppleBatteryVsc( + new Object[] { + 1, + BluetoothHeadset + .VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + 9 + })); + Assert.assertEquals( + 60, + RemoteDevices.getBatteryLevelFromAppleBatteryVsc( + new Object[] { + 3, + BluetoothHeadset + .VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + 5, + 2, + 1, + 3, + 10 + })); + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + RemoteDevices.getBatteryLevelFromAppleBatteryVsc( + new Object[] { + 3, + BluetoothHeadset + .VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + 5, + 2, + 1, + 3 + })); + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + RemoteDevices.getBatteryLevelFromAppleBatteryVsc( + new Object[] { + 1, + BluetoothHeadset + .VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + 10 + })); + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + RemoteDevices.getBatteryLevelFromAppleBatteryVsc( + new Object[] { + 1, + BluetoothHeadset + .VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + -1 + })); + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + RemoteDevices.getBatteryLevelFromAppleBatteryVsc( + new Object[] { + 1, + BluetoothHeadset + .VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + "5" + })); + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + RemoteDevices.getBatteryLevelFromAppleBatteryVsc(new Object[] {1, 35, 37})); + Assert.assertEquals( + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, RemoteDevices.getBatteryLevelFromAppleBatteryVsc( - new Object[]{1, "WRONG", "WRONG"})); + new Object[] {1, "WRONG", "WRONG"})); } @Test @@ -517,16 +576,17 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify that user can get battery level after the update Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), - batteryLevel); + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); // Verify that resetting battery level changes it back to BluetoothDevice // .BATTERY_LEVEL_UNKNOWN @@ -536,21 +596,24 @@ public class RemoteDevicesTest { BluetoothProfile.STATE_DISCONNECTED); // Verify BATTERY_LEVEL_CHANGED intent is sent after first reset - verify(mAdapterService, times(2)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); - verifyBatteryLevelChangedIntent(mDevice1, BluetoothDevice.BATTERY_LEVEL_UNKNOWN, - mIntentArgument); + verify(mAdapterService, times(2)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); + verifyBatteryLevelChangedIntent( + mDevice1, BluetoothDevice.BATTERY_LEVEL_UNKNOWN, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify value is reset in properties Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), BluetoothDevice.BATTERY_LEVEL_UNKNOWN); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent again - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService, times(3)).sendBroadcast(mIntentArgument.capture(), - mStringArgument.capture(), any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService, times(3)) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); @@ -568,16 +631,17 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel, mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); // Verify that user can get battery level after the update Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), - batteryLevel); + Assert.assertEquals( + mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); // Verify that battery level is not reset. mRemoteDevices.onHeadsetClientConnectionStateChanged( @@ -586,8 +650,8 @@ public class RemoteDevicesTest { BluetoothProfile.STATE_DISCONNECTED); Assert.assertNotNull(mRemoteDevices.getDeviceProperties(mDevice1)); - Assert.assertEquals(batteryLevel, - mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); + Assert.assertEquals( + batteryLevel, mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); clearBatteryServiceForTesting(oldBatteryService); @@ -606,7 +670,7 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); verify(mAdapterService) .sendBroadcast( mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); @@ -619,14 +683,14 @@ public class RemoteDevicesTest { mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); // Verify that updating battery service overrides hfp battery level - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel2, /*fromBas=*/ true); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel2, /* fromBas= */ true); verify(mAdapterService, times(2)) .sendBroadcast( mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); verifyBatteryLevelChangedIntent(mDevice1, batteryLevel2, mIntentArgument); // Verify that the battery level isn't reset - mRemoteDevices.resetBatteryLevel(mDevice1, /*fromBas=*/ true); + mRemoteDevices.resetBatteryLevel(mDevice1, /* fromBas= */ true); Assert.assertEquals( batteryLevel, mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); verify(mAdapterService, times(3)) @@ -650,7 +714,7 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(mDevice1)); // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ false); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ false); verify(mAdapterService) .sendBroadcast( mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); @@ -663,11 +727,11 @@ public class RemoteDevicesTest { mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel(), batteryLevel); // Verify that updating battery service doesn't send broadcast - mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /*fromBas=*/ true); + mRemoteDevices.updateBatteryLevel(mDevice1, batteryLevel, /* fromBas= */ true); verifyNoMoreInteractions(mAdapterService); // Verify that the battery level isn't reset - mRemoteDevices.resetBatteryLevel(mDevice1, /*fromBas=*/ true); + mRemoteDevices.resetBatteryLevel(mDevice1, /* fromBas= */ true); Assert.assertEquals( batteryLevel, mRemoteDevices.getDeviceProperties(mDevice1).getBatteryLevel()); verifyNoMoreInteractions(mAdapterService); @@ -686,10 +750,13 @@ public class RemoteDevicesTest { // Verify that ACTION_AG_EVENT intent updates battery level mRemoteDevices.onAgBatteryLevelChanged(mDevice1, batteryLevel); - verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(), - any(Bundle.class)); - verifyBatteryLevelChangedIntent(mDevice1, - RemoteDevices.batteryChargeIndicatorToPercentge(batteryLevel), mIntentArgument); + verify(mAdapterService) + .sendBroadcast( + mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class)); + verifyBatteryLevelChangedIntent( + mDevice1, + RemoteDevices.batteryChargeIndicatorToPercentge(batteryLevel), + mIntentArgument); Assert.assertEquals(BLUETOOTH_CONNECT, mStringArgument.getValue()); } @@ -701,16 +768,19 @@ public class RemoteDevicesTest { mRemoteDevices.addDeviceProperties(Utils.getBytesFromAddress(TEST_BT_ADDR_1)); DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(mDevice1); - BluetoothSinkAudioPolicy policies = new BluetoothSinkAudioPolicy.Builder() - .setCallEstablishPolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .setActiveDevicePolicyAfterConnection(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .setInBandRingtonePolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .build(); + BluetoothSinkAudioPolicy policies = + new BluetoothSinkAudioPolicy.Builder() + .setCallEstablishPolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .setActiveDevicePolicyAfterConnection( + BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .setInBandRingtonePolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .build(); deviceProp.setHfAudioPolicyForRemoteAg(policies); // Verify that the audio policy properties are set and get propperly - Assert.assertEquals(policies, mRemoteDevices.getDeviceProperties(mDevice1) - .getHfAudioPolicyForRemoteAg()); + Assert.assertEquals( + policies, + mRemoteDevices.getDeviceProperties(mDevice1).getHfAudioPolicyForRemoteAg()); } @Test @@ -750,20 +820,21 @@ public class RemoteDevicesTest { Assert.assertNull(mRemoteDevices.getDeviceProperties(null)); } - - private static void verifyBatteryLevelChangedIntent(BluetoothDevice device, int batteryLevel, - ArgumentCaptor intentArgument) { + private static void verifyBatteryLevelChangedIntent( + BluetoothDevice device, int batteryLevel, ArgumentCaptor intentArgument) { verifyBatteryLevelChangedIntent(device, batteryLevel, intentArgument.getValue()); } - private static void verifyBatteryLevelChangedIntent(BluetoothDevice device, int batteryLevel, - Intent intent) { + private static void verifyBatteryLevelChangedIntent( + BluetoothDevice device, int batteryLevel, Intent intent) { Assert.assertEquals(BluetoothDevice.ACTION_BATTERY_LEVEL_CHANGED, intent.getAction()); Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); - Assert.assertEquals(batteryLevel, - intent.getIntExtra(BluetoothDevice.EXTRA_BATTERY_LEVEL, -15)); - Assert.assertEquals(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT - | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, intent.getFlags()); + Assert.assertEquals( + batteryLevel, intent.getIntExtra(BluetoothDevice.EXTRA_BATTERY_LEVEL, -15)); + Assert.assertEquals( + Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT + | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, + intent.getFlags()); } private static Object[] getXEventArray(int batteryLevel, int numLevels) { @@ -778,8 +849,7 @@ public class RemoteDevicesTest { private static BatteryService setBatteryServiceForTesting(BluetoothDevice device) { BatteryService newService = mock(BatteryService.class); - when(newService.getConnectionState(device)) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(newService.getConnectionState(device)).thenReturn(BluetoothProfile.STATE_CONNECTED); when(newService.isAvailable()).thenReturn(true); BatteryService oldService = BatteryService.getBatteryService(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java index 36be66af702..398b29d5ef6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java @@ -68,7 +68,6 @@ public class SilenceDeviceManagerTest { @Mock private A2dpService mA2dpService; @Mock private HeadsetService mHeadsetService; - @Before public void setUp() throws Exception { mContext = InstrumentationRegistry.getTargetContext(); @@ -83,8 +82,7 @@ public class SilenceDeviceManagerTest { mHandlerThread = new HandlerThread("SilenceManagerTestHandlerThread"); mHandlerThread.start(); mLooper = mHandlerThread.getLooper(); - mSilenceDeviceManager = new SilenceDeviceManager(mAdapterService, mServiceFactory, - mLooper); + mSilenceDeviceManager = new SilenceDeviceManager(mAdapterService, mServiceFactory, mLooper); mSilenceDeviceManager.start(); } @@ -119,9 +117,10 @@ public class SilenceDeviceManagerTest { if (wasSilenced) { Assert.assertTrue(mSilenceDeviceManager.setSilenceMode(mTestDevice, true)); TestUtils.waitForLooperToFinishScheduledTask(mLooper); - verify(mAdapterService, times(++mVerifyCount)).sendBroadcastAsUser( - intentArgument.capture(), eq(UserHandle.ALL), - eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify(mAdapterService, times(++mVerifyCount)) + .sendBroadcastAsUser( + intentArgument.capture(), eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), any(Bundle.class)); } // Set silence state and check whether state changed successfully @@ -131,9 +130,10 @@ public class SilenceDeviceManagerTest { // Check for silence state changed intent if (wasSilenced != enableSilence) { - verify(mAdapterService, times(++mVerifyCount)).sendBroadcastAsUser( - intentArgument.capture(), eq(UserHandle.ALL), - eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify(mAdapterService, times(++mVerifyCount)) + .sendBroadcastAsUser( + intentArgument.capture(), eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), any(Bundle.class)); verifySilenceStateIntent(intentArgument.getValue()); } @@ -145,9 +145,10 @@ public class SilenceDeviceManagerTest { if (enableSilence) { // If the silence mode is enabled, it should be automatically disabled // after device is disconnected. - verify(mAdapterService, times(++mVerifyCount)).sendBroadcastAsUser( - intentArgument.capture(), eq(UserHandle.ALL), - eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify(mAdapterService, times(++mVerifyCount)) + .sendBroadcastAsUser( + intentArgument.capture(), eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), any(Bundle.class)); } } @@ -159,9 +160,10 @@ public class SilenceDeviceManagerTest { Assert.assertFalse(mSilenceDeviceManager.getSilenceMode(mTestDevice)); // Should be no intent been broadcasted - verify(mAdapterService, times(mVerifyCount)).sendBroadcastAsUser( - intentArgument.capture(), eq(UserHandle.ALL), - eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify(mAdapterService, times(mVerifyCount)) + .sendBroadcastAsUser( + intentArgument.capture(), eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), any(Bundle.class)); } void verifySilenceStateIntent(Intent intent) { @@ -169,36 +171,28 @@ public class SilenceDeviceManagerTest { Assert.assertEquals(mTestDevice, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); } - /** - * Helper to indicate A2dp connected for a device. - */ + /** Helper to indicate A2dp connected for a device. */ private void a2dpConnected(BluetoothDevice device) { mSilenceDeviceManager.a2dpConnectionStateChanged( device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); TestUtils.waitForLooperToFinishScheduledTask(mLooper); } - /** - * Helper to indicate A2dp disconnected for a device. - */ + /** Helper to indicate A2dp disconnected for a device. */ private void a2dpDisconnected(BluetoothDevice device) { mSilenceDeviceManager.a2dpConnectionStateChanged( device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); TestUtils.waitForLooperToFinishScheduledTask(mLooper); } - /** - * Helper to indicate Headset connected for a device. - */ + /** Helper to indicate Headset connected for a device. */ private void headsetConnected(BluetoothDevice device) { mSilenceDeviceManager.hfpConnectionStateChanged( device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); TestUtils.waitForLooperToFinishScheduledTask(mLooper); } - /** - * Helper to indicate Headset disconnected for a device. - */ + /** Helper to indicate Headset disconnected for a device. */ private void headsetDisconnected(BluetoothDevice device) { mSilenceDeviceManager.hfpConnectionStateChanged( device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java index ae60fb4d7e5..09c7d4340f1 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java @@ -63,63 +63,71 @@ public final class BluetoothKeystoreServiceTest { "/data/misc/bluedroid/bt_config.checksum.encrypted"; // bt_config file test content. - private final List mConfigTestData = List.of("[Info]", - "FileSource = Empty", - "TimeCreated = XXXX-XX-XX XX:XX:XX", - "", - "[Metrics]", - "Salt256Bit = aaaaaaaaaaaaaaaaaaa", - "", - "[Adapter]", - "Address = 11:22:33:44:55:66", - "LE_LOCAL_KEY_IRK = IRK1234567890", - "LE_LOCAL_KEY_IR = IR1234567890", - "LE_LOCAL_KEY_DHK = DHK1234567890", - "LE_LOCAL_KEY_ER = ER1234567890", - "ScanMode = 0", - "DiscoveryTimeout = 120", - "", - "[aa:bb:cc:dd:ee:ff]", - "Timestamp = 12345678", - "Name = Test", - "DevClass = 1234567", - "LinkKey = 11223344556677889900aabbccddeeff", - "LE_KEY_PENC = ec111111111111111111111111111111111111111111111111111111", - "LE_KEY_PID = d222222222222222222222222222222222222222222222", - "LE_KEY_PCSRK = c33333333333333333333333333333333333333333333333", - "LE_KEY_LENC = eec4444444444444444444444444444444444444", - "LE_KEY_LCSRK = aec555555555555555555555555555555555555555555555", - "LE_KEY_LID =" - ); - - private final List mConfigTestDataForOldEncryptedFile = List.of("[Info]", - "FileSource = Empty", - "TimeCreated = XXXX-XX-XX XX:XX:XX", - "", - "[Metrics]", - "Salt256Bit = aaaaaaaaaaaaaaaaaaa", - "", - "[Adapter]", - "Address = 11:22:33:44:55:66", - "LE_LOCAL_KEY_IRK = IRK1234567890", - "LE_LOCAL_KEY_IR = IR1234567890", - "LE_LOCAL_KEY_DHK = DHK1234567890", - "LE_LOCAL_KEY_ER = ER1234567890", - "ScanMode = 0", - "DiscoveryTimeout = 120", - "", - "[aa:bb:cc:dd:ee:ff]", - "Timestamp = 12345678", - "Name = Test", - "DevClass = 1234567", - "LinkKey = CgzgWAk2ROa2cjknZhsaMIPzf20MvCRx2QeAHycQ7gFy9LnVi9FYs/PodOfl+FP5YkXP/WHkY4", - "LE_KEY_PENC = CgwomFvDc/IuhOeoTn8aSPHqDneIZJ7aszhKQPorqeDPF50cytW4I/LzmdNvMeVX0qBsuh", - "LE_KEY_PID = Cgxu7Z7sXniNj3ija1waPkvHCLH4gnttOyb0OZjiJj+xH3KvtfDh6k2wbgGcGTLe9pYS4EX", - "LE_KEY_PCSRK = Cgx5t1PkIm8ohz9BLzYaQOsrmZakN77CMgbWeBIqT8bW6bQhK1JZYpp3qWZVM8HM3y09h", - "LE_KEY_LENC = CgytzELdVX+QptdzuuMaOLDiNuzn7BNK9OmPNHYspp4ojThTA/5iWBxrZV6E3qZydLyNHk", - "LE_KEY_LCSRK = CgydDaLIr/pSx1/eoPEaQEZN2BDpSJPjOSiJWwDBkMkgIpf/YmfxB6rUB8EXHkC+9eSy4", - "LE_KEY_LID =" - ); + private final List mConfigTestData = + List.of( + "[Info]", + "FileSource = Empty", + "TimeCreated = XXXX-XX-XX XX:XX:XX", + "", + "[Metrics]", + "Salt256Bit = aaaaaaaaaaaaaaaaaaa", + "", + "[Adapter]", + "Address = 11:22:33:44:55:66", + "LE_LOCAL_KEY_IRK = IRK1234567890", + "LE_LOCAL_KEY_IR = IR1234567890", + "LE_LOCAL_KEY_DHK = DHK1234567890", + "LE_LOCAL_KEY_ER = ER1234567890", + "ScanMode = 0", + "DiscoveryTimeout = 120", + "", + "[aa:bb:cc:dd:ee:ff]", + "Timestamp = 12345678", + "Name = Test", + "DevClass = 1234567", + "LinkKey = 11223344556677889900aabbccddeeff", + "LE_KEY_PENC = ec111111111111111111111111111111111111111111111111111111", + "LE_KEY_PID = d222222222222222222222222222222222222222222222", + "LE_KEY_PCSRK = c33333333333333333333333333333333333333333333333", + "LE_KEY_LENC = eec4444444444444444444444444444444444444", + "LE_KEY_LCSRK = aec555555555555555555555555555555555555555555555", + "LE_KEY_LID ="); + + private final List mConfigTestDataForOldEncryptedFile = + List.of( + "[Info]", + "FileSource = Empty", + "TimeCreated = XXXX-XX-XX XX:XX:XX", + "", + "[Metrics]", + "Salt256Bit = aaaaaaaaaaaaaaaaaaa", + "", + "[Adapter]", + "Address = 11:22:33:44:55:66", + "LE_LOCAL_KEY_IRK = IRK1234567890", + "LE_LOCAL_KEY_IR = IR1234567890", + "LE_LOCAL_KEY_DHK = DHK1234567890", + "LE_LOCAL_KEY_ER = ER1234567890", + "ScanMode = 0", + "DiscoveryTimeout = 120", + "", + "[aa:bb:cc:dd:ee:ff]", + "Timestamp = 12345678", + "Name = Test", + "DevClass = 1234567", + "LinkKey =" + + " CgzgWAk2ROa2cjknZhsaMIPzf20MvCRx2QeAHycQ7gFy9LnVi9FYs/PodOfl+FP5YkXP/WHkY4", + "LE_KEY_PENC =" + + " CgwomFvDc/IuhOeoTn8aSPHqDneIZJ7aszhKQPorqeDPF50cytW4I/LzmdNvMeVX0qBsuh", + "LE_KEY_PID =" + + " Cgxu7Z7sXniNj3ija1waPkvHCLH4gnttOyb0OZjiJj+xH3KvtfDh6k2wbgGcGTLe9pYS4EX", + "LE_KEY_PCSRK =" + + " Cgx5t1PkIm8ohz9BLzYaQOsrmZakN77CMgbWeBIqT8bW6bQhK1JZYpp3qWZVM8HM3y09h", + "LE_KEY_LENC =" + + " CgytzELdVX+QptdzuuMaOLDiNuzn7BNK9OmPNHYspp4ojThTA/5iWBxrZV6E3qZydLyNHk", + "LE_KEY_LCSRK =" + + " CgydDaLIr/pSx1/eoPEaQEZN2BDpSJPjOSiJWwDBkMkgIpf/YmfxB6rUB8EXHkC+9eSy4", + "LE_KEY_LID ="); private List mConfigData = new ArrayList<>(); @@ -170,17 +178,19 @@ public final class BluetoothKeystoreServiceTest { } private void createNameDecryptKeyResult() { - mNameDecryptKeyResult.put("aa:bb:cc:dd:ee:ff-LinkKey", - "11223344556677889900aabbccddeeff"); - mNameDecryptKeyResult.put("aa:bb:cc:dd:ee:ff-LE_KEY_PENC", + mNameDecryptKeyResult.put("aa:bb:cc:dd:ee:ff-LinkKey", "11223344556677889900aabbccddeeff"); + mNameDecryptKeyResult.put( + "aa:bb:cc:dd:ee:ff-LE_KEY_PENC", "ec111111111111111111111111111111111111111111111111111111"); - mNameDecryptKeyResult.put("aa:bb:cc:dd:ee:ff-LE_KEY_PID", - "d222222222222222222222222222222222222222222222"); - mNameDecryptKeyResult.put("aa:bb:cc:dd:ee:ff-LE_KEY_PCSRK", + mNameDecryptKeyResult.put( + "aa:bb:cc:dd:ee:ff-LE_KEY_PID", "d222222222222222222222222222222222222222222222"); + mNameDecryptKeyResult.put( + "aa:bb:cc:dd:ee:ff-LE_KEY_PCSRK", "c33333333333333333333333333333333333333333333333"); - mNameDecryptKeyResult.put("aa:bb:cc:dd:ee:ff-LE_KEY_LENC", - "eec4444444444444444444444444444444444444"); - mNameDecryptKeyResult.put("aa:bb:cc:dd:ee:ff-LE_KEY_LCSRK", + mNameDecryptKeyResult.put( + "aa:bb:cc:dd:ee:ff-LE_KEY_LENC", "eec4444444444444444444444444444444444444"); + mNameDecryptKeyResult.put( + "aa:bb:cc:dd:ee:ff-LE_KEY_LCSRK", "aec555555555555555555555555555555555555555555555"); } @@ -234,8 +244,8 @@ public final class BluetoothKeystoreServiceTest { // load config file. Assert.assertTrue(parseConfigFile(CONFIG_FILE_PATH)); // make sure it is same with createNameDecryptKeyResult - Assert.assertTrue(doCompareMap(mNameDecryptKeyResult, - mBluetoothKeystoreService.getNameDecryptKey())); + Assert.assertTrue( + doCompareMap(mNameDecryptKeyResult, mBluetoothKeystoreService.getNameDecryptKey())); } @Test @@ -245,8 +255,9 @@ public final class BluetoothKeystoreServiceTest { // Wait for encryption to complete mBluetoothKeystoreService.stopThread(); - Assert.assertTrue(doCompareKeySet(mNameDecryptKeyResult, - mBluetoothKeystoreService.getNameEncryptKey())); + Assert.assertTrue( + doCompareKeySet( + mNameDecryptKeyResult, mBluetoothKeystoreService.getNameEncryptKey())); } @Test @@ -261,8 +272,8 @@ public final class BluetoothKeystoreServiceTest { // Wait for encryption to complete mBluetoothKeystoreService.stopThread(); - Assert.assertTrue(doCompareMap(mNameDecryptKeyResult, - mBluetoothKeystoreService.getNameDecryptKey())); + Assert.assertTrue( + doCompareMap(mNameDecryptKeyResult, mBluetoothKeystoreService.getNameDecryptKey())); } @Test @@ -302,8 +313,8 @@ public final class BluetoothKeystoreServiceTest { mBluetoothKeystoreService.getNameDecryptKey().remove(CONFIG_FILE_PREFIX); mBluetoothKeystoreService.getNameDecryptKey().remove(CONFIG_BACKUP_PREFIX); - Assert.assertTrue(doCompareMap(mNameDecryptKeyResult, - mBluetoothKeystoreService.getNameDecryptKey())); + Assert.assertTrue( + doCompareMap(mNameDecryptKeyResult, mBluetoothKeystoreService.getNameDecryptKey())); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java index 94c1993b404..0973b2bd705 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java @@ -100,10 +100,12 @@ public final class DatabaseManagerTest { @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); @Rule - public MigrationTestHelper testHelper = new MigrationTestHelper( - InstrumentationRegistry.getInstrumentation(), - MetadataDatabase.class.getCanonicalName(), - new FrameworkSQLiteOpenHelperFactory()); + public MigrationTestHelper testHelper = + new MigrationTestHelper( + InstrumentationRegistry.getInstrumentation(), + MetadataDatabase.class.getCanonicalName(), + new FrameworkSQLiteOpenHelperFactory()); + @Before public void setUp() throws Exception { TestUtils.setAdapterService(mAdapterService); @@ -113,18 +115,19 @@ public final class DatabaseManagerTest { mTestDevice3 = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(TEST_BT_ADDR3); // Create a memory database for DatabaseManager instead of use a real database. - mDatabase = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getTargetContext(), - MetadataDatabase.class).build(); + mDatabase = + Room.inMemoryDatabaseBuilder( + InstrumentationRegistry.getTargetContext(), MetadataDatabase.class) + .build(); - when(mAdapterService.getPackageManager()).thenReturn( - InstrumentationRegistry.getTargetContext().getPackageManager()); + when(mAdapterService.getPackageManager()) + .thenReturn(InstrumentationRegistry.getTargetContext().getPackageManager()); mDatabaseManager = new DatabaseManager(mAdapterService); BluetoothDevice[] bondedDevices = {mTestDevice}; doReturn(bondedDevices).when(mAdapterService).getBondedDevices(); - doNothing().when(mAdapterService).metadataChanged( - anyString(), anyInt(), any(byte[].class)); + doNothing().when(mAdapterService).metadataChanged(anyString(), anyInt(), any(byte[].class)); restartDatabaseManagerHelper(); } @@ -143,15 +146,18 @@ public final class DatabaseManagerTest { restartDatabaseManagerHelper(); for (int id = 0; id < BluetoothProfile.MAX_PROFILE_ID; id++) { - Assert.assertEquals(BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + Assert.assertEquals( + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mDatabaseManager.getProfileConnectionPolicy(mTestDevice, id)); } - Assert.assertEquals(BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN, + Assert.assertEquals( + BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN, mDatabaseManager.getA2dpSupportsOptionalCodecs(mTestDevice)); - Assert.assertEquals(BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN, - mDatabaseManager.getA2dpOptionalCodecsEnabled(mTestDevice)); + Assert.assertEquals( + BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN, + mDatabaseManager.getA2dpOptionalCodecsEnabled(mTestDevice)); for (int id = 0; id < MAX_META_ID; id++) { Assert.assertNull(mDatabaseManager.getCustomMeta(mTestDevice, id)); @@ -168,24 +174,42 @@ public final class DatabaseManagerTest { int badConnectionPolicy = -100; // Cases of device not in database - testSetGetProfileConnectionPolicyCase(false, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true); - testSetGetProfileConnectionPolicyCase(false, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, true); - testSetGetProfileConnectionPolicyCase(false, BluetoothProfile.CONNECTION_POLICY_ALLOWED, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, true); - testSetGetProfileConnectionPolicyCase(false, badConnectionPolicy, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); + testSetGetProfileConnectionPolicyCase( + false, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + true); + testSetGetProfileConnectionPolicyCase( + false, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + true); + testSetGetProfileConnectionPolicyCase( + false, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + true); + testSetGetProfileConnectionPolicyCase( + false, badConnectionPolicy, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); // Cases of device already in database - testSetGetProfileConnectionPolicyCase(true, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true); - testSetGetProfileConnectionPolicyCase(true, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, true); - testSetGetProfileConnectionPolicyCase(true, BluetoothProfile.CONNECTION_POLICY_ALLOWED, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, true); - testSetGetProfileConnectionPolicyCase(true, badConnectionPolicy, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); + testSetGetProfileConnectionPolicyCase( + true, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + true); + testSetGetProfileConnectionPolicyCase( + true, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + true); + testSetGetProfileConnectionPolicyCase( + true, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + true); + testSetGetProfileConnectionPolicyCase( + true, badConnectionPolicy, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); } @Test @@ -193,30 +217,48 @@ public final class DatabaseManagerTest { int badValue = -100; // Cases of device not in database - testSetGetA2dpOptionalCodecsCase(A2DP_SUPPORT_OP_CODEC_TEST, false, + testSetGetA2dpOptionalCodecsCase( + A2DP_SUPPORT_OP_CODEC_TEST, + false, BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN, BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN); - testSetGetA2dpOptionalCodecsCase(A2DP_SUPPORT_OP_CODEC_TEST, false, + testSetGetA2dpOptionalCodecsCase( + A2DP_SUPPORT_OP_CODEC_TEST, + false, BluetoothA2dp.OPTIONAL_CODECS_NOT_SUPPORTED, BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN); - testSetGetA2dpOptionalCodecsCase(A2DP_SUPPORT_OP_CODEC_TEST, false, + testSetGetA2dpOptionalCodecsCase( + A2DP_SUPPORT_OP_CODEC_TEST, + false, BluetoothA2dp.OPTIONAL_CODECS_SUPPORTED, BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN); - testSetGetA2dpOptionalCodecsCase(A2DP_SUPPORT_OP_CODEC_TEST, false, - badValue, BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN); + testSetGetA2dpOptionalCodecsCase( + A2DP_SUPPORT_OP_CODEC_TEST, + false, + badValue, + BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN); // Cases of device already in database - testSetGetA2dpOptionalCodecsCase(A2DP_SUPPORT_OP_CODEC_TEST, true, + testSetGetA2dpOptionalCodecsCase( + A2DP_SUPPORT_OP_CODEC_TEST, + true, BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN, BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN); - testSetGetA2dpOptionalCodecsCase(A2DP_SUPPORT_OP_CODEC_TEST, true, + testSetGetA2dpOptionalCodecsCase( + A2DP_SUPPORT_OP_CODEC_TEST, + true, BluetoothA2dp.OPTIONAL_CODECS_NOT_SUPPORTED, BluetoothA2dp.OPTIONAL_CODECS_NOT_SUPPORTED); - testSetGetA2dpOptionalCodecsCase(A2DP_SUPPORT_OP_CODEC_TEST, true, + testSetGetA2dpOptionalCodecsCase( + A2DP_SUPPORT_OP_CODEC_TEST, + true, BluetoothA2dp.OPTIONAL_CODECS_SUPPORTED, BluetoothA2dp.OPTIONAL_CODECS_SUPPORTED); - testSetGetA2dpOptionalCodecsCase(A2DP_SUPPORT_OP_CODEC_TEST, true, - badValue, BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN); + testSetGetA2dpOptionalCodecsCase( + A2DP_SUPPORT_OP_CODEC_TEST, + true, + badValue, + BluetoothA2dp.OPTIONAL_CODECS_SUPPORT_UNKNOWN); } @Test @@ -224,30 +266,48 @@ public final class DatabaseManagerTest { int badValue = -100; // Cases of device not in database - testSetGetA2dpOptionalCodecsCase(A2DP_ENALBED_OP_CODEC_TEST, false, + testSetGetA2dpOptionalCodecsCase( + A2DP_ENALBED_OP_CODEC_TEST, + false, BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN, BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN); - testSetGetA2dpOptionalCodecsCase(A2DP_ENALBED_OP_CODEC_TEST, false, + testSetGetA2dpOptionalCodecsCase( + A2DP_ENALBED_OP_CODEC_TEST, + false, BluetoothA2dp.OPTIONAL_CODECS_PREF_DISABLED, BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN); - testSetGetA2dpOptionalCodecsCase(A2DP_ENALBED_OP_CODEC_TEST, false, + testSetGetA2dpOptionalCodecsCase( + A2DP_ENALBED_OP_CODEC_TEST, + false, BluetoothA2dp.OPTIONAL_CODECS_PREF_ENABLED, BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN); - testSetGetA2dpOptionalCodecsCase(A2DP_ENALBED_OP_CODEC_TEST, false, - badValue, BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN); + testSetGetA2dpOptionalCodecsCase( + A2DP_ENALBED_OP_CODEC_TEST, + false, + badValue, + BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN); // Cases of device already in database - testSetGetA2dpOptionalCodecsCase(A2DP_ENALBED_OP_CODEC_TEST, true, + testSetGetA2dpOptionalCodecsCase( + A2DP_ENALBED_OP_CODEC_TEST, + true, BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN, BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN); - testSetGetA2dpOptionalCodecsCase(A2DP_ENALBED_OP_CODEC_TEST, true, + testSetGetA2dpOptionalCodecsCase( + A2DP_ENALBED_OP_CODEC_TEST, + true, BluetoothA2dp.OPTIONAL_CODECS_PREF_DISABLED, BluetoothA2dp.OPTIONAL_CODECS_PREF_DISABLED); - testSetGetA2dpOptionalCodecsCase(A2DP_ENALBED_OP_CODEC_TEST, true, + testSetGetA2dpOptionalCodecsCase( + A2DP_ENALBED_OP_CODEC_TEST, + true, BluetoothA2dp.OPTIONAL_CODECS_PREF_ENABLED, BluetoothA2dp.OPTIONAL_CODECS_PREF_ENABLED); - testSetGetA2dpOptionalCodecsCase(A2DP_ENALBED_OP_CODEC_TEST, true, - badValue, BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN); + testSetGetA2dpOptionalCodecsCase( + A2DP_ENALBED_OP_CODEC_TEST, + true, + badValue, + BluetoothA2dp.OPTIONAL_CODECS_PREF_UNKNOWN); } @Test @@ -310,10 +370,10 @@ public final class DatabaseManagerTest { mDatabase.insert(otherData2); // Add OTHER_BT_ADDR1 OTHER_BT_ADDR2 to bonded devices - BluetoothDevice otherDevice1 = BluetoothAdapter.getDefaultAdapter() - .getRemoteDevice(OTHER_BT_ADDR1); - BluetoothDevice otherDevice2 = BluetoothAdapter.getDefaultAdapter() - .getRemoteDevice(OTHER_BT_ADDR2); + BluetoothDevice otherDevice1 = + BluetoothAdapter.getDefaultAdapter().getRemoteDevice(OTHER_BT_ADDR1); + BluetoothDevice otherDevice2 = + BluetoothAdapter.getDefaultAdapter().getRemoteDevice(OTHER_BT_ADDR2); BluetoothDevice[] bondedDevices = {otherDevice1, otherDevice2}; doReturn(bondedDevices).when(mAdapterService).getBondedDevices(); @@ -338,7 +398,6 @@ public final class DatabaseManagerTest { mDatabaseManager.mMetadataCache.clear(); // Wait for clear database TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - } @Test @@ -347,142 +406,110 @@ public final class DatabaseManagerTest { byte[] value = "input value".getBytes(); // Device is not in database - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MANUFACTURER_NAME, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MODEL_NAME, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_SOFTWARE_VERSION, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_HARDWARE_VERSION, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_COMPANION_APP, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MAIN_ICON, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_LEFT_ICON, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_RIGHT_ICON, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_CASE_ICON, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_LEFT_BATTERY, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_RIGHT_BATTERY, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_CASE_BATTERY, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_LEFT_CHARGING, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_RIGHT_CHARGING, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_CASE_CHARGING, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_ENHANCED_SETTINGS_UI_URI, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_DEVICE_TYPE, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MAIN_BATTERY, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MAIN_CHARGING, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MAIN_LOW_BATTERY_THRESHOLD, - value, true); - testSetGetCustomMetaCase(false, - BluetoothDevice.METADATA_UNTETHERED_LEFT_LOW_BATTERY_THRESHOLD, - value, true); - testSetGetCustomMetaCase(false, + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MANUFACTURER_NAME, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MODEL_NAME, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_SOFTWARE_VERSION, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_HARDWARE_VERSION, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_COMPANION_APP, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MAIN_ICON, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_LEFT_ICON, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_RIGHT_ICON, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_UNTETHERED_CASE_ICON, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_LEFT_BATTERY, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_RIGHT_BATTERY, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_CASE_BATTERY, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_LEFT_CHARGING, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_RIGHT_CHARGING, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_CASE_CHARGING, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_ENHANCED_SETTINGS_UI_URI, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_DEVICE_TYPE, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MAIN_BATTERY, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_MAIN_CHARGING, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_MAIN_LOW_BATTERY_THRESHOLD, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_LEFT_LOW_BATTERY_THRESHOLD, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_RIGHT_LOW_BATTERY_THRESHOLD, - value, true); - testSetGetCustomMetaCase(false, - BluetoothDevice.METADATA_UNTETHERED_CASE_LOW_BATTERY_THRESHOLD, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_SPATIAL_AUDIO, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_FAST_PAIR_CUSTOMIZED_FIELDS, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_LE_AUDIO, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_GMCS_CCCD, - value, true); - testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_GTBS_CCCD, - value, true); + value, + true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_UNTETHERED_CASE_LOW_BATTERY_THRESHOLD, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_SPATIAL_AUDIO, value, true); + testSetGetCustomMetaCase( + false, BluetoothDevice.METADATA_FAST_PAIR_CUSTOMIZED_FIELDS, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_LE_AUDIO, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_GMCS_CCCD, value, true); + testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_GTBS_CCCD, value, true); testSetGetCustomMetaCase(false, badKey, value, false); testSetGetCustomMetaCase(false, BluetoothDevice.METADATA_EXCLUSIVE_MANAGER, value, true); // Device is in database - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MANUFACTURER_NAME, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MODEL_NAME, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_SOFTWARE_VERSION, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_HARDWARE_VERSION, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_COMPANION_APP, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MAIN_ICON, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_LEFT_ICON, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_RIGHT_ICON, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_CASE_ICON, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_LEFT_BATTERY, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_RIGHT_BATTERY, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_CASE_BATTERY, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_LEFT_CHARGING, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_RIGHT_CHARGING, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_CASE_CHARGING, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_ENHANCED_SETTINGS_UI_URI, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_DEVICE_TYPE, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MAIN_BATTERY, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MAIN_CHARGING, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MAIN_LOW_BATTERY_THRESHOLD, - value, true); - testSetGetCustomMetaCase(true, - BluetoothDevice.METADATA_UNTETHERED_LEFT_LOW_BATTERY_THRESHOLD, - value, true); - testSetGetCustomMetaCase(true, - BluetoothDevice.METADATA_UNTETHERED_RIGHT_LOW_BATTERY_THRESHOLD, - value, true); - testSetGetCustomMetaCase(true, - BluetoothDevice.METADATA_UNTETHERED_CASE_LOW_BATTERY_THRESHOLD, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_SPATIAL_AUDIO, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_FAST_PAIR_CUSTOMIZED_FIELDS, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_LE_AUDIO, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_GMCS_CCCD, - value, true); - testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_GTBS_CCCD, - value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MANUFACTURER_NAME, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MODEL_NAME, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_SOFTWARE_VERSION, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_HARDWARE_VERSION, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_COMPANION_APP, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MAIN_ICON, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_IS_UNTETHERED_HEADSET, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_LEFT_ICON, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_RIGHT_ICON, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_UNTETHERED_CASE_ICON, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_LEFT_BATTERY, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_RIGHT_BATTERY, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_CASE_BATTERY, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_LEFT_CHARGING, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_RIGHT_CHARGING, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_CASE_CHARGING, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_ENHANCED_SETTINGS_UI_URI, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_DEVICE_TYPE, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MAIN_BATTERY, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_MAIN_CHARGING, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_MAIN_LOW_BATTERY_THRESHOLD, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_LEFT_LOW_BATTERY_THRESHOLD, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_RIGHT_LOW_BATTERY_THRESHOLD, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_UNTETHERED_CASE_LOW_BATTERY_THRESHOLD, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_SPATIAL_AUDIO, value, true); + testSetGetCustomMetaCase( + true, BluetoothDevice.METADATA_FAST_PAIR_CUSTOMIZED_FIELDS, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_LE_AUDIO, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_GMCS_CCCD, value, true); + testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_GTBS_CCCD, value, true); testSetGetCustomMetaCase(true, BluetoothDevice.METADATA_EXCLUSIVE_MANAGER, value, true); } + @Test public void testSetGetAudioPolicyMetaData() { int badKey = 100; - BluetoothSinkAudioPolicy value = new BluetoothSinkAudioPolicy.Builder() - .setCallEstablishPolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .setActiveDevicePolicyAfterConnection(BluetoothSinkAudioPolicy.POLICY_NOT_ALLOWED) - .setInBandRingtonePolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .build(); + BluetoothSinkAudioPolicy value = + new BluetoothSinkAudioPolicy.Builder() + .setCallEstablishPolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .setActiveDevicePolicyAfterConnection( + BluetoothSinkAudioPolicy.POLICY_NOT_ALLOWED) + .setInBandRingtonePolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .build(); // Device is not in database testSetGetAudioPolicyMetadataCase(false, value, true); @@ -556,8 +583,9 @@ public final class DatabaseManagerTest { mDatabaseManager.setConnection(mTestDevice, BluetoothProfile.A2DP); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertTrue(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); + Assert.assertTrue( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); List mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(mTestDevice, mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); @@ -568,13 +596,14 @@ public final class DatabaseManagerTest { mDatabaseManager.setConnection(mTestDevice2, BluetoothProfile.A2DP); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertTrue(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertTrue( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); Assert.assertEquals(mTestDevice2, mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(2, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice2, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -583,13 +612,14 @@ public final class DatabaseManagerTest { mDatabaseManager.setConnection(mTestDevice, BluetoothProfile.A2DP); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertTrue(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); + Assert.assertTrue( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); Assert.assertEquals(mTestDevice, mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(2, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice2, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -598,13 +628,14 @@ public final class DatabaseManagerTest { mDatabaseManager.setDisconnection(mTestDevice, BluetoothProfile.A2DP); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); Assert.assertNull(mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(2, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice2, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -613,15 +644,17 @@ public final class DatabaseManagerTest { mDatabaseManager.setConnection(mTestDevice3, BluetoothProfile.HEADSET); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice3.getAddress()).is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice3.getAddress()) + .is_active_a2dp_device); Assert.assertNull(mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(3, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice3, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -631,15 +664,17 @@ public final class DatabaseManagerTest { mDatabaseManager.setConnection(mTestDevice, BluetoothProfile.A2DP); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertTrue(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice3.getAddress()).is_active_a2dp_device); + Assert.assertTrue( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice3.getAddress()) + .is_active_a2dp_device); Assert.assertEquals(mTestDevice, mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(3, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice3, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -649,15 +684,17 @@ public final class DatabaseManagerTest { mDatabaseManager.setConnection(mTestDevice3, BluetoothProfile.HEADSET); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertTrue(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice3.getAddress()).is_active_a2dp_device); + Assert.assertTrue( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice3.getAddress()) + .is_active_a2dp_device); Assert.assertEquals(mTestDevice, mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(3, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice3, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -667,15 +704,17 @@ public final class DatabaseManagerTest { mDatabaseManager.setDisconnection(mTestDevice2, BluetoothProfile.A2DP); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertTrue(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice3.getAddress()).is_active_a2dp_device); + Assert.assertTrue( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice3.getAddress()) + .is_active_a2dp_device); Assert.assertEquals(mTestDevice, mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(3, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice3, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -685,15 +724,17 @@ public final class DatabaseManagerTest { mDatabaseManager.setDisconnection(mTestDevice, BluetoothProfile.A2DP); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice3.getAddress()).is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice3.getAddress()) + .is_active_a2dp_device); Assert.assertNull(mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(3, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice3, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -703,15 +744,17 @@ public final class DatabaseManagerTest { mDatabaseManager.setDisconnection(mTestDevice3, BluetoothProfile.A2DP); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice2.getAddress()).is_active_a2dp_device); - Assert.assertFalse(mDatabaseManager - .mMetadataCache.get(mTestDevice3.getAddress()).is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice2.getAddress()) + .is_active_a2dp_device); + Assert.assertFalse( + mDatabaseManager.mMetadataCache.get(mTestDevice3.getAddress()) + .is_active_a2dp_device); Assert.assertNull(mDatabaseManager.getMostRecentlyConnectedA2dpDevice()); - mostRecentlyConnectedDevicesOrdered = - mDatabaseManager.getMostRecentlyConnectedDevices(); + mostRecentlyConnectedDevicesOrdered = mDatabaseManager.getMostRecentlyConnectedDevices(); Assert.assertEquals(3, mostRecentlyConnectedDevicesOrdered.size()); Assert.assertEquals(mTestDevice3, mostRecentlyConnectedDevicesOrdered.get(0)); Assert.assertEquals(mTestDevice, mostRecentlyConnectedDevicesOrdered.get(1)); @@ -730,22 +773,26 @@ public final class DatabaseManagerTest { preferences.putInt(BluetoothAdapter.AUDIO_MODE_DUPLEX, BluetoothProfile.LE_AUDIO); // TEST 1: If input is invalid, throws the right Exception - Assert.assertThrows(NullPointerException.class, + Assert.assertThrows( + NullPointerException.class, () -> mDatabaseManager.setPreferredAudioProfiles(null, preferences)); - Assert.assertThrows(NullPointerException.class, + Assert.assertThrows( + NullPointerException.class, () -> mDatabaseManager.setPreferredAudioProfiles(new ArrayList<>(), null)); - Assert.assertThrows(IllegalArgumentException.class, + Assert.assertThrows( + IllegalArgumentException.class, () -> mDatabaseManager.setPreferredAudioProfiles(new ArrayList<>(), preferences)); - Assert.assertThrows(IllegalArgumentException.class, + Assert.assertThrows( + IllegalArgumentException.class, () -> mDatabaseManager.getPreferredAudioProfiles(null)); // TEST 2: If not stored, setter fails and getter returns an empty Bundle - testSetGetPreferredAudioProfilesCase(false, preferences, Bundle.EMPTY, - BluetoothStatusCodes.ERROR_DEVICE_NOT_BONDED); + testSetGetPreferredAudioProfilesCase( + false, preferences, Bundle.EMPTY, BluetoothStatusCodes.ERROR_DEVICE_NOT_BONDED); // TEST 3: If stored, setter succeeds and getter returns the stored preference - testSetGetPreferredAudioProfilesCase(true, preferences, preferences, - BluetoothStatusCodes.SUCCESS); + testSetGetPreferredAudioProfilesCase( + true, preferences, preferences, BluetoothStatusCodes.SUCCESS); } @Test @@ -759,8 +806,9 @@ public final class DatabaseManagerTest { // Migrate database from 100 to 101 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 101, true, - MetadataDatabase.MIGRATION_100_101); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 101, true, MetadataDatabase.MIGRATION_100_101); cursor = db.query("SELECT * FROM metadata"); // Check whether pbap_client_priority exists in version 101 @@ -809,7 +857,8 @@ public final class DatabaseManagerTest { device.put("unthethered_left_charging", testString); device.put("unthethered_right_charging", testString); device.put("unthethered_case_charging", testString); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Check the metadata names on version 101 @@ -826,8 +875,9 @@ public final class DatabaseManagerTest { // Migrate database from 101 to 102 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 102, true, - MetadataDatabase.MIGRATION_101_102); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 102, true, MetadataDatabase.MIGRATION_101_102); cursor = db.query("SELECT * FROM metadata"); // metadata names should be changed on version 102 @@ -934,7 +984,8 @@ public final class DatabaseManagerTest { device.put("untethered_left_charging", testString); device.put("untethered_right_charging", testString); device.put("untethered_case_charging", testString); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Check the metadata names on version 102 @@ -953,8 +1004,9 @@ public final class DatabaseManagerTest { // Migrate database from 102 to 103 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 103, true, - MetadataDatabase.MIGRATION_102_103); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 103, true, MetadataDatabase.MIGRATION_102_103); cursor = db.query("SELECT * FROM metadata"); // metadata names should be changed on version 103 @@ -1078,13 +1130,15 @@ public final class DatabaseManagerTest { device.put("untethered_left_charging", testString); device.put("untethered_right_charging", testString); device.put("untethered_case_charging", testString); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 103 to 104 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 104, true, - MetadataDatabase.MIGRATION_103_104); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 104, true, MetadataDatabase.MIGRATION_103_104); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "last_active_time", true); @@ -1108,8 +1162,9 @@ public final class DatabaseManagerTest { // Migrate database from 104 to 105 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 105, true, - MetadataDatabase.MIGRATION_104_105); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 105, true, MetadataDatabase.MIGRATION_104_105); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "device_type", true); @@ -1146,13 +1201,15 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 105 to 106 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 106, true, - MetadataDatabase.MIGRATION_105_106); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 106, true, MetadataDatabase.MIGRATION_105_106); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "le_audio_connection_policy", true); @@ -1174,13 +1231,15 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 106 to 107 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 107, true, - MetadataDatabase.MIGRATION_106_107); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 107, true, MetadataDatabase.MIGRATION_106_107); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "volume_control_connection_policy", true); @@ -1200,12 +1259,14 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 107 to 108 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 108, true, - MetadataDatabase.MIGRATION_107_108); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 108, true, MetadataDatabase.MIGRATION_107_108); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "csip_set_coordinator_connection_policy", true); while (cursor.moveToNext()) { @@ -1223,12 +1284,14 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 108 to 109 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 109, true, - MetadataDatabase.MIGRATION_108_109); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 109, true, MetadataDatabase.MIGRATION_108_109); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "le_call_control_connection_policy", true); while (cursor.moveToNext()) { @@ -1246,12 +1309,14 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 109 to 110 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 110, true, - MetadataDatabase.MIGRATION_109_110); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 110, true, MetadataDatabase.MIGRATION_109_110); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "hap_client_connection_policy", true); while (cursor.moveToNext()) { @@ -1269,12 +1334,14 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 111 to 112 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 112, true, - MetadataDatabase.MIGRATION_111_112); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 112, true, MetadataDatabase.MIGRATION_111_112); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "battery_connection_policy", true); while (cursor.moveToNext()) { @@ -1291,12 +1358,14 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 112 to 113 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 113, true, - MetadataDatabase.MIGRATION_112_113); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 113, true, MetadataDatabase.MIGRATION_112_113); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "spatial_audio", true); assertHasColumn(cursor, "fastpair_customized", true); @@ -1315,12 +1384,14 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 113 to 114 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 114, true, - MetadataDatabase.MIGRATION_113_114); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 114, true, MetadataDatabase.MIGRATION_113_114); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "le_audio", true); while (cursor.moveToNext()) { @@ -1337,13 +1408,15 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 114 to 115 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 115, true, - MetadataDatabase.MIGRATION_114_115); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 115, true, MetadataDatabase.MIGRATION_114_115); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "call_establish_audio_policy", true); @@ -1365,13 +1438,15 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 115 to 116 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 116, true, - MetadataDatabase.MIGRATION_115_116); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 116, true, MetadataDatabase.MIGRATION_115_116); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "preferred_output_only_profile", true); assertHasColumn(cursor, "preferred_duplex_profile", true); @@ -1390,12 +1465,14 @@ public final class DatabaseManagerTest { ContentValues device = new ContentValues(); device.put("address", TEST_BT_ADDR); device.put("migrated", false); - assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), CoreMatchers.not(-1)); // Migrate database from 116 to 117 db.close(); - db = testHelper.runMigrationsAndValidate(DB_NAME, 117, true, - MetadataDatabase.MIGRATION_116_117); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 117, true, MetadataDatabase.MIGRATION_116_117); Cursor cursor = db.query("SELECT * FROM metadata"); assertHasColumn(cursor, "gmcs_cccd", true); assertHasColumn(cursor, "gtbs_cccd", true); @@ -1479,9 +1556,7 @@ public final class DatabaseManagerTest { } } - /** - * Helper function to check whether the database has the expected column - */ + /** Helper function to check whether the database has the expected column */ void assertHasColumn(Cursor cursor, String columnName, boolean hasColumn) { if (hasColumn) { assertThat(cursor.getColumnIndex(columnName), CoreMatchers.not(-1)); @@ -1490,27 +1565,21 @@ public final class DatabaseManagerTest { } } - /** - * Helper function to check whether the database has the expected value - */ + /** Helper function to check whether the database has the expected value */ void assertColumnIntData(Cursor cursor, String columnName, int value) { assertThat(cursor.getInt(cursor.getColumnIndex(columnName)), CoreMatchers.is(value)); } - /** - * Helper function to check whether the column data type is BLOB - */ + /** Helper function to check whether the column data type is BLOB */ void assertColumnBlob(Cursor cursor, String columnName) { - assertThat(cursor.getType(cursor.getColumnIndex(columnName)), + assertThat( + cursor.getType(cursor.getColumnIndex(columnName)), CoreMatchers.is(Cursor.FIELD_TYPE_BLOB)); } - /** - * Helper function to check the BLOB data in a column is expected - */ + /** Helper function to check the BLOB data in a column is expected */ void assertColumnBlobData(Cursor cursor, String columnName, byte[] data) { - assertThat(cursor.getBlob(cursor.getColumnIndex(columnName)), - CoreMatchers.is(data)); + assertThat(cursor.getBlob(cursor.getColumnIndex(columnName)), CoreMatchers.is(data)); } void restartDatabaseManagerHelper() { @@ -1530,17 +1599,22 @@ public final class DatabaseManagerTest { TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); } - void testSetGetProfileConnectionPolicyCase(boolean stored, int connectionPolicy, - int expectedConnectionPolicy, boolean expectedSetResult) { + void testSetGetProfileConnectionPolicyCase( + boolean stored, + int connectionPolicy, + int expectedConnectionPolicy, + boolean expectedSetResult) { if (stored) { Metadata data = new Metadata(TEST_BT_ADDR); mDatabaseManager.mMetadataCache.put(TEST_BT_ADDR, data); mDatabase.insert(data); } - Assert.assertEquals(expectedSetResult, - mDatabaseManager.setProfileConnectionPolicy(mTestDevice, - BluetoothProfile.HEADSET, connectionPolicy)); - Assert.assertEquals(expectedConnectionPolicy, + Assert.assertEquals( + expectedSetResult, + mDatabaseManager.setProfileConnectionPolicy( + mTestDevice, BluetoothProfile.HEADSET, connectionPolicy)); + Assert.assertEquals( + expectedConnectionPolicy, mDatabaseManager.getProfileConnectionPolicy(mTestDevice, BluetoothProfile.HEADSET)); // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); @@ -1560,7 +1634,8 @@ public final class DatabaseManagerTest { // Check whether the device is in database restartDatabaseManagerHelper(); - Assert.assertEquals(expectedConnectionPolicy, + Assert.assertEquals( + expectedConnectionPolicy, mDatabaseManager.getProfileConnectionPolicy(mTestDevice, BluetoothProfile.HEADSET)); mDatabaseManager.factoryReset(); @@ -1577,12 +1652,12 @@ public final class DatabaseManagerTest { } if (test == A2DP_SUPPORT_OP_CODEC_TEST) { mDatabaseManager.setA2dpSupportsOptionalCodecs(mTestDevice, value); - Assert.assertEquals(expectedValue, - mDatabaseManager.getA2dpSupportsOptionalCodecs(mTestDevice)); + Assert.assertEquals( + expectedValue, mDatabaseManager.getA2dpSupportsOptionalCodecs(mTestDevice)); } else { mDatabaseManager.setA2dpOptionalCodecsEnabled(mTestDevice, value); - Assert.assertEquals(expectedValue, - mDatabaseManager.getA2dpOptionalCodecsEnabled(mTestDevice)); + Assert.assertEquals( + expectedValue, mDatabaseManager.getA2dpOptionalCodecsEnabled(mTestDevice)); } // Wait for database update TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); @@ -1600,11 +1675,11 @@ public final class DatabaseManagerTest { // Check whether the device is in database restartDatabaseManagerHelper(); if (test == A2DP_SUPPORT_OP_CODEC_TEST) { - Assert.assertEquals(expectedValue, - mDatabaseManager.getA2dpSupportsOptionalCodecs(mTestDevice)); + Assert.assertEquals( + expectedValue, mDatabaseManager.getA2dpSupportsOptionalCodecs(mTestDevice)); } else { - Assert.assertEquals(expectedValue, - mDatabaseManager.getA2dpOptionalCodecsEnabled(mTestDevice)); + Assert.assertEquals( + expectedValue, mDatabaseManager.getA2dpOptionalCodecsEnabled(mTestDevice)); } mDatabaseManager.factoryReset(); @@ -1620,18 +1695,17 @@ public final class DatabaseManagerTest { Metadata data = new Metadata(TEST_BT_ADDR); mDatabaseManager.mMetadataCache.put(TEST_BT_ADDR, data); mDatabase.insert(data); - Assert.assertEquals(expectedResult, - mDatabaseManager.setCustomMeta(mTestDevice, key, testValue)); + Assert.assertEquals( + expectedResult, mDatabaseManager.setCustomMeta(mTestDevice, key, testValue)); verify(mAdapterService).metadataChanged(TEST_BT_ADDR, key, testValue); verifyTime++; } - Assert.assertEquals(expectedResult, - mDatabaseManager.setCustomMeta(mTestDevice, key, value)); + Assert.assertEquals( + expectedResult, mDatabaseManager.setCustomMeta(mTestDevice, key, value)); if (expectedResult) { // Check for callback and get value verify(mAdapterService, times(verifyTime)).metadataChanged(TEST_BT_ADDR, key, value); - Assert.assertEquals(value, - mDatabaseManager.getCustomMeta(mTestDevice, key)); + Assert.assertEquals(value, mDatabaseManager.getCustomMeta(mTestDevice, key)); } else { Assert.assertNull(mDatabaseManager.getCustomMeta(mTestDevice, key)); return; @@ -1641,8 +1715,7 @@ public final class DatabaseManagerTest { // Check whether the value is saved in database restartDatabaseManagerHelper(); - Assert.assertArrayEquals(value, - mDatabaseManager.getCustomMeta(mTestDevice, key)); + Assert.assertArrayEquals(value, mDatabaseManager.getCustomMeta(mTestDevice, key)); mDatabaseManager.factoryReset(); mDatabaseManager.mMetadataCache.clear(); @@ -1650,22 +1723,22 @@ public final class DatabaseManagerTest { TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); } - void testSetGetAudioPolicyMetadataCase(boolean stored, - BluetoothSinkAudioPolicy policy, boolean expectedResult) { + void testSetGetAudioPolicyMetadataCase( + boolean stored, BluetoothSinkAudioPolicy policy, boolean expectedResult) { BluetoothSinkAudioPolicy testPolicy = new BluetoothSinkAudioPolicy.Builder().build(); if (stored) { Metadata data = new Metadata(TEST_BT_ADDR); mDatabaseManager.mMetadataCache.put(TEST_BT_ADDR, data); mDatabase.insert(data); - Assert.assertEquals(expectedResult, + Assert.assertEquals( + expectedResult, mDatabaseManager.setAudioPolicyMetadata(mTestDevice, testPolicy)); } - Assert.assertEquals(expectedResult, - mDatabaseManager.setAudioPolicyMetadata(mTestDevice, policy)); + Assert.assertEquals( + expectedResult, mDatabaseManager.setAudioPolicyMetadata(mTestDevice, policy)); if (expectedResult) { // Check for callback and get value - Assert.assertEquals(policy, - mDatabaseManager.getAudioPolicyMetadata(mTestDevice)); + Assert.assertEquals(policy, mDatabaseManager.getAudioPolicyMetadata(mTestDevice)); } else { Assert.assertNull(mDatabaseManager.getAudioPolicyMetadata(mTestDevice)); return; @@ -1675,8 +1748,7 @@ public final class DatabaseManagerTest { // Check whether the value is saved in database restartDatabaseManagerHelper(); - Assert.assertEquals(policy, - mDatabaseManager.getAudioPolicyMetadata(mTestDevice)); + Assert.assertEquals(policy, mDatabaseManager.getAudioPolicyMetadata(mTestDevice)); mDatabaseManager.factoryReset(); mDatabaseManager.mMetadataCache.clear(); @@ -1684,8 +1756,11 @@ public final class DatabaseManagerTest { TestUtils.waitForLooperToFinishScheduledTask(mDatabaseManager.getHandlerLooper()); } - void testSetGetPreferredAudioProfilesCase(boolean stored, Bundle preferencesToSet, - Bundle expectedPreferences, int expectedSetResult) { + void testSetGetPreferredAudioProfilesCase( + boolean stored, + Bundle preferencesToSet, + Bundle expectedPreferences, + int expectedSetResult) { if (stored) { Metadata data = new Metadata(TEST_BT_ADDR); Metadata data2 = new Metadata(TEST_BT_ADDR2); @@ -1698,19 +1773,22 @@ public final class DatabaseManagerTest { groupDevices.add(mTestDevice); groupDevices.add(mTestDevice2); - Assert.assertEquals(expectedSetResult, + Assert.assertEquals( + expectedSetResult, mDatabaseManager.setPreferredAudioProfiles(groupDevices, preferencesToSet)); Bundle testDevicePreferences = mDatabaseManager.getPreferredAudioProfiles(mTestDevice); Bundle testDevice2Preferences = mDatabaseManager.getPreferredAudioProfiles(mTestDevice2); Assert.assertNotNull(testDevicePreferences); Assert.assertNotNull(testDevice2Preferences); - Assert.assertEquals(expectedPreferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY), + Assert.assertEquals( + expectedPreferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY), testDevicePreferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY)); - Assert.assertEquals(expectedPreferences.getInt(BluetoothAdapter.AUDIO_MODE_DUPLEX), + Assert.assertEquals( + expectedPreferences.getInt(BluetoothAdapter.AUDIO_MODE_DUPLEX), testDevicePreferences.getInt(BluetoothAdapter.AUDIO_MODE_DUPLEX)); - Assert.assertEquals(0, - testDevice2Preferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY)); + Assert.assertEquals( + 0, testDevice2Preferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY)); Assert.assertEquals(0, testDevice2Preferences.getInt(BluetoothAdapter.AUDIO_MODE_DUPLEX)); // Wait for database update @@ -1732,12 +1810,14 @@ public final class DatabaseManagerTest { Assert.assertNotNull(testDevicePreferences); Assert.assertNotNull(testDevice2Preferences); - Assert.assertEquals(expectedPreferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY), + Assert.assertEquals( + expectedPreferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY), testDevicePreferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY)); - Assert.assertEquals(expectedPreferences.getInt(BluetoothAdapter.AUDIO_MODE_DUPLEX), + Assert.assertEquals( + expectedPreferences.getInt(BluetoothAdapter.AUDIO_MODE_DUPLEX), testDevicePreferences.getInt(BluetoothAdapter.AUDIO_MODE_DUPLEX)); - Assert.assertEquals(0, - testDevice2Preferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY)); + Assert.assertEquals( + 0, testDevice2Preferences.getInt(BluetoothAdapter.AUDIO_MODE_OUTPUT_ONLY)); Assert.assertEquals(0, testDevice2Preferences.getInt(BluetoothAdapter.AUDIO_MODE_DUPLEX)); mDatabaseManager.factoryReset(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java index 2f2b075ef33..181a735d2d3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java @@ -38,8 +38,7 @@ public class BluetoothCsisBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private CsipSetCoordinatorService mService; + @Mock private CsipSetCoordinatorService mService; private AttributionSource mAttributionSource; private BluetoothDevice mTestDevice; @@ -73,7 +72,7 @@ public class BluetoothCsisBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] { BluetoothProfile.STATE_CONNECTED }; + int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); verify(mService).getDevicesMatchingConnectionStates(states); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java index d212f044b04..34de5db973c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java @@ -78,8 +78,7 @@ public class CsipSetCoordinatorServiceTest { @Mock private AdapterService mAdapterService; @Mock private LeAudioService mLeAudioService; - @Spy - private ServiceFactory mServiceFactory = new ServiceFactory(); + @Spy private ServiceFactory mServiceFactory = new ServiceFactory(); @Mock private DatabaseManager mDatabaseManager; @Mock private CsipSetCoordinatorNativeInterface mCsipSetCoordinatorNativeInterface; @Mock private IBluetoothCsipSetCoordinatorLockCallback mCsipSetCoordinatorLockCallback; @@ -96,7 +95,6 @@ public class CsipSetCoordinatorServiceTest { } Assert.assertNotNull(Looper.myLooper()); - TestUtils.setAdapterService(mAdapterService); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); @@ -175,17 +173,13 @@ public class CsipSetCoordinatorServiceTest { Assert.assertNull(mService); } - /** - * Test getting CsipSetCoordinator Service - */ + /** Test getting CsipSetCoordinator Service */ @Test public void testGetService() { Assert.assertEquals(mService, CsipSetCoordinatorService.getCsipSetCoordinatorService()); } - /** - * Test stop CsipSetCoordinator Service - */ + /** Test stop CsipSetCoordinator Service */ @Test public void testStopService() { Assert.assertEquals(mService, CsipSetCoordinatorService.getCsipSetCoordinatorService()); @@ -198,67 +192,95 @@ public class CsipSetCoordinatorServiceTest { @Test public void testGetSetPolicy() { when(mDatabaseManager.getProfileConnectionPolicy( - mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - Assert.assertEquals("Initial device policy", BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + Assert.assertEquals( + "Initial device policy", + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mService.getConnectionPolicy(mTestDevice)); when(mDatabaseManager.getProfileConnectionPolicy( - mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - Assert.assertEquals("Setting device policy to POLICY_FORBIDDEN", + Assert.assertEquals( + "Setting device policy to POLICY_FORBIDDEN", BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, mService.getConnectionPolicy(mTestDevice)); when(mDatabaseManager.getProfileConnectionPolicy( - mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - Assert.assertEquals("Setting device policy to POLICY_ALLOWED", + Assert.assertEquals( + "Setting device policy to POLICY_ALLOWED", BluetoothProfile.CONNECTION_POLICY_ALLOWED, mService.getConnectionPolicy(mTestDevice)); } - /** - * Test if getProfileConnectionPolicy works after the service is stopped. - */ + /** Test if getProfileConnectionPolicy works after the service is stopped. */ @Test public void testGetPolicyAfterStopped() { mService.stop(); - when(mDatabaseManager - .getProfileConnectionPolicy(mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + when(mDatabaseManager.getProfileConnectionPolicy( + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - Assert.assertEquals("Initial device policy", + Assert.assertEquals( + "Initial device policy", BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mService.getConnectionPolicy(mTestDevice)); } - /** - * Test okToConnect method using various test cases - */ + /** Test okToConnect method using various test cases */ @Test public void testOkToConnect() { int badPolicyValue = 1024; int badBondState = 42; - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_NONE, badPolicyValue, false); - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDING, badPolicyValue, false); - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true); - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, true); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + true); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + true); testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDED, badPolicyValue, false); testOkToConnectCase( mTestDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); @@ -269,10 +291,7 @@ public class CsipSetCoordinatorServiceTest { testOkToConnectCase(mTestDevice, badBondState, badPolicyValue, false); } - /** - * Test that call to groupLockSet method calls corresponding native interface - * method - */ + /** Test that call to groupLockSet method calls corresponding native interface method */ @Test public void testGroupLockSetNative() { int group_id = 0x01; @@ -283,8 +302,8 @@ public class CsipSetCoordinatorServiceTest { doCallRealMethod() .when(mCsipSetCoordinatorNativeInterface) - .onDeviceAvailable(any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), - anyLong()); + .onDeviceAvailable( + any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), anyLong()); mCsipSetCoordinatorNativeInterface.onDeviceAvailable( getByteAddress(mTestDevice), group_id, group_size, 1, uuidLsb, uuidMsb); Assert.assertFalse(mService.isGroupLocked(group_id)); @@ -302,8 +321,7 @@ public class CsipSetCoordinatorServiceTest { try { verify(mCsipSetCoordinatorLockCallback, times(1)) - .onGroupLockSet(group_id, BluetoothStatusCodes.SUCCESS, - true); + .onGroupLockSet(group_id, BluetoothStatusCodes.SUCCESS, true); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } @@ -317,17 +335,13 @@ public class CsipSetCoordinatorServiceTest { try { verify(mCsipSetCoordinatorLockCallback, times(1)) - .onGroupLockSet(group_id, BluetoothStatusCodes.SUCCESS, - false); + .onGroupLockSet(group_id, BluetoothStatusCodes.SUCCESS, false); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } - /** - * Test that call to groupLockSet method calls corresponding native interface - * method - */ + /** Test that call to groupLockSet method calls corresponding native interface method */ @Test public void testGroupExclusiveLockSet() { int group_id = 0x01; @@ -338,8 +352,8 @@ public class CsipSetCoordinatorServiceTest { doCallRealMethod() .when(mCsipSetCoordinatorNativeInterface) - .onDeviceAvailable(any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), - anyLong()); + .onDeviceAvailable( + any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), anyLong()); mCsipSetCoordinatorNativeInterface.onDeviceAvailable( getByteAddress(mTestDevice), group_id, group_size, 1, uuidLsb, uuidMsb); Assert.assertFalse(mService.isGroupLocked(group_id)); @@ -358,23 +372,20 @@ public class CsipSetCoordinatorServiceTest { try { verify(mCsipSetCoordinatorLockCallback, times(1)) - .onGroupLockSet(group_id, - BluetoothStatusCodes.ERROR_CSIP_GROUP_LOCKED_BY_OTHER, true); + .onGroupLockSet( + group_id, BluetoothStatusCodes.ERROR_CSIP_GROUP_LOCKED_BY_OTHER, true); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } Assert.assertNull(lock_uuid); } - /** - * Test that an outgoing connection to device that does not have MICS UUID is - * rejected - */ + /** Test that an outgoing connection to device that does not have MICS UUID is rejected */ @Test public void testOutgoingConnectMissingUuid() { // Update the device policy so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy( - mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mCsipSetCoordinatorNativeInterface).connect(any(BluetoothDevice.class)); doReturn(true).when(mCsipSetCoordinatorNativeInterface).connect(any(BluetoothDevice.class)); @@ -388,14 +399,12 @@ public class CsipSetCoordinatorServiceTest { Assert.assertFalse("Connect expected to fail", mService.connect(mTestDevice)); } - /** - * Test that an outgoing connection to device that have MICS UUID is successful - */ + /** Test that an outgoing connection to device that have MICS UUID is successful */ @Test public void testOutgoingConnectExistingUuid() { // Update the device policy so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy( - mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mCsipSetCoordinatorNativeInterface).connect(any(BluetoothDevice.class)); doReturn(true) @@ -412,9 +421,7 @@ public class CsipSetCoordinatorServiceTest { TestUtils.waitForIntent(TIMEOUT_MS, mIntentQueue.get(mTestDevice)); } - /** - * Test that an outgoing connection to device with POLICY_FORBIDDEN is rejected - */ + /** Test that an outgoing connection to device with POLICY_FORBIDDEN is rejected */ @Test public void testOutgoingConnectPolicyForbidden() { doReturn(true).when(mCsipSetCoordinatorNativeInterface).connect(any(BluetoothDevice.class)); @@ -424,22 +431,20 @@ public class CsipSetCoordinatorServiceTest { // Set the device policy to POLICY_FORBIDDEN so connect() should fail when(mDatabaseManager.getProfileConnectionPolicy( - mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Send a connect request Assert.assertFalse("Connect expected to fail", mService.connect(mTestDevice)); } - /** - * Test that an outgoing connection times out - */ + /** Test that an outgoing connection times out */ @Test public void testOutgoingConnectTimeout() { // Update the device policy so okToConnect() returns true when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager); when(mDatabaseManager.getProfileConnectionPolicy( - mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mCsipSetCoordinatorNativeInterface).connect(any(BluetoothDevice.class)); doReturn(true) @@ -450,22 +455,25 @@ public class CsipSetCoordinatorServiceTest { Assert.assertTrue("Connect failed", mService.connect(mTestDevice)); // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, mTestDevice, BluetoothProfile.STATE_CONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mTestDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); Assert.assertEquals( BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(mTestDevice)); // Verify the connection state broadcast, and that we are in Disconnected state - verifyConnectionStateIntent(CsipSetCoordinatorStateMachine.sConnectTimeoutMs * 2, - mTestDevice, BluetoothProfile.STATE_DISCONNECTED, + verifyConnectionStateIntent( + CsipSetCoordinatorStateMachine.sConnectTimeoutMs * 2, + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); Assert.assertEquals( BluetoothProfile.STATE_DISCONNECTED, mService.getConnectionState(mTestDevice)); } - /** - * Test that native callback generates proper intent. - */ + /** Test that native callback generates proper intent. */ @Test public void testStackEventDeviceAvailable() { int group_id = 0x01; @@ -476,8 +484,8 @@ public class CsipSetCoordinatorServiceTest { doCallRealMethod() .when(mCsipSetCoordinatorNativeInterface) - .onDeviceAvailable(any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), - anyLong()); + .onDeviceAvailable( + any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), anyLong()); mCsipSetCoordinatorNativeInterface.onDeviceAvailable( getByteAddress(mTestDevice), group_id, group_size, 0x02, uuidLsb, uuidMsb); @@ -488,9 +496,11 @@ public class CsipSetCoordinatorServiceTest { Assert.assertEquals(mTestDevice, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); Assert.assertEquals( group_id, intent.getIntExtra(BluetoothCsipSetCoordinator.EXTRA_CSIS_GROUP_ID, -1)); - Assert.assertEquals(group_size, + Assert.assertEquals( + group_size, intent.getIntExtra(BluetoothCsipSetCoordinator.EXTRA_CSIS_GROUP_SIZE, -1)); - Assert.assertEquals(uuid, + Assert.assertEquals( + uuid, intent.getSerializableExtra( BluetoothCsipSetCoordinator.EXTRA_CSIS_GROUP_TYPE_UUID)); @@ -509,9 +519,7 @@ public class CsipSetCoordinatorServiceTest { Assert.assertEquals(2, devices.indexOf(mTestDevice3)); } - /** - * Test that native callback generates proper intent after group connected. - */ + /** Test that native callback generates proper intent after group connected. */ @Test public void testStackEventSetMemberAvailableAfterGroupConnected() { int group_id = 0x01; @@ -522,8 +530,8 @@ public class CsipSetCoordinatorServiceTest { // Make sure to use real methods when needed below doCallRealMethod() .when(mCsipSetCoordinatorNativeInterface) - .onDeviceAvailable(any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), - anyLong()); + .onDeviceAvailable( + any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), anyLong()); doCallRealMethod() .when(mCsipSetCoordinatorNativeInterface) .onConnectionStateChanged(any(byte[].class), anyInt()); @@ -538,8 +546,8 @@ public class CsipSetCoordinatorServiceTest { getByteAddress(mTestDevice), BluetoothProfile.STATE_CONNECTED); // Comes from state machine - mService.connectionStateChanged(mTestDevice, BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + mService.connectionStateChanged( + mTestDevice, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); mCsipSetCoordinatorNativeInterface.onSetMemberAvailable( getByteAddress(mTestDevice2), group_id); @@ -553,9 +561,7 @@ public class CsipSetCoordinatorServiceTest { group_id, intent.getIntExtra(BluetoothCsipSetCoordinator.EXTRA_CSIS_GROUP_ID, -1)); } - /** - * Test that native callback generates proper intent before group connected. - */ + /** Test that native callback generates proper intent before group connected. */ @Test public void testStackEventSetMemberAvailableBeforeGroupConnected() { int group_id = 0x01; @@ -566,8 +572,8 @@ public class CsipSetCoordinatorServiceTest { // Make sure to use real methods when needed below doCallRealMethod() .when(mCsipSetCoordinatorNativeInterface) - .onDeviceAvailable(any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), - anyLong()); + .onDeviceAvailable( + any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), anyLong()); doCallRealMethod() .when(mCsipSetCoordinatorNativeInterface) .onSetMemberAvailable(any(byte[].class), anyInt()); @@ -587,9 +593,9 @@ public class CsipSetCoordinatorServiceTest { Intent intent = TestUtils.waitForNoIntent(TIMEOUT_MS, mIntentQueue.get(mTestDevice2)); Assert.assertNull(intent); - // Comes from state machine - mService.connectionStateChanged(mTestDevice, BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + // Comes from state machine + mService.connectionStateChanged( + mTestDevice, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); intent = TestUtils.waitForIntent(TIMEOUT_MS, mIntentQueue.get(mTestDevice2)); Assert.assertNotNull(intent); @@ -614,47 +620,55 @@ public class CsipSetCoordinatorServiceTest { doCallRealMethod() .when(mCsipSetCoordinatorNativeInterface) - .onDeviceAvailable(any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), - anyLong()); - when(mLeAudioService.getConnectionPolicy(any())).thenReturn( - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .onDeviceAvailable( + any(byte[].class), anyInt(), anyInt(), anyInt(), anyLong(), anyLong()); + when(mLeAudioService.getConnectionPolicy(any())) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Make first set device available and connected mCsipSetCoordinatorNativeInterface.onDeviceAvailable( getByteAddress(mTestDevice), group_id, group_size, 0x02, uuidLsb, uuidMsb); - mService.connectionStateChanged(mTestDevice, BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + mService.connectionStateChanged( + mTestDevice, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); // Another device with the highest rank mCsipSetCoordinatorNativeInterface.onDeviceAvailable( getByteAddress(mTestDevice2), group_id, group_size, 0x01, uuidLsb, uuidMsb); // When LEA is FORBIDDEN, verify we don't disable CSIP until all set devices are available - verify(mDatabaseManager, never()).setProfileConnectionPolicy(mTestDevice, - BluetoothProfile.CSIP_SET_COORDINATOR, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - verify(mDatabaseManager, never()).setProfileConnectionPolicy(mTestDevice2, - BluetoothProfile.CSIP_SET_COORDINATOR, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + verify(mDatabaseManager, never()) + .setProfileConnectionPolicy( + mTestDevice, + BluetoothProfile.CSIP_SET_COORDINATOR, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + verify(mDatabaseManager, never()) + .setProfileConnectionPolicy( + mTestDevice2, + BluetoothProfile.CSIP_SET_COORDINATOR, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Mark the second device as connected - mService.connectionStateChanged(mTestDevice2, BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + mService.connectionStateChanged( + mTestDevice2, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); // When LEA is FORBIDDEN, verify we disable CSIP once all set devices are available - verify(mDatabaseManager, times(1)).setProfileConnectionPolicy(mTestDevice, - BluetoothProfile.CSIP_SET_COORDINATOR, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - verify(mDatabaseManager, times(1)).setProfileConnectionPolicy(mTestDevice2, - BluetoothProfile.CSIP_SET_COORDINATOR, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + verify(mDatabaseManager, times(1)) + .setProfileConnectionPolicy( + mTestDevice, + BluetoothProfile.CSIP_SET_COORDINATOR, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + verify(mDatabaseManager, times(1)) + .setProfileConnectionPolicy( + mTestDevice2, + BluetoothProfile.CSIP_SET_COORDINATOR, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); } @Test public void testDump_doesNotCrash() { // Update the device policy so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy( - mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) + mTestDevice, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mCsipSetCoordinatorNativeInterface).connect(any(BluetoothDevice.class)); doReturn(true) @@ -671,14 +685,13 @@ public class CsipSetCoordinatorServiceTest { mService.dump(new StringBuilder()); } - /** - * Helper function to test ConnectionStateIntent() method - */ + /** Helper function to test ConnectionStateIntent() method */ private void verifyConnectionStateIntent( int timeoutMs, BluetoothDevice device, int newState, int prevState) { Intent intent = TestUtils.waitForIntent(timeoutMs, mIntentQueue.get(device)); Assert.assertNotNull(intent); - Assert.assertEquals(BluetoothCsipSetCoordinator.ACTION_CSIS_CONNECTION_STATE_CHANGED, + Assert.assertEquals( + BluetoothCsipSetCoordinator.ACTION_CSIS_CONNECTION_STATE_CHANGED, intent.getAction()); Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); Assert.assertEquals(newState, intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); @@ -686,21 +699,17 @@ public class CsipSetCoordinatorServiceTest { prevState, intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)); } - /** - * Helper function to test okToConnect() method - */ + /** Helper function to test okToConnect() method */ private void testOkToConnectCase( BluetoothDevice device, int bondState, int policy, boolean expected) { doReturn(bondState).when(mAdapterService).getBondState(device); when(mDatabaseManager.getProfileConnectionPolicy( - device, BluetoothProfile.CSIP_SET_COORDINATOR)) + device, BluetoothProfile.CSIP_SET_COORDINATOR)) .thenReturn(policy); Assert.assertEquals(expected, mService.okToConnect(device)); } - /** - * Helper function to get byte array for a device address - */ + /** Helper function to get byte array for a device address */ private byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachineTest.java index 8afde812ba5..85871a331af 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachineTest.java @@ -84,8 +84,13 @@ public class CsipSetCoordinatorStateMachineTest { // Set up thread and looper mHandlerThread = new HandlerThread("CsipSetCoordinatorServiceTestHandlerThread"); mHandlerThread.start(); - mStateMachine = spy(new CsipSetCoordinatorStateMachineWrapper( - mTestDevice, mService, mNativeInterface, mHandlerThread.getLooper())); + mStateMachine = + spy( + new CsipSetCoordinatorStateMachineWrapper( + mTestDevice, + mService, + mNativeInterface, + mHandlerThread.getLooper())); // Override the timeout value to speed up the test CsipSetCoordinatorStateMachine.sConnectTimeoutMs = 1000; @@ -102,13 +107,10 @@ public class CsipSetCoordinatorStateMachineTest { TestUtils.clearAdapterService(mAdapterService); } - /** - * Test that default state is disconnected - */ + /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { - Assert.assertEquals( - STATE_DISCONNECTED, mStateMachine.getConnectionState()); + Assert.assertEquals(STATE_DISCONNECTED, mStateMachine.getConnectionState()); } /** @@ -120,17 +122,15 @@ public class CsipSetCoordinatorStateMachineTest { doReturn(allow).when(mService).okToConnect(any(BluetoothDevice.class)); } - /** - * Test that an incoming connection with policy forbidding connection is - * rejected - */ + /** Test that an incoming connection with policy forbidding connection is rejected */ @Test public void testIncomingPolicyReject() { allowConnection(false); // Inject an event for when incoming connection is requested - CsipSetCoordinatorStackEvent connStCh = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent connStCh = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, connStCh); @@ -138,20 +138,20 @@ public class CsipSetCoordinatorStateMachineTest { // Verify that no connection state broadcast is executed verify(mService, after(TIMEOUT_MS).never()).sendBroadcast(any(Intent.class), anyString()); // Check that we are in Disconnected state - Assert.assertThat(mStateMachine.getCurrentState(), + Assert.assertThat( + mStateMachine.getCurrentState(), IsInstanceOf.instanceOf(CsipSetCoordinatorStateMachine.Disconnected.class)); } - /** - * Test that an incoming connection with policy allowing connection is accepted - */ + /** Test that an incoming connection with policy allowing connection is accepted */ @Test public void testIncomingPolicyAccept() { allowConnection(true); // Inject an event for when incoming connection is requested - CsipSetCoordinatorStackEvent connStCh = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent connStCh = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = connStCh.CONNECTION_STATE_CONNECTING; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, connStCh); @@ -160,16 +160,19 @@ public class CsipSetCoordinatorStateMachineTest { ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); verify(mService, timeout(TIMEOUT_MS).times(1)) .sendBroadcast(intentArgument1.capture(), anyString()); - Assert.assertEquals(STATE_CONNECTING, + Assert.assertEquals( + STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mStateMachine.getCurrentState(), + Assert.assertThat( + mStateMachine.getCurrentState(), IsInstanceOf.instanceOf(CsipSetCoordinatorStateMachine.Connecting.class)); // Send a message to trigger connection completed - CsipSetCoordinatorStackEvent connCompletedEvent = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent connCompletedEvent = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = mTestDevice; connCompletedEvent.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, connCompletedEvent); @@ -181,13 +184,12 @@ public class CsipSetCoordinatorStateMachineTest { verify(mService, timeout(TIMEOUT_MS).times(2)) .sendBroadcast(intentArgument2.capture(), anyString()); // Check that we are in Connected state - Assert.assertThat(mStateMachine.getCurrentState(), + Assert.assertThat( + mStateMachine.getCurrentState(), IsInstanceOf.instanceOf(CsipSetCoordinatorStateMachine.Connected.class)); } - /** - * Test that an outgoing connection times out - */ + /** Test that an outgoing connection times out */ @Test public void testOutgoingTimeout() { allowConnection(true); @@ -201,29 +203,31 @@ public class CsipSetCoordinatorStateMachineTest { ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); verify(mService, timeout(TIMEOUT_MS).times(1)) .sendBroadcast(intentArgument1.capture(), anyString()); - Assert.assertEquals(STATE_CONNECTING, + Assert.assertEquals( + STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mStateMachine.getCurrentState(), + Assert.assertThat( + mStateMachine.getCurrentState(), IsInstanceOf.instanceOf(CsipSetCoordinatorStateMachine.Connecting.class)); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); verify(mService, timeout(CsipSetCoordinatorStateMachine.sConnectTimeoutMs * 2).times(2)) .sendBroadcast(intentArgument2.capture(), anyString()); - Assert.assertEquals(STATE_DISCONNECTED, + Assert.assertEquals( + STATE_DISCONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Disconnected state - Assert.assertThat(mStateMachine.getCurrentState(), + Assert.assertThat( + mStateMachine.getCurrentState(), IsInstanceOf.instanceOf(CsipSetCoordinatorStateMachine.Disconnected.class)); verify(mNativeInterface).disconnect(eq(mTestDevice)); } - /** - * Test that an incoming connection times out - */ + /** Test that an incoming connection times out */ @Test public void testIncomingTimeout() { allowConnection(true); @@ -231,8 +235,9 @@ public class CsipSetCoordinatorStateMachineTest { doReturn(true).when(mNativeInterface).disconnect(any(BluetoothDevice.class)); // Inject an event for when incoming connection is requested - CsipSetCoordinatorStackEvent connStCh = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent connStCh = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTING; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, connStCh); @@ -241,22 +246,26 @@ public class CsipSetCoordinatorStateMachineTest { ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); verify(mService, timeout(TIMEOUT_MS).times(1)) .sendBroadcast(intentArgument1.capture(), anyString()); - Assert.assertEquals(STATE_CONNECTING, + Assert.assertEquals( + STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mStateMachine.getCurrentState(), + Assert.assertThat( + mStateMachine.getCurrentState(), IsInstanceOf.instanceOf(CsipSetCoordinatorStateMachine.Connecting.class)); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); verify(mService, timeout(CsipSetCoordinatorStateMachine.sConnectTimeoutMs * 2).times(2)) .sendBroadcast(intentArgument2.capture(), anyString()); - Assert.assertEquals(STATE_DISCONNECTED, + Assert.assertEquals( + STATE_DISCONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Disconnected state - Assert.assertThat(mStateMachine.getCurrentState(), + Assert.assertThat( + mStateMachine.getCurrentState(), IsInstanceOf.instanceOf(CsipSetCoordinatorStateMachine.Disconnected.class)); verify(mNativeInterface).disconnect(eq(mTestDevice)); } @@ -314,15 +323,17 @@ public class CsipSetCoordinatorStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); Assert.assertEquals(STATE_DISCONNECTED, mStateMachine.getConnectionState()); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_DISCONNECTED; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); Assert.assertEquals(STATE_DISCONNECTED, mStateMachine.getConnectionState()); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTING; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -330,23 +341,26 @@ public class CsipSetCoordinatorStateMachineTest { verify(mNativeInterface).disconnect(mTestDevice); Mockito.clearInvocations(mNativeInterface); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); Assert.assertEquals(STATE_DISCONNECTED, mStateMachine.getConnectionState()); verify(mNativeInterface).disconnect(mTestDevice); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_DISCONNECTING; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); Assert.assertEquals(STATE_DISCONNECTED, mStateMachine.getConnectionState()); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = -1; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -356,8 +370,9 @@ public class CsipSetCoordinatorStateMachineTest { @Test public void testStackEvent_toConnectingState_onDisconnectedState() { allowConnection(true); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTING; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -367,8 +382,9 @@ public class CsipSetCoordinatorStateMachineTest { @Test public void testStackEvent_toConnectedState_onDisconnectedState() { allowConnection(true); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -380,8 +396,9 @@ public class CsipSetCoordinatorStateMachineTest { initToConnectingState(); mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.CONNECT); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertTrue(mStateMachine.doesSuperHaveDeferredMessages( - CsipSetCoordinatorStateMachine.CONNECT)); + Assert.assertTrue( + mStateMachine.doesSuperHaveDeferredMessages( + CsipSetCoordinatorStateMachine.CONNECT)); } @Test @@ -406,15 +423,17 @@ public class CsipSetCoordinatorStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); Assert.assertEquals(STATE_CONNECTING, mStateMachine.getConnectionState()); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTING; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); Assert.assertEquals(STATE_CONNECTING, mStateMachine.getConnectionState()); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = 10000; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -424,8 +443,9 @@ public class CsipSetCoordinatorStateMachineTest { @Test public void testStackEvent_toDisconnectedState_onConnectingState() { initToConnectingState(); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_DISCONNECTED; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -435,8 +455,9 @@ public class CsipSetCoordinatorStateMachineTest { @Test public void testStackEvent_toConnectedState_onConnectingState() { initToConnectingState(); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -446,8 +467,9 @@ public class CsipSetCoordinatorStateMachineTest { @Test public void testStackEvent_toDisconnectingState_onConnectingState() { initToConnectingState(); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_DISCONNECTING; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -488,8 +510,9 @@ public class CsipSetCoordinatorStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); Assert.assertEquals(STATE_CONNECTED, mStateMachine.getConnectionState()); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTING; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -499,8 +522,9 @@ public class CsipSetCoordinatorStateMachineTest { @Test public void testStackEvent_toDisconnectedState_onConnectedState() { initToConnectedState(); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_DISCONNECTED; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -510,8 +534,9 @@ public class CsipSetCoordinatorStateMachineTest { @Test public void testStackEvent_toDisconnectingState_onConnectedState() { initToConnectedState(); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_DISCONNECTING; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -552,30 +577,34 @@ public class CsipSetCoordinatorStateMachineTest { Assert.assertEquals(STATE_DISCONNECTING, mStateMachine.getConnectionState()); allowConnection(false); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mNativeInterface).disconnect(any()); Mockito.clearInvocations(mNativeInterface); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTING; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mNativeInterface).disconnect(any()); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_DISCONNECTING; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); Assert.assertEquals(STATE_DISCONNECTING, mStateMachine.getConnectionState()); - event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = 10000; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -586,8 +615,9 @@ public class CsipSetCoordinatorStateMachineTest { public void testStackEvent_toConnectedState_onDisconnectingState() { initToDisconnectingState(); allowConnection(true); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -598,8 +628,9 @@ public class CsipSetCoordinatorStateMachineTest { public void testStackEvent_toConnectedState_butNotAllowed_onDisconnectingState() { initToDisconnectingState(); allowConnection(false); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -610,8 +641,9 @@ public class CsipSetCoordinatorStateMachineTest { public void testStackEvent_toConnectingState_onDisconnectingState() { initToDisconnectingState(); allowConnection(true); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTING; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -622,8 +654,9 @@ public class CsipSetCoordinatorStateMachineTest { public void testStackEvent_toConnectingState_butNotAllowed_onDisconnectingState() { initToDisconnectingState(); allowConnection(false); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; mStateMachine.sendMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -632,8 +665,9 @@ public class CsipSetCoordinatorStateMachineTest { private void initToConnectingState() { allowConnection(true); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTING; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -643,8 +677,9 @@ public class CsipSetCoordinatorStateMachineTest { private void initToConnectedState() { allowConnection(true); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_CONNECTED; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -654,8 +689,9 @@ public class CsipSetCoordinatorStateMachineTest { private void initToDisconnectingState() { initToConnectingState(); - CsipSetCoordinatorStackEvent event = new CsipSetCoordinatorStackEvent( - CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + CsipSetCoordinatorStackEvent event = + new CsipSetCoordinatorStackEvent( + CsipSetCoordinatorStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt1 = CsipSetCoordinatorStackEvent.CONNECTION_STATE_DISCONNECTING; sendMessageAndVerifyTransition( mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.STACK_EVENT, event), @@ -673,9 +709,11 @@ public class CsipSetCoordinatorStateMachineTest { public static class CsipSetCoordinatorStateMachineWrapper extends CsipSetCoordinatorStateMachine { - CsipSetCoordinatorStateMachineWrapper(BluetoothDevice device, + CsipSetCoordinatorStateMachineWrapper( + BluetoothDevice device, CsipSetCoordinatorService svc, - CsipSetCoordinatorNativeInterface nativeInterface, Looper looper) { + CsipSetCoordinatorNativeInterface nativeInterface, + Looper looper) { super(device, svc, nativeInterface, looper); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/AdvertiseHelperTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/AdvertiseHelperTest.java index f432c3f2192..5f89c4b4cad 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/AdvertiseHelperTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/AdvertiseHelperTest.java @@ -32,9 +32,7 @@ import org.junit.runner.RunWith; import java.util.UUID; -/** - * Test cases for {@link AdvertiseHelper}. - */ +/** Test cases for {@link AdvertiseHelper}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class AdvertiseHelperTest { @@ -46,27 +44,23 @@ public class AdvertiseHelperTest { assertThat(emptyBytes.length).isEqualTo(0); int manufacturerId = 1; - byte[] manufacturerData = new byte[]{ - 0x30, 0x31, 0x32, 0x34 - }; - - byte[] serviceData = new byte[]{ - 0x10, 0x12, 0x14 - }; - - byte[] transportDiscoveryData = new byte[]{ - 0x40, 0x44, 0x48 - }; - - AdvertiseData advertiseData = new AdvertiseData.Builder() - .setIncludeDeviceName(true) - .addManufacturerData(manufacturerId, manufacturerData) - .setIncludeTxPowerLevel(true) - .addServiceUuid(new ParcelUuid(UUID.randomUUID())) - .addServiceData(new ParcelUuid(UUID.randomUUID()), serviceData) - .addServiceSolicitationUuid(new ParcelUuid(UUID.randomUUID())) - .addTransportDiscoveryData(new TransportDiscoveryData(transportDiscoveryData)) - .build(); + byte[] manufacturerData = new byte[] {0x30, 0x31, 0x32, 0x34}; + + byte[] serviceData = new byte[] {0x10, 0x12, 0x14}; + + byte[] transportDiscoveryData = new byte[] {0x40, 0x44, 0x48}; + + AdvertiseData advertiseData = + new AdvertiseData.Builder() + .setIncludeDeviceName(true) + .addManufacturerData(manufacturerId, manufacturerData) + .setIncludeTxPowerLevel(true) + .addServiceUuid(new ParcelUuid(UUID.randomUUID())) + .addServiceData(new ParcelUuid(UUID.randomUUID()), serviceData) + .addServiceSolicitationUuid(new ParcelUuid(UUID.randomUUID())) + .addTransportDiscoveryData( + new TransportDiscoveryData(transportDiscoveryData)) + .build(); String deviceName = "TestDeviceName"; int expectedAdvDataBytesLength = 86; @@ -77,17 +71,14 @@ public class AdvertiseHelperTest { assertThat(advDataBytes.length).isEqualTo(expectedAdvDataBytesLength); int expectedAdvDataBytesLongNameLength = 98; - byte[] advDataBytesLongName = AdvertiseHelper - .advertiseDataToBytes(advertiseData, deviceNameLong); + byte[] advDataBytesLongName = + AdvertiseHelper.advertiseDataToBytes(advertiseData, deviceNameLong); assertThat(advDataBytesLongName.length).isEqualTo(expectedAdvDataBytesLongNameLength); } @Test public void checkLength_withGT255_throwsException() { - assertThrows( - IllegalArgumentException.class, - () -> AdvertiseHelper.check_length(0X00, 256) - ); + assertThrows(IllegalArgumentException.class, () -> AdvertiseHelper.check_length(0X00, 256)); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/AdvertiseManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/AdvertiseManagerTest.java index 0fdfd3cd8a0..ecafc2c88d2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/AdvertiseManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/AdvertiseManagerTest.java @@ -16,7 +16,6 @@ package com.android.bluetooth.gatt; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; @@ -44,31 +43,24 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -/** - * Test cases for {@link AdvertiseManager}. - */ +/** Test cases for {@link AdvertiseManager}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class AdvertiseManagerTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private AdapterService mAdapterService; + @Mock private AdapterService mAdapterService; - @Mock - private GattService mService; + @Mock private GattService mService; - @Mock - private GattService.AdvertiserMap mAdvertiserMap; + @Mock private GattService.AdvertiserMap mAdvertiserMap; @Mock private AdvertiseManagerNativeInterface mNativeInterface; - @Mock - private IAdvertisingSetCallback mCallback; + @Mock private IAdvertisingSetCallback mCallback; - @Mock - private IBinder mBinder; + @Mock private IBinder mBinder; private AdvertiseManager mAdvertiseManager; private int mAdvertiserId; @@ -92,8 +84,16 @@ public class AdvertiseManagerTest { doReturn(mBinder).when(mCallback).asBinder(); doNothing().when(mBinder).linkToDeath(any(), eq(0)); - mAdvertiseManager.startAdvertisingSet(parameters, advertiseData, scanResponse, - periodicParameters, periodicData, duration, maxExtAdvEvents, 0, mCallback); + mAdvertiseManager.startAdvertisingSet( + parameters, + advertiseData, + scanResponse, + periodicParameters, + periodicData, + duration, + maxExtAdvEvents, + 0, + mCallback); mAdvertiserId = AdvertiseManager.sTempRegistrationId; } @@ -111,8 +111,8 @@ public class AdvertiseManagerTest { mAdvertiseManager.enableAdvertisingSet(mAdvertiserId, enable, duration, maxExtAdvEvents); - verify(mAdvertiserMap).enableAdvertisingSet(mAdvertiserId, enable, duration, - maxExtAdvEvents); + verify(mAdvertiserMap) + .enableAdvertisingSet(mAdvertiserId, enable, duration, maxExtAdvEvents); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/AppAdvertiseStatsTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/AppAdvertiseStatsTest.java index 6c6ad1cf562..eee79a79043 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/AppAdvertiseStatsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/AppAdvertiseStatsTest.java @@ -42,23 +42,18 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -/** - * Test cases for {@link AppAdvertiseStats}. - */ +/** Test cases for {@link AppAdvertiseStats}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class AppAdvertiseStatsTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private ContextMap map; + @Mock private ContextMap map; - @Mock - private GattService service; + @Mock private GattService service; - @Mock - private MetricsLogger mMetricsLogger; + @Mock private MetricsLogger mMetricsLogger; @Before public void setUp() throws Exception { @@ -89,8 +84,7 @@ public class AppAdvertiseStatsTest { AppAdvertiseStats appAdvertiseStats = new AppAdvertiseStats(id, name, map, service); - assertThat(appAdvertiseStats.mAdvertiserRecords.size()) - .isEqualTo(0); + assertThat(appAdvertiseStats.mAdvertiserRecords.size()).isEqualTo(0); int duration = 1; int maxExtAdvEvents = 2; @@ -111,13 +105,11 @@ public class AppAdvertiseStatsTest { periodicParameters, periodicData, duration, - maxExtAdvEvents - ); + maxExtAdvEvents); int numOfExpectedRecords = 2; - assertThat(appAdvertiseStats.mAdvertiserRecords.size()) - .isEqualTo(numOfExpectedRecords); + assertThat(appAdvertiseStats.mAdvertiserRecords.size()).isEqualTo(numOfExpectedRecords); } @Test @@ -130,8 +122,7 @@ public class AppAdvertiseStatsTest { int duration = 1; int maxExtAdvEvents = 2; - assertThat(appAdvertiseStats.mAdvertiserRecords.size()) - .isEqualTo(0); + assertThat(appAdvertiseStats.mAdvertiserRecords.size()).isEqualTo(0); appAdvertiseStats.recordAdvertiseStart(duration, maxExtAdvEvents); @@ -149,15 +140,13 @@ public class AppAdvertiseStatsTest { periodicParameters, periodicData, duration, - maxExtAdvEvents - ); + maxExtAdvEvents); appAdvertiseStats.recordAdvertiseStop(); int numOfExpectedRecords = 2; - assertThat(appAdvertiseStats.mAdvertiserRecords.size()) - .isEqualTo(numOfExpectedRecords); + assertThat(appAdvertiseStats.mAdvertiserRecords.size()).isEqualTo(numOfExpectedRecords); } @Test @@ -170,16 +159,14 @@ public class AppAdvertiseStatsTest { int duration = 1; int maxExtAdvEvents = 2; - assertThat(appAdvertiseStats.mAdvertiserRecords.size()) - .isEqualTo(0); + assertThat(appAdvertiseStats.mAdvertiserRecords.size()).isEqualTo(0); appAdvertiseStats.enableAdvertisingSet(true, duration, maxExtAdvEvents); appAdvertiseStats.enableAdvertisingSet(false, duration, maxExtAdvEvents); int numOfExpectedRecords = 1; - assertThat(appAdvertiseStats.mAdvertiserRecords.size()) - .isEqualTo(numOfExpectedRecords); + assertThat(appAdvertiseStats.mAdvertiserRecords.size()).isEqualTo(numOfExpectedRecords); } @Test @@ -269,8 +256,7 @@ public class AppAdvertiseStatsTest { periodicParameters, periodicData, duration, - maxExtAdvEvents - ); + maxExtAdvEvents); AppAdvertiseStats.dumpToString(sb, appAdvertiseStats); } @@ -282,8 +268,8 @@ public class AppAdvertiseStatsTest { AppAdvertiseStats appAdvertiseStats = new AppAdvertiseStats(id, name, map, service); - AdvertisingSetParameters parameters = new AdvertisingSetParameters.Builder() - .setConnectable(true).build(); + AdvertisingSetParameters parameters = + new AdvertisingSetParameters.Builder().setConnectable(true).build(); AdvertiseData advertiseData = new AdvertiseData.Builder().build(); AdvertiseData scanResponse = new AdvertiseData.Builder().build(); PeriodicAdvertisingParameters periodicParameters = @@ -291,34 +277,29 @@ public class AppAdvertiseStatsTest { AdvertiseData periodicData = new AdvertiseData.Builder().build(); appAdvertiseStats.recordAdvertiseStart( - parameters, - advertiseData, - scanResponse, - periodicParameters, - periodicData, - 0, - 0 - ); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_COUNT_ENABLE), eq((long) 1)); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_COUNT_CONNECTABLE_ENABLE), eq((long)1)); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_COUNT_PERIODIC_ENABLE), eq((long) 1)); + parameters, advertiseData, scanResponse, periodicParameters, periodicData, 0, 0); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.LE_ADV_COUNT_ENABLE), eq((long) 1)); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.LE_ADV_COUNT_CONNECTABLE_ENABLE), eq((long) 1)); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.LE_ADV_COUNT_PERIODIC_ENABLE), eq((long) 1)); Mockito.clearInvocations(mMetricsLogger); appAdvertiseStats.recordAdvertiseStop(); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_COUNT_DISABLE), eq((long) 1)); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_COUNT_CONNECTABLE_DISABLE), eq((long)1)); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_COUNT_PERIODIC_DISABLE), eq((long) 1)); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_DURATION_COUNT_TOTAL_1M), eq((long) 1)); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_DURATION_COUNT_CONNECTABLE_1M), eq((long) 1)); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.LE_ADV_DURATION_COUNT_PERIODIC_1M), eq((long) 1)); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.LE_ADV_COUNT_DISABLE), eq((long) 1)); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.LE_ADV_COUNT_CONNECTABLE_DISABLE), eq((long) 1)); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.LE_ADV_COUNT_PERIODIC_DISABLE), eq((long) 1)); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.LE_ADV_DURATION_COUNT_TOTAL_1M), eq((long) 1)); + verify(mMetricsLogger, times(1)) + .cacheCount( + eq(BluetoothProtoEnums.LE_ADV_DURATION_COUNT_CONNECTABLE_1M), eq((long) 1)); + verify(mMetricsLogger, times(1)) + .cacheCount( + eq(BluetoothProtoEnums.LE_ADV_DURATION_COUNT_PERIODIC_1M), eq((long) 1)); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/CallbackInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/CallbackInfoTest.java index dea410cd8a3..b23cbc8b8fb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/CallbackInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/CallbackInfoTest.java @@ -26,9 +26,7 @@ import org.junit.runner.RunWith; import java.util.Arrays; -/** - * Test cases for {@link CallbackInfo}. - */ +/** Test cases for {@link CallbackInfo}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class CallbackInfoTest { @@ -40,10 +38,8 @@ public class CallbackInfoTest { int handle = 1; byte[] value = "Test Value Byte Array".getBytes(); - CallbackInfo callbackInfo = new CallbackInfo.Builder(address, status) - .setHandle(handle) - .setValue(value) - .build(); + CallbackInfo callbackInfo = + new CallbackInfo.Builder(address, status).setHandle(handle).setValue(value).build(); assertThat(callbackInfo.address).isEqualTo(address); assertThat(callbackInfo.status).isEqualTo(status); diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/ContextMapTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/ContextMapTest.java index 2dc195687cc..4c6f758db0f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/ContextMapTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/ContextMapTest.java @@ -49,16 +49,13 @@ import org.mockito.junit.MockitoRule; import java.util.UUID; -/** - * Test cases for {@link ContextMap}. - */ +/** Test cases for {@link ContextMap}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class ContextMapTest { private static final String APP_NAME = "com.android.what.a.name"; - @Rule - public final ServiceTestRule mServiceRule = new ServiceTestRule(); + @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule(); @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @@ -68,8 +65,7 @@ public class ContextMapTest { @Mock private TransitionalScanHelper mMockScanHelper; @Mock private PackageManager mMockPackageManager; - @Spy - private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); + @Spy private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); @Before public void setUp() throws Exception { diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java index 077d2b9f4b4..829b39e9c7a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java @@ -50,9 +50,7 @@ import org.mockito.junit.MockitoRule; import java.util.UUID; -/** - * Test cases for {@link DistanceMeasurementManager}. - */ +/** Test cases for {@link DistanceMeasurementManager}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class DistanceMeasurementManagerTest { @@ -85,98 +83,119 @@ public class DistanceMeasurementManagerTest { @Test public void testStartRssiTracker() { - DistanceMeasurementParams params = new DistanceMeasurementParams.Builder(mDevice) - .setDurationSeconds(1000) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) - .build(); + DistanceMeasurementParams params = + new DistanceMeasurementParams.Builder(mDevice) + .setDurationSeconds(1000) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) + .build(); mDistanceMeasurementManager.startDistanceMeasurement(mUuid, params, mCallback); - verify(mDistanceMeasurementNativeInterface).startDistanceMeasurement( - IDENTITY_ADDRESS, RSSI_FREQUENCY_LOW, - DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); + verify(mDistanceMeasurementNativeInterface) + .startDistanceMeasurement( + IDENTITY_ADDRESS, + RSSI_FREQUENCY_LOW, + DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); } @Test public void testStopRssiTracker() { - DistanceMeasurementParams params = new DistanceMeasurementParams.Builder(mDevice) - .setDurationSeconds(1000) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) - .build(); + DistanceMeasurementParams params = + new DistanceMeasurementParams.Builder(mDevice) + .setDurationSeconds(1000) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) + .build(); mDistanceMeasurementManager.startDistanceMeasurement(mUuid, params, mCallback); - mDistanceMeasurementManager.stopDistanceMeasurement(mUuid, mDevice, - DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI, false); - verify(mDistanceMeasurementNativeInterface).stopDistanceMeasurement( - IDENTITY_ADDRESS, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); + mDistanceMeasurementManager.stopDistanceMeasurement( + mUuid, mDevice, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI, false); + verify(mDistanceMeasurementNativeInterface) + .stopDistanceMeasurement( + IDENTITY_ADDRESS, + DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); } @Test public void testHandleRssiStarted() throws RemoteException { - DistanceMeasurementParams params = new DistanceMeasurementParams.Builder(mDevice) - .setDurationSeconds(1000) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) - .build(); + DistanceMeasurementParams params = + new DistanceMeasurementParams.Builder(mDevice) + .setDurationSeconds(1000) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) + .build(); mDistanceMeasurementManager.startDistanceMeasurement(mUuid, params, mCallback); - verify(mDistanceMeasurementNativeInterface).startDistanceMeasurement( - IDENTITY_ADDRESS, RSSI_FREQUENCY_LOW, - DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); - mDistanceMeasurementManager.onDistanceMeasurementStarted(IDENTITY_ADDRESS, - DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); + verify(mDistanceMeasurementNativeInterface) + .startDistanceMeasurement( + IDENTITY_ADDRESS, + RSSI_FREQUENCY_LOW, + DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); + mDistanceMeasurementManager.onDistanceMeasurementStarted( + IDENTITY_ADDRESS, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); verify(mCallback).onStarted(mDevice); } @Test public void testHandleRssiStartFail() throws RemoteException { - DistanceMeasurementParams params = new DistanceMeasurementParams.Builder(mDevice) - .setDurationSeconds(1000) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) - .build(); + DistanceMeasurementParams params = + new DistanceMeasurementParams.Builder(mDevice) + .setDurationSeconds(1000) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) + .build(); mDistanceMeasurementManager.startDistanceMeasurement(mUuid, params, mCallback); - verify(mDistanceMeasurementNativeInterface).startDistanceMeasurement( - IDENTITY_ADDRESS, RSSI_FREQUENCY_LOW, - DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); - mDistanceMeasurementManager.onDistanceMeasurementStartFail(IDENTITY_ADDRESS, + verify(mDistanceMeasurementNativeInterface) + .startDistanceMeasurement( + IDENTITY_ADDRESS, + RSSI_FREQUENCY_LOW, + DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); + mDistanceMeasurementManager.onDistanceMeasurementStartFail( + IDENTITY_ADDRESS, BluetoothStatusCodes.ERROR_DISTANCE_MEASUREMENT_INTERNAL, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); - verify(mCallback).onStartFail(mDevice, - BluetoothStatusCodes.ERROR_DISTANCE_MEASUREMENT_INTERNAL); + verify(mCallback) + .onStartFail(mDevice, BluetoothStatusCodes.ERROR_DISTANCE_MEASUREMENT_INTERNAL); } @Test public void testHandleRssiStopped() throws RemoteException { - DistanceMeasurementParams params = new DistanceMeasurementParams.Builder(mDevice) - .setDurationSeconds(1000) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) - .build(); + DistanceMeasurementParams params = + new DistanceMeasurementParams.Builder(mDevice) + .setDurationSeconds(1000) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) + .build(); mDistanceMeasurementManager.startDistanceMeasurement(mUuid, params, mCallback); - mDistanceMeasurementManager.onDistanceMeasurementStarted(IDENTITY_ADDRESS, - DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); + mDistanceMeasurementManager.onDistanceMeasurementStarted( + IDENTITY_ADDRESS, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); verify(mCallback).onStarted(mDevice); - mDistanceMeasurementManager.onDistanceMeasurementStopped(IDENTITY_ADDRESS, + mDistanceMeasurementManager.onDistanceMeasurementStopped( + IDENTITY_ADDRESS, BluetoothStatusCodes.REASON_REMOTE_REQUEST, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); - verify(mCallback).onStopped(mDevice, - BluetoothStatusCodes.REASON_REMOTE_REQUEST); + verify(mCallback).onStopped(mDevice, BluetoothStatusCodes.REASON_REMOTE_REQUEST); } @Test public void testHandleRssiResult() throws RemoteException { - DistanceMeasurementParams params = new DistanceMeasurementParams.Builder(mDevice) - .setDurationSeconds(1000) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) - .build(); + DistanceMeasurementParams params = + new DistanceMeasurementParams.Builder(mDevice) + .setDurationSeconds(1000) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .setMethodId(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) + .build(); mDistanceMeasurementManager.startDistanceMeasurement(mUuid, params, mCallback); - mDistanceMeasurementManager.onDistanceMeasurementStarted(IDENTITY_ADDRESS, - DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); + mDistanceMeasurementManager.onDistanceMeasurementStarted( + IDENTITY_ADDRESS, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); verify(mCallback).onStarted(mDevice); - mDistanceMeasurementManager.onDistanceMeasurementResult(IDENTITY_ADDRESS, - 100, 100, -1, -1, -1, -1, + mDistanceMeasurementManager.onDistanceMeasurementResult( + IDENTITY_ADDRESS, + 100, + 100, + -1, + -1, + -1, + -1, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); ArgumentCaptor result = ArgumentCaptor.forClass(DistanceMeasurementResult.class); @@ -191,21 +210,31 @@ public class DistanceMeasurementManagerTest { @Test public void testReceivedResultAfterStopped() throws RemoteException { - DistanceMeasurementParams params = new DistanceMeasurementParams.Builder(mDevice) - .setDurationSeconds(1000) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .setDurationSeconds(DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) - .build(); + DistanceMeasurementParams params = + new DistanceMeasurementParams.Builder(mDevice) + .setDurationSeconds(1000) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .setDurationSeconds( + DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI) + .build(); mDistanceMeasurementManager.startDistanceMeasurement(mUuid, params, mCallback); - mDistanceMeasurementManager.stopDistanceMeasurement(mUuid, mDevice, - DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI, false); - verify(mDistanceMeasurementNativeInterface).stopDistanceMeasurement( - IDENTITY_ADDRESS, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); - mDistanceMeasurementManager.onDistanceMeasurementResult(IDENTITY_ADDRESS, - 100, 100, -1, -1, -1, -1, + mDistanceMeasurementManager.stopDistanceMeasurement( + mUuid, mDevice, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI, false); + verify(mDistanceMeasurementNativeInterface) + .stopDistanceMeasurement( + IDENTITY_ADDRESS, + DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); + mDistanceMeasurementManager.onDistanceMeasurementResult( + IDENTITY_ADDRESS, + 100, + 100, + -1, + -1, + -1, + -1, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI); - DistanceMeasurementResult result = new DistanceMeasurementResult.Builder( - 1.00, 1.00).build(); + DistanceMeasurementResult result = + new DistanceMeasurementResult.Builder(1.00, 1.00).build(); verify(mCallback, after(100).never()).onResult(mDevice, result); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementTrackerTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementTrackerTest.java index 603b20fe457..28bc62038da 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementTrackerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementTrackerTest.java @@ -43,9 +43,7 @@ import org.mockito.junit.MockitoRule; import java.util.UUID; -/** - * Test cases for {@link DistanceMeasurementTracker}. - */ +/** Test cases for {@link DistanceMeasurementTracker}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class DistanceMeasurementTrackerTest { @@ -67,13 +65,20 @@ public class DistanceMeasurementTrackerTest { public void setUp() throws Exception { mUuid = UUID.randomUUID(); mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(IDENTITY_ADDRESS); - mParams = new DistanceMeasurementParams.Builder(mDevice) - .setDurationSeconds(TIMEOUT_S) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .setMethodId(mMethod) - .build(); - mTracker = new DistanceMeasurementTracker( - mDistanceMeasurementManager, mParams, IDENTITY_ADDRESS, mUuid, 1000, mCallback); + mParams = + new DistanceMeasurementParams.Builder(mDevice) + .setDurationSeconds(TIMEOUT_S) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .setMethodId(mMethod) + .build(); + mTracker = + new DistanceMeasurementTracker( + mDistanceMeasurementManager, + mParams, + IDENTITY_ADDRESS, + mUuid, + 1000, + mCallback); mHandlerThread = new HandlerThread("DistanceMeasurementTrackerTestHandlerThread"); mHandlerThread.start(); } @@ -95,21 +100,33 @@ public class DistanceMeasurementTrackerTest { public void testCancelTimer() { mTracker.startTimer(mHandlerThread.getLooper()); mTracker.cancelTimer(); - verify(mDistanceMeasurementManager, after(TIMEOUT_MS).never()).stopDistanceMeasurement( - mUuid, mDevice, mMethod, true); + verify(mDistanceMeasurementManager, after(TIMEOUT_MS).never()) + .stopDistanceMeasurement(mUuid, mDevice, mMethod, true); } @Test public void testEquals() { - DistanceMeasurementTracker tracker = new DistanceMeasurementTracker( - mDistanceMeasurementManager, mParams, IDENTITY_ADDRESS, mUuid, 1000, mCallback); + DistanceMeasurementTracker tracker = + new DistanceMeasurementTracker( + mDistanceMeasurementManager, + mParams, + IDENTITY_ADDRESS, + mUuid, + 1000, + mCallback); assertThat(mTracker.equals(tracker)).isTrue(); } @Test public void testHashCode() { - DistanceMeasurementTracker tracker = new DistanceMeasurementTracker( - mDistanceMeasurementManager, mParams, IDENTITY_ADDRESS, mUuid, 1000, mCallback); + DistanceMeasurementTracker tracker = + new DistanceMeasurementTracker( + mDistanceMeasurementManager, + mParams, + IDENTITY_ADDRESS, + mUuid, + 1000, + mCallback); assertThat(mTracker.hashCode()).isEqualTo(tracker.hashCode()); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/FilterParamsTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/FilterParamsTest.java index 3033c12a5d0..84aebeafa6f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/FilterParamsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/FilterParamsTest.java @@ -24,9 +24,7 @@ import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; -/** - * Test cases for {@link FilterParams}. - */ +/** Test cases for {@link FilterParams}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class FilterParamsTest { @@ -46,20 +44,20 @@ public class FilterParamsTest { int foundTimeOutCnt = 10; int numOfTrackEntries = 11; - FilterParams filterParams = new FilterParams( - clientIf, - filtIndex, - featSeln, - listLogicType, - filtLogicType, - rssiHighValue, - rssiLowValue, - delyMode, - foundTimeOut, - lostTimeOut, - foundTimeOutCnt, - numOfTrackEntries - ); + FilterParams filterParams = + new FilterParams( + clientIf, + filtIndex, + featSeln, + listLogicType, + filtLogicType, + rssiHighValue, + rssiLowValue, + delyMode, + foundTimeOut, + lostTimeOut, + foundTimeOutCnt, + numOfTrackEntries); assertThat(filterParams).isNotNull(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattDebugUtilsTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattDebugUtilsTest.java index 8d7f4aafe7d..dbf2e5c167c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattDebugUtilsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattDebugUtilsTest.java @@ -32,17 +32,14 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -/** - * Test cases for {@link GattDebugUtils}. - */ +/** Test cases for {@link GattDebugUtils}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class GattDebugUtilsTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private GattService mService; + @Mock private GattService mService; @Test public void handleDebugAction() { @@ -79,7 +76,7 @@ public class GattDebugUtilsTest { int initKey = 7; int respKey = 7; int maxKey = 16; - verify(mService).gattTestCommand(0xF0, null, null, authReq, ioCap, initKey, respKey, - maxKey); + verify(mService) + .gattTestCommand(0xF0, null, null, authReq, ioCap, initKey, respKey, maxKey); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java index 218dce7bc9f..0e2a2de3728 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java @@ -68,8 +68,7 @@ public class GattServiceBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private GattService mService; + @Mock private GattService mService; @Mock private TransitionalScanHelper mScanHelper; private Context mContext; @@ -83,8 +82,8 @@ public class GattServiceBinderTest { public void setUp() throws Exception { mContext = InstrumentationRegistry.getTargetContext(); Intent intent = new Intent(); - mPendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, - PendingIntent.FLAG_IMMUTABLE); + mPendingIntent = + PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_IMMUTABLE); when(mService.isAvailable()).thenReturn(true); when(mService.getTransitionalScanHelper()).thenReturn(mScanHelper); mBinder = new GattService.BluetoothGattBinder(mService); @@ -207,8 +206,16 @@ public class GattServiceBinderTest { phy, mAttributionSource); - verify(mService).clientConnect(clientIf, address, addressType, isDirect, transport, - opportunistic, phy, mAttributionSource); + verify(mService) + .clientConnect( + clientIf, + address, + addressType, + isDirect, + transport, + opportunistic, + phy, + mAttributionSource); } @Test @@ -232,8 +239,9 @@ public class GattServiceBinderTest { mBinder.clientSetPreferredPhy( clientIf, address, txPhy, rxPhy, phyOptions, mAttributionSource); - verify(mService).clientSetPreferredPhy(clientIf, address, txPhy, rxPhy, phyOptions, - mAttributionSource); + verify(mService) + .clientSetPreferredPhy( + clientIf, address, txPhy, rxPhy, phyOptions, mAttributionSource); } @Test @@ -307,8 +315,15 @@ public class GattServiceBinderTest { authReq, mAttributionSource); - verify(mService).readUsingCharacteristicUuid(clientIf, address, uuid, startHandle, - endHandle, authReq, mAttributionSource); + verify(mService) + .readUsingCharacteristicUuid( + clientIf, + address, + uuid, + startHandle, + endHandle, + authReq, + mAttributionSource); } @Test @@ -323,8 +338,9 @@ public class GattServiceBinderTest { mBinder.writeCharacteristic( clientIf, address, handle, writeType, authReq, value, mAttributionSource); - verify(mService).writeCharacteristic(clientIf, address, handle, writeType, authReq, value, - mAttributionSource); + verify(mService) + .writeCharacteristic( + clientIf, address, handle, writeType, authReq, value, mAttributionSource); } @Test @@ -349,8 +365,8 @@ public class GattServiceBinderTest { mBinder.writeDescriptor(clientIf, address, handle, authReq, value, mAttributionSource); - verify(mService).writeDescriptor(clientIf, address, handle, authReq, value, - mAttributionSource); + verify(mService) + .writeDescriptor(clientIf, address, handle, authReq, value, mAttributionSource); } @Test @@ -383,8 +399,8 @@ public class GattServiceBinderTest { mBinder.registerForNotification(clientIf, address, handle, enable, mAttributionSource); - verify(mService).registerForNotification(clientIf, address, handle, enable, - mAttributionSource); + verify(mService) + .registerForNotification(clientIf, address, handle, enable, mAttributionSource); } @Test @@ -417,8 +433,9 @@ public class GattServiceBinderTest { mBinder.connectionParameterUpdate( clientIf, address, connectionPriority, mAttributionSource); - verify(mService).connectionParameterUpdate(clientIf, address, connectionPriority, - mAttributionSource); + verify(mService) + .connectionParameterUpdate( + clientIf, address, connectionPriority, mAttributionSource); } @Test @@ -443,10 +460,17 @@ public class GattServiceBinderTest { maxConnectionEventLen, mAttributionSource); - verify(mService).leConnectionUpdate( - clientIf, address, minConnectionInterval, maxConnectionInterval, - peripheralLatency, supervisionTimeout, minConnectionEventLen, - maxConnectionEventLen, mAttributionSource); + verify(mService) + .leConnectionUpdate( + clientIf, + address, + minConnectionInterval, + maxConnectionInterval, + peripheralLatency, + supervisionTimeout, + minConnectionEventLen, + maxConnectionEventLen, + mAttributionSource); } @Test @@ -506,8 +530,9 @@ public class GattServiceBinderTest { mBinder.serverSetPreferredPhy( serverIf, address, txPhy, rxPhy, phyOptions, mAttributionSource); - verify(mService).serverSetPreferredPhy(serverIf, address, txPhy, rxPhy, phyOptions, - mAttributionSource); + verify(mService) + .serverSetPreferredPhy( + serverIf, address, txPhy, rxPhy, phyOptions, mAttributionSource); } @Test @@ -561,8 +586,9 @@ public class GattServiceBinderTest { mBinder.sendResponse( serverIf, address, requestId, status, offset, value, mAttributionSource); - verify(mService).sendResponse(serverIf, address, requestId, status, offset, value, - mAttributionSource); + verify(mService) + .sendResponse( + serverIf, address, requestId, status, offset, value, mAttributionSource); } @Test @@ -575,8 +601,8 @@ public class GattServiceBinderTest { mBinder.sendNotification(serverIf, address, handle, confirm, value, mAttributionSource); - verify(mService).sendNotification(serverIf, address, handle, confirm, value, - mAttributionSource); + verify(mService) + .sendNotification(serverIf, address, handle, confirm, value, mAttributionSource); } @Test @@ -604,9 +630,18 @@ public class GattServiceBinderTest { callback, mAttributionSource); - verify(mService).startAdvertisingSet(parameters, advertiseData, scanResponse, - periodicParameters, periodicData, duration, maxExtAdvEvents, - serverIf, callback, mAttributionSource); + verify(mService) + .startAdvertisingSet( + parameters, + advertiseData, + scanResponse, + periodicParameters, + periodicData, + duration, + maxExtAdvEvents, + serverIf, + callback, + mAttributionSource); } @Test @@ -637,8 +672,9 @@ public class GattServiceBinderTest { mBinder.enableAdvertisingSet( advertiserId, enable, duration, maxExtAdvEvents, mAttributionSource); - verify(mService).enableAdvertisingSet(advertiserId, enable, duration, maxExtAdvEvents, - mAttributionSource); + verify(mService) + .enableAdvertisingSet( + advertiserId, enable, duration, maxExtAdvEvents, mAttributionSource); } @Test @@ -679,8 +715,8 @@ public class GattServiceBinderTest { mBinder.setPeriodicAdvertisingParameters(advertiserId, parameters, mAttributionSource); - verify(mService).setPeriodicAdvertisingParameters(advertiserId, parameters, - mAttributionSource); + verify(mService) + .setPeriodicAdvertisingParameters(advertiserId, parameters, mAttributionSource); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java index d3b15802e03..8d33f570630 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java @@ -69,9 +69,7 @@ import java.util.Map; import java.util.Set; import java.util.UUID; -/** - * Test cases for {@link GattService}. - */ +/** Test cases for {@link GattService}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class GattServiceTest { @@ -120,7 +118,8 @@ public class GattServiceTest { GattObjectsFactory.setInstanceForTesting(mFactory); doReturn(mNativeInterface).when(mFactory).getNativeInterface(); doReturn(mScanManager).when(mFactory).createScanManager(any(), any(), any(), any(), any()); - doReturn(mDistanceMeasurementManager).when(mFactory) + doReturn(mDistanceMeasurementManager) + .when(mFactory) .createDistanceMeasurementManager(any()); mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -130,8 +129,10 @@ public class GattServiceTest { when(mAdapterService.getResources()).thenReturn(mResources); when(mResources.getInteger(anyInt())).thenReturn(0); when(mAdapterService.getSharedPreferences(anyString(), anyInt())) - .thenReturn(InstrumentationRegistry.getTargetContext() - .getSharedPreferences("GattServiceTestPrefs", Context.MODE_PRIVATE)); + .thenReturn( + InstrumentationRegistry.getTargetContext() + .getSharedPreferences( + "GattServiceTestPrefs", Context.MODE_PRIVATE)); TestUtils.mockGetSystemService( mAdapterService, Context.LOCATION_SERVICE, LocationManager.class); @@ -205,10 +206,10 @@ public class GattServiceTest { Integer connId = 1; doReturn(connId).when(mClientMap).connIdByAddress(clientIf, address); - mService.clientSetPreferredPhy(clientIf, address, txPhy, rxPhy, phyOptions, - mAttributionSource); - verify(mNativeInterface).gattClientSetPreferredPhy(clientIf, address, txPhy, rxPhy, - phyOptions); + mService.clientSetPreferredPhy( + clientIf, address, txPhy, rxPhy, phyOptions, mAttributionSource); + verify(mNativeInterface) + .gattClientSetPreferredPhy(clientIf, address, txPhy, rxPhy, phyOptions); } @Test @@ -217,19 +218,27 @@ public class GattServiceTest { String address = REMOTE_DEVICE_ADDRESS; int connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_HIGH; - mService.connectionParameterUpdate(clientIf, address, connectionPriority, - mAttributionSource); + mService.connectionParameterUpdate( + clientIf, address, connectionPriority, mAttributionSource); connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER; - mService.connectionParameterUpdate(clientIf, address, connectionPriority, - mAttributionSource); + mService.connectionParameterUpdate( + clientIf, address, connectionPriority, mAttributionSource); connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_BALANCED; - mService.connectionParameterUpdate(clientIf, address, connectionPriority, - mAttributionSource); + mService.connectionParameterUpdate( + clientIf, address, connectionPriority, mAttributionSource); - verify(mNativeInterface, times(3)).gattConnectionParameterUpdate(eq(clientIf), - eq(address), anyInt(), anyInt(), anyInt(), anyInt(), eq(0), eq(0)); + verify(mNativeInterface, times(3)) + .gattConnectionParameterUpdate( + eq(clientIf), + eq(address), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + eq(0), + eq(0)); } @Test @@ -247,11 +256,19 @@ public class GattServiceTest { boolean opportunistic = true; int phy = 3; - mService.clientConnect(clientIf, address, addressType, isDirect, transport, - opportunistic, phy, mAttributionSource); + mService.clientConnect( + clientIf, + address, + addressType, + isDirect, + transport, + opportunistic, + phy, + mAttributionSource); - verify(mNativeInterface).gattClientConnect(clientIf, address, addressType, - isDirect, transport, opportunistic, phy); + verify(mNativeInterface) + .gattClientConnect( + clientIf, address, addressType, isDirect, transport, opportunistic, phy); } @Test @@ -322,7 +339,7 @@ public class GattServiceTest { int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; BluetoothDevice testDevice = mAdapter.getRemoteDevice("00:01:02:03:04:05"); - BluetoothDevice[] bluetoothDevices = new BluetoothDevice[]{testDevice}; + BluetoothDevice[] bluetoothDevices = new BluetoothDevice[] {testDevice}; doReturn(bluetoothDevices).when(mAdapterService).getBondedDevices(); Set connectedDevices = new HashSet<>(); @@ -347,8 +364,9 @@ public class GattServiceTest { boolean eattSupport = true; mService.registerClient(uuid, callback, eattSupport, mAttributionSource); - verify(mNativeInterface).gattClientRegisterApp(uuid.getLeastSignificantBits(), - uuid.getMostSignificantBits(), eattSupport); + verify(mNativeInterface) + .gattClientRegisterApp( + uuid.getLeastSignificantBits(), uuid.getMostSignificantBits(), eattSupport); } @Test @@ -386,11 +404,16 @@ public class GattServiceTest { Integer connId = 1; doReturn(connId).when(mClientMap).connIdByAddress(clientIf, address); - mService.readUsingCharacteristicUuid(clientIf, address, uuid, startHandle, endHandle, - authReq, mAttributionSource); - verify(mNativeInterface).gattClientReadUsingCharacteristicUuid(connId, - uuid.getLeastSignificantBits(), uuid.getMostSignificantBits(), startHandle, - endHandle, authReq); + mService.readUsingCharacteristicUuid( + clientIf, address, uuid, startHandle, endHandle, authReq, mAttributionSource); + verify(mNativeInterface) + .gattClientReadUsingCharacteristicUuid( + connId, + uuid.getLeastSignificantBits(), + uuid.getMostSignificantBits(), + startHandle, + endHandle, + authReq); } @Test @@ -405,8 +428,9 @@ public class GattServiceTest { Integer connId = 1; doReturn(connId).when(mClientMap).connIdByAddress(clientIf, address); - int writeCharacteristicResult = mService.writeCharacteristic(clientIf, address, handle, - writeType, authReq, value, mAttributionSource); + int writeCharacteristicResult = + mService.writeCharacteristic( + clientIf, address, handle, writeType, authReq, value, mAttributionSource); assertThat(writeCharacteristicResult) .isEqualTo(BluetoothStatusCodes.ERROR_DEVICE_NOT_CONNECTED); } @@ -460,8 +484,8 @@ public class GattServiceTest { mService.registerForNotification(clientIf, address, handle, enable, mAttributionSource); - verify(mNativeInterface).gattClientRegisterForNotifications(clientIf, address, handle, - enable); + verify(mNativeInterface) + .gattClientRegisterForNotifications(clientIf, address, handle, enable); } @Test @@ -497,13 +521,27 @@ public class GattServiceTest { int minConnectionEventLen = 7; int maxConnectionEventLen = 8; - mService.leConnectionUpdate(clientIf, address, minInterval, maxInterval, - peripheralLatency, supervisionTimeout, minConnectionEventLen, - maxConnectionEventLen, mAttributionSource); + mService.leConnectionUpdate( + clientIf, + address, + minInterval, + maxInterval, + peripheralLatency, + supervisionTimeout, + minConnectionEventLen, + maxConnectionEventLen, + mAttributionSource); - verify(mNativeInterface).gattConnectionParameterUpdate(clientIf, address, minInterval, - maxInterval, peripheralLatency, supervisionTimeout, minConnectionEventLen, - maxConnectionEventLen); + verify(mNativeInterface) + .gattConnectionParameterUpdate( + clientIf, + address, + minInterval, + maxInterval, + peripheralLatency, + supervisionTimeout, + minConnectionEventLen, + maxConnectionEventLen); } @Test @@ -540,10 +578,10 @@ public class GattServiceTest { int rxPhy = 1; int phyOptions = 3; - mService.serverSetPreferredPhy(serverIf, address, txPhy, rxPhy, phyOptions, - mAttributionSource); - verify(mNativeInterface).gattServerSetPreferredPhy(serverIf, address, txPhy, rxPhy, - phyOptions); + mService.serverSetPreferredPhy( + serverIf, address, txPhy, rxPhy, phyOptions, mAttributionSource); + verify(mNativeInterface) + .gattServerSetPreferredPhy(serverIf, address, txPhy, rxPhy, phyOptions); } @Test @@ -589,8 +627,8 @@ public class GattServiceTest { int duration = 3; int maxExtAdvEvents = 4; - mService.enableAdvertisingSet(advertiserId, enable, duration, maxExtAdvEvents, - mAttributionSource); + mService.enableAdvertisingSet( + advertiserId, enable, duration, maxExtAdvEvents, mAttributionSource); } @Test @@ -621,10 +659,11 @@ public class GattServiceTest { public void startDistanceMeasurement() { UUID uuid = UUID.randomUUID(); BluetoothDevice device = mAdapter.getRemoteDevice("00:01:02:03:04:05"); - DistanceMeasurementParams params = new DistanceMeasurementParams.Builder(device) - .setDurationSeconds(123) - .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) - .build(); + DistanceMeasurementParams params = + new DistanceMeasurementParams.Builder(device) + .setDurationSeconds(123) + .setFrequency(DistanceMeasurementParams.REPORT_FREQUENCY_LOW) + .build(); IDistanceMeasurementCallback callback = mock(IDistanceMeasurementCallback.class); mService.startDistanceMeasurement(uuid, params, callback); verify(mDistanceMeasurementManager).startDistanceMeasurement(uuid, params, callback); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeInterfaceTest.java index 813a55a3097..7b219591ce6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeInterfaceTest.java @@ -35,11 +35,10 @@ import org.mockito.junit.MockitoRule; public class HapClientNativeInterfaceTest { private static final byte[] TEST_DEVICE_ADDRESS = - new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - HapClientService mService; + @Mock HapClientService mService; private HapClientNativeInterface mNativeInterface; @@ -63,8 +62,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); assertThat(event.getValue().valueInt1).isEqualTo(state); } @@ -76,8 +75,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_DEVICE_AVAILABLE); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_DEVICE_AVAILABLE); assertThat(event.getValue().valueInt1).isEqualTo(features); } @@ -89,8 +88,7 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_DEVICE_FEATURES); + assertThat(event.getValue().type).isEqualTo(HapClientStackEvent.EVENT_TYPE_DEVICE_FEATURES); assertThat(event.getValue().valueInt1).isEqualTo(features); } @@ -102,8 +100,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECTED); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECTED); assertThat(event.getValue().valueInt1).isEqualTo(presetIndex); } @@ -116,13 +114,12 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECTED); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECTED); assertThat(event.getValue().valueInt1).isEqualTo(presetIndex); assertThat(event.getValue().valueInt2).isEqualTo(groupId); } - @Test public void onActivePresetSelectError() { int resultCode = -1; @@ -131,8 +128,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECT_ERROR); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECT_ERROR); assertThat(event.getValue().valueInt1).isEqualTo(resultCode); } @@ -145,8 +142,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECT_ERROR); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECT_ERROR); assertThat(event.getValue().valueInt1).isEqualTo(resultCode); assertThat(event.getValue().valueInt2).isEqualTo(groupId); } @@ -154,18 +151,18 @@ public class HapClientNativeInterfaceTest { @Test public void onPresetInfo() { int infoReason = HapClientStackEvent.PRESET_INFO_REASON_ALL_PRESET_INFO; - BluetoothHapPresetInfo[] presets = - {new BluetoothHapPresetInfo.Builder(0x01, "onPresetInfo") - .setWritable(true) - .setAvailable(false) - .build()}; + BluetoothHapPresetInfo[] presets = { + new BluetoothHapPresetInfo.Builder(0x01, "onPresetInfo") + .setWritable(true) + .setAvailable(false) + .build() + }; mNativeInterface.onPresetInfo(TEST_DEVICE_ADDRESS, infoReason, presets); ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO); + assertThat(event.getValue().type).isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO); assertThat(event.getValue().valueInt2).isEqualTo(infoReason); assertThat(event.getValue().valueList.toArray()).isEqualTo(presets); } @@ -174,18 +171,18 @@ public class HapClientNativeInterfaceTest { public void onGroupPresetInfo() { int groupId = 100; int infoReason = HapClientStackEvent.PRESET_INFO_REASON_ALL_PRESET_INFO; - BluetoothHapPresetInfo[] presets = - {new BluetoothHapPresetInfo.Builder(0x01, "onPresetInfo") - .setWritable(true) - .setAvailable(false) - .build()}; + BluetoothHapPresetInfo[] presets = { + new BluetoothHapPresetInfo.Builder(0x01, "onPresetInfo") + .setWritable(true) + .setAvailable(false) + .build() + }; mNativeInterface.onGroupPresetInfo(groupId, infoReason, presets); ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO); + assertThat(event.getValue().type).isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO); assertThat(event.getValue().valueInt2).isEqualTo(infoReason); assertThat(event.getValue().valueInt3).isEqualTo(groupId); assertThat(event.getValue().valueList.toArray()).isEqualTo(presets); @@ -200,8 +197,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_PRESET_NAME_SET_ERROR); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_PRESET_NAME_SET_ERROR); assertThat(event.getValue().valueInt1).isEqualTo(resultCode); assertThat(event.getValue().valueInt2).isEqualTo(presetIndex); } @@ -216,8 +213,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_PRESET_NAME_SET_ERROR); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_PRESET_NAME_SET_ERROR); assertThat(event.getValue().valueInt1).isEqualTo(resultCode); assertThat(event.getValue().valueInt2).isEqualTo(presetIndex); assertThat(event.getValue().valueInt3).isEqualTo(groupId); @@ -232,8 +229,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO_ERROR); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO_ERROR); assertThat(event.getValue().valueInt1).isEqualTo(resultCode); assertThat(event.getValue().valueInt2).isEqualTo(presetIndex); } @@ -248,8 +245,8 @@ public class HapClientNativeInterfaceTest { ArgumentCaptor event = ArgumentCaptor.forClass(HapClientStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO_ERROR); + assertThat(event.getValue().type) + .isEqualTo(HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO_ERROR); assertThat(event.getValue().valueInt1).isEqualTo(resultCode); assertThat(event.getValue().valueInt2).isEqualTo(presetIndex); assertThat(event.getValue().valueInt3).isEqualTo(groupId); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientStackEventTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientStackEventTest.java index 20a6790e5a0..d307a5ce9e0 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientStackEventTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientStackEventTest.java @@ -25,141 +25,146 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class HapClientStackEventTest { - @Test - public void toString_containsProperSubStrings() { - HapClientStackEvent event; - String eventStr; - event = new HapClientStackEvent(0 /* EVENT_TYPE_NONE */); - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_NONE"); - - event = new HapClientStackEvent(10000); - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_UNKNOWN"); - - event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); - event.valueInt1 = -1; - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_CONNECTION_STATE_CHANGED"); - assertThat(eventStr).contains("CONNECTION_STATE_UNKNOWN"); - - event.valueInt1 = HapClientStackEvent.CONNECTION_STATE_DISCONNECTED; - eventStr = event.toString(); - assertThat(eventStr).contains("CONNECTION_STATE_DISCONNECTED"); - - event.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTING; - eventStr = event.toString(); - assertThat(eventStr).contains("CONNECTION_STATE_CONNECTING"); - - event.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTED; - eventStr = event.toString(); - assertThat(eventStr).contains("CONNECTION_STATE_CONNECTED"); - - event.valueInt1 = HapClientStackEvent.CONNECTION_STATE_DISCONNECTING; - eventStr = event.toString(); - assertThat(eventStr).contains("CONNECTION_STATE_DISCONNECTING"); - - event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_DEVICE_AVAILABLE); - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_DEVICE_AVAILABLE"); - - event.valueInt1 = 1 << HapClientStackEvent.FEATURE_BIT_NUM_TYPE_MONAURAL - | 1 << HapClientStackEvent.FEATURE_BIT_NUM_SYNCHRONIZATED_PRESETS; - eventStr = event.toString(); - assertThat(eventStr).contains("TYPE_MONAURAL"); - assertThat(eventStr).contains("SYNCHRONIZATED_PRESETS"); - - event.valueInt1 = 1 << HapClientStackEvent.FEATURE_BIT_NUM_TYPE_BANDED - | 1 << HapClientStackEvent.FEATURE_BIT_NUM_INDEPENDENT_PRESETS; - eventStr = event.toString(); - assertThat(eventStr).contains("TYPE_BANDED"); - assertThat(eventStr).contains("INDEPENDENT_PRESETS"); - - event.valueInt1 = 1 << HapClientStackEvent.FEATURE_BIT_NUM_DYNAMIC_PRESETS - | 1 << HapClientStackEvent.FEATURE_BIT_NUM_WRITABLE_PRESETS; - eventStr = event.toString(); - assertThat(eventStr).contains("TYPE_BINAURAL"); - assertThat(eventStr).contains("DYNAMIC_PRESETS"); - assertThat(eventStr).contains("WRITABLE_PRESETS"); - - event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_DEVICE_FEATURES); - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_DEVICE_FEATURES"); - - event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECTED); - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_ON_ACTIVE_PRESET_SELECTED"); - - event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECT_ERROR); - event.valueInt1 = -1; - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_ON_ACTIVE_PRESET_SELECT_ERROR"); - assertThat(eventStr).contains("ERROR_UNKNOWN"); - - event.valueInt1 = HapClientStackEvent.STATUS_NO_ERROR; - eventStr = event.toString(); - assertThat(eventStr).contains("STATUS_NO_ERROR"); - - event.valueInt1 = HapClientStackEvent.STATUS_SET_NAME_NOT_ALLOWED; - eventStr = event.toString(); - assertThat(eventStr).contains("STATUS_SET_NAME_NOT_ALLOWED"); - - event.valueInt1 = HapClientStackEvent.STATUS_OPERATION_NOT_SUPPORTED; - eventStr = event.toString(); - assertThat(eventStr).contains("STATUS_OPERATION_NOT_SUPPORTED"); - - event.valueInt1 = HapClientStackEvent.STATUS_OPERATION_NOT_POSSIBLE; - eventStr = event.toString(); - assertThat(eventStr).contains("STATUS_OPERATION_NOT_POSSIBLE"); - - event.valueInt1 = HapClientStackEvent.STATUS_INVALID_PRESET_NAME_LENGTH; - eventStr = event.toString(); - assertThat(eventStr).contains("STATUS_INVALID_PRESET_NAME_LENGTH"); - - event.valueInt1 = HapClientStackEvent.STATUS_INVALID_PRESET_INDEX; - eventStr = event.toString(); - assertThat(eventStr).contains("STATUS_INVALID_PRESET_INDEX"); - - event.valueInt1 = HapClientStackEvent.STATUS_GROUP_OPERATION_NOT_SUPPORTED; - eventStr = event.toString(); - assertThat(eventStr).contains("STATUS_GROUP_OPERATION_NOT_SUPPORTED"); - - event.valueInt1 = HapClientStackEvent.STATUS_PROCEDURE_ALREADY_IN_PROGRESS; - eventStr = event.toString(); - assertThat(eventStr).contains("STATUS_PROCEDURE_ALREADY_IN_PROGRESS"); - - event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO); - event.valueInt2 = -1; - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_ON_PRESET_INFO"); - assertThat(eventStr).contains("UNKNOWN"); - - event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_ALL_PRESET_INFO; - eventStr = event.toString(); - assertThat(eventStr).contains("PRESET_INFO_REASON_ALL_PRESET_INFO"); - - event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_PRESET_INFO_UPDATE; - eventStr = event.toString(); - assertThat(eventStr).contains("PRESET_INFO_REASON_PRESET_INFO_UPDATE"); - - event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_PRESET_DELETED; - eventStr = event.toString(); - assertThat(eventStr).contains("PRESET_INFO_REASON_PRESET_DELETED"); - - event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_PRESET_AVAILABILITY_CHANGED; - eventStr = event.toString(); - assertThat(eventStr).contains("PRESET_INFO_REASON_PRESET_AVAILABILITY_CHANGED"); - - event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_PRESET_INFO_REQUEST_RESPONSE; - eventStr = event.toString(); - assertThat(eventStr).contains("PRESET_INFO_REASON_PRESET_INFO_REQUEST_RESPONSE"); - - event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_PRESET_NAME_SET_ERROR); - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_ON_PRESET_NAME_SET_ERROR"); - - event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO_ERROR); - eventStr = event.toString(); - assertThat(eventStr).contains("EVENT_TYPE_ON_PRESET_INFO_ERROR"); - } + @Test + public void toString_containsProperSubStrings() { + HapClientStackEvent event; + String eventStr; + event = new HapClientStackEvent(0 /* EVENT_TYPE_NONE */); + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_NONE"); + + event = new HapClientStackEvent(10000); + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_UNKNOWN"); + + event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + event.valueInt1 = -1; + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_CONNECTION_STATE_CHANGED"); + assertThat(eventStr).contains("CONNECTION_STATE_UNKNOWN"); + + event.valueInt1 = HapClientStackEvent.CONNECTION_STATE_DISCONNECTED; + eventStr = event.toString(); + assertThat(eventStr).contains("CONNECTION_STATE_DISCONNECTED"); + + event.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTING; + eventStr = event.toString(); + assertThat(eventStr).contains("CONNECTION_STATE_CONNECTING"); + + event.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTED; + eventStr = event.toString(); + assertThat(eventStr).contains("CONNECTION_STATE_CONNECTED"); + + event.valueInt1 = HapClientStackEvent.CONNECTION_STATE_DISCONNECTING; + eventStr = event.toString(); + assertThat(eventStr).contains("CONNECTION_STATE_DISCONNECTING"); + + event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_DEVICE_AVAILABLE); + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_DEVICE_AVAILABLE"); + + event.valueInt1 = + 1 << HapClientStackEvent.FEATURE_BIT_NUM_TYPE_MONAURAL + | 1 << HapClientStackEvent.FEATURE_BIT_NUM_SYNCHRONIZATED_PRESETS; + eventStr = event.toString(); + assertThat(eventStr).contains("TYPE_MONAURAL"); + assertThat(eventStr).contains("SYNCHRONIZATED_PRESETS"); + + event.valueInt1 = + 1 << HapClientStackEvent.FEATURE_BIT_NUM_TYPE_BANDED + | 1 << HapClientStackEvent.FEATURE_BIT_NUM_INDEPENDENT_PRESETS; + eventStr = event.toString(); + assertThat(eventStr).contains("TYPE_BANDED"); + assertThat(eventStr).contains("INDEPENDENT_PRESETS"); + + event.valueInt1 = + 1 << HapClientStackEvent.FEATURE_BIT_NUM_DYNAMIC_PRESETS + | 1 << HapClientStackEvent.FEATURE_BIT_NUM_WRITABLE_PRESETS; + eventStr = event.toString(); + assertThat(eventStr).contains("TYPE_BINAURAL"); + assertThat(eventStr).contains("DYNAMIC_PRESETS"); + assertThat(eventStr).contains("WRITABLE_PRESETS"); + + event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_DEVICE_FEATURES); + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_DEVICE_FEATURES"); + + event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECTED); + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_ON_ACTIVE_PRESET_SELECTED"); + + event = + new HapClientStackEvent( + HapClientStackEvent.EVENT_TYPE_ON_ACTIVE_PRESET_SELECT_ERROR); + event.valueInt1 = -1; + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_ON_ACTIVE_PRESET_SELECT_ERROR"); + assertThat(eventStr).contains("ERROR_UNKNOWN"); + + event.valueInt1 = HapClientStackEvent.STATUS_NO_ERROR; + eventStr = event.toString(); + assertThat(eventStr).contains("STATUS_NO_ERROR"); + + event.valueInt1 = HapClientStackEvent.STATUS_SET_NAME_NOT_ALLOWED; + eventStr = event.toString(); + assertThat(eventStr).contains("STATUS_SET_NAME_NOT_ALLOWED"); + + event.valueInt1 = HapClientStackEvent.STATUS_OPERATION_NOT_SUPPORTED; + eventStr = event.toString(); + assertThat(eventStr).contains("STATUS_OPERATION_NOT_SUPPORTED"); + + event.valueInt1 = HapClientStackEvent.STATUS_OPERATION_NOT_POSSIBLE; + eventStr = event.toString(); + assertThat(eventStr).contains("STATUS_OPERATION_NOT_POSSIBLE"); + + event.valueInt1 = HapClientStackEvent.STATUS_INVALID_PRESET_NAME_LENGTH; + eventStr = event.toString(); + assertThat(eventStr).contains("STATUS_INVALID_PRESET_NAME_LENGTH"); + + event.valueInt1 = HapClientStackEvent.STATUS_INVALID_PRESET_INDEX; + eventStr = event.toString(); + assertThat(eventStr).contains("STATUS_INVALID_PRESET_INDEX"); + + event.valueInt1 = HapClientStackEvent.STATUS_GROUP_OPERATION_NOT_SUPPORTED; + eventStr = event.toString(); + assertThat(eventStr).contains("STATUS_GROUP_OPERATION_NOT_SUPPORTED"); + + event.valueInt1 = HapClientStackEvent.STATUS_PROCEDURE_ALREADY_IN_PROGRESS; + eventStr = event.toString(); + assertThat(eventStr).contains("STATUS_PROCEDURE_ALREADY_IN_PROGRESS"); + + event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO); + event.valueInt2 = -1; + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_ON_PRESET_INFO"); + assertThat(eventStr).contains("UNKNOWN"); + + event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_ALL_PRESET_INFO; + eventStr = event.toString(); + assertThat(eventStr).contains("PRESET_INFO_REASON_ALL_PRESET_INFO"); + + event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_PRESET_INFO_UPDATE; + eventStr = event.toString(); + assertThat(eventStr).contains("PRESET_INFO_REASON_PRESET_INFO_UPDATE"); + + event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_PRESET_DELETED; + eventStr = event.toString(); + assertThat(eventStr).contains("PRESET_INFO_REASON_PRESET_DELETED"); + + event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_PRESET_AVAILABILITY_CHANGED; + eventStr = event.toString(); + assertThat(eventStr).contains("PRESET_INFO_REASON_PRESET_AVAILABILITY_CHANGED"); + + event.valueInt2 = HapClientStackEvent.PRESET_INFO_REASON_PRESET_INFO_REQUEST_RESPONSE; + eventStr = event.toString(); + assertThat(eventStr).contains("PRESET_INFO_REASON_PRESET_INFO_REQUEST_RESPONSE"); + + event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_PRESET_NAME_SET_ERROR); + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_ON_PRESET_NAME_SET_ERROR"); + + event = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_ON_PRESET_INFO_ERROR); + eventStr = event.toString(); + assertThat(eventStr).contains("EVENT_TYPE_ON_PRESET_INFO_ERROR"); + } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientStateMachineTest.java index 4c878d896fa..808acc5bd4a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientStateMachineTest.java @@ -63,12 +63,9 @@ public class HapClientStateMachineTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private AdapterService mAdapterService; - @Mock - private HapClientService mHapClientService; - @Mock - private HapClientNativeInterface mHearingAccessGattClientInterface; + @Mock private AdapterService mAdapterService; + @Mock private HapClientService mHapClientService; + @Mock private HapClientNativeInterface mHearingAccessGattClientInterface; @Before public void setUp() throws Exception { @@ -83,10 +80,14 @@ public class HapClientStateMachineTest { // Set up thread and looper mHandlerThread = new HandlerThread("HapClientStateMachineTestHandlerThread"); mHandlerThread.start(); - mHapClientStateMachine = new HapClientStateMachine(mTestDevice, - mHapClientService, mHearingAccessGattClientInterface, mHandlerThread.getLooper()); + mHapClientStateMachine = + new HapClientStateMachine( + mTestDevice, + mHapClientService, + mHearingAccessGattClientInterface, + mHandlerThread.getLooper()); // Override the timeout value to speed up the test - HapClientStateMachine.sConnectTimeoutMs = 1000; // 1s + HapClientStateMachine.sConnectTimeoutMs = 1000; // 1s mHapClientStateMachine.start(); } @@ -102,13 +103,11 @@ public class HapClientStateMachineTest { TestUtils.clearAdapterService(mAdapterService); } - /** - * Test that default state is disconnected - */ + /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, - mHapClientStateMachine.getConnectionState()); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mHapClientStateMachine.getConnectionState()); } /** @@ -120,53 +119,50 @@ public class HapClientStateMachineTest { doReturn(allow).when(mHapClientService).okToConnect(any(BluetoothDevice.class)); } - /** - * Test that an incoming connection with policy forbidding connection is rejected - */ + /** Test that an incoming connection with policy forbidding connection is rejected */ @Test public void testIncomingPolicyReject() { allowConnection(false); // Inject an event for when incoming connection is requested HapClientStackEvent connStCh = - new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTED; mHapClientStateMachine.sendMessage(HapClientStateMachine.STACK_EVENT, connStCh); // Verify that no connection state broadcast is executed - verify(mHapClientService, after(TIMEOUT_MS).never()).sendBroadcast(any(Intent.class), - anyString()); + verify(mHapClientService, after(TIMEOUT_MS).never()) + .sendBroadcast(any(Intent.class), anyString()); // Check that we are in Disconnected state - Assert.assertThat(mHapClientStateMachine.getCurrentState(), + Assert.assertThat( + mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HapClientStateMachine.Disconnected.class)); } - /** - * Test that an incoming connection with policy allowing connection is accepted - */ + /** Test that an incoming connection with policy allowing connection is accepted */ @Test public void testIncomingPolicyAccept() { allowConnection(true); // Inject an event for when incoming connection is requested HapClientStackEvent connStCh = - new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTING; mHapClientStateMachine.sendMessage(HapClientStateMachine.STACK_EVENT, connStCh); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mHapClientService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - intentArgument1.capture(), anyString()); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify(mHapClientService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString()); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mHapClientStateMachine.getCurrentState(), + Assert.assertThat( + mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HapClientStateMachine.Connecting.class)); // Send a message to trigger connection completed @@ -174,98 +170,103 @@ public class HapClientStateMachineTest { new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = mTestDevice; connCompletedEvent.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTED; - mHapClientStateMachine.sendMessage(HapClientStateMachine.STACK_EVENT, - connCompletedEvent); + mHapClientStateMachine.sendMessage(HapClientStateMachine.STACK_EVENT, connCompletedEvent); // Verify that the expected number of broadcasts are executed: // - two calls to broadcastConnectionState(): Disconnected -> Connecting -> Connected ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mHapClientService, timeout(TIMEOUT_MS).times(2)).sendBroadcast( - intentArgument2.capture(), anyString()); + verify(mHapClientService, timeout(TIMEOUT_MS).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString()); // Check that we are in Connected state - Assert.assertThat(mHapClientStateMachine.getCurrentState(), + Assert.assertThat( + mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HapClientStateMachine.Connected.class)); } - /** - * Test that an outgoing connection times out - */ + /** Test that an outgoing connection times out */ @Test public void testOutgoingTimeout() { allowConnection(true); - doReturn(true).when(mHearingAccessGattClientInterface).connectHapClient(any( - BluetoothDevice.class)); - doReturn(true).when(mHearingAccessGattClientInterface).disconnectHapClient(any( - BluetoothDevice.class)); + doReturn(true) + .when(mHearingAccessGattClientInterface) + .connectHapClient(any(BluetoothDevice.class)); + doReturn(true) + .when(mHearingAccessGattClientInterface) + .disconnectHapClient(any(BluetoothDevice.class)); // Send a connect request mHapClientStateMachine.sendMessage(HapClientStateMachine.CONNECT, mTestDevice); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mHapClientService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - intentArgument1.capture(), - anyString()); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify(mHapClientService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString()); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mHapClientStateMachine.getCurrentState(), + Assert.assertThat( + mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HapClientStateMachine.Connecting.class)); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mHapClientService, timeout(HapClientStateMachine.sConnectTimeoutMs * 2).times( - 2)).sendBroadcast(intentArgument2.capture(), anyString()); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + verify(mHapClientService, timeout(HapClientStateMachine.sConnectTimeoutMs * 2).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString()); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Disconnected state - Assert.assertThat(mHapClientStateMachine.getCurrentState(), + Assert.assertThat( + mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HapClientStateMachine.Disconnected.class)); verify(mHearingAccessGattClientInterface).disconnectHapClient(eq(mTestDevice)); } - /** - * Test that an incoming connection times out - */ + /** Test that an incoming connection times out */ @Test public void testIncomingTimeout() { allowConnection(true); - doReturn(true).when(mHearingAccessGattClientInterface).connectHapClient(any( - BluetoothDevice.class)); - doReturn(true).when(mHearingAccessGattClientInterface).disconnectHapClient(any( - BluetoothDevice.class)); + doReturn(true) + .when(mHearingAccessGattClientInterface) + .connectHapClient(any(BluetoothDevice.class)); + doReturn(true) + .when(mHearingAccessGattClientInterface) + .disconnectHapClient(any(BluetoothDevice.class)); // Inject an event for when incoming connection is requested HapClientStackEvent connStCh = - new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTING; mHapClientStateMachine.sendMessage(HapClientStateMachine.STACK_EVENT, connStCh); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mHapClientService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - intentArgument1.capture(), - anyString()); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify(mHapClientService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString()); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mHapClientStateMachine.getCurrentState(), + Assert.assertThat( + mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HapClientStateMachine.Connecting.class)); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mHapClientService, timeout(HapClientStateMachine.sConnectTimeoutMs * 2).times( - 2)).sendBroadcast(intentArgument2.capture(), anyString()); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + verify(mHapClientService, timeout(HapClientStateMachine.sConnectTimeoutMs * 2).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString()); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Disconnected state - Assert.assertThat(mHapClientStateMachine.getCurrentState(), + Assert.assertThat( + mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HapClientStateMachine.Disconnected.class)); verify(mHearingAccessGattClientInterface).disconnectHapClient(eq(mTestDevice)); } @@ -273,11 +274,13 @@ public class HapClientStateMachineTest { @Test public void testStatesChangesWithMessages() { allowConnection(true); - doReturn(true).when(mHearingAccessGattClientInterface).connectHapClient(any( - BluetoothDevice.class)); + doReturn(true) + .when(mHearingAccessGattClientInterface) + .connectHapClient(any(BluetoothDevice.class)); // Check that we are in Disconnected state - Assert.assertThat(mHapClientStateMachine.getCurrentState(), + Assert.assertThat( + mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HapClientStateMachine.Disconnected.class)); mHapClientStateMachine.sendMessage(HapClientStateMachine.DISCONNECT); @@ -308,32 +311,29 @@ public class HapClientStateMachineTest { mHapClientStateMachine.obtainMessage(HapClientStateMachine.CONNECT), HapClientStateMachine.Connecting.class); // connecting -> disconnecting - HapClientStackEvent connStCh = new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + HapClientStackEvent connStCh = + new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_DISCONNECTING; sendMessageAndVerifyTransition( mHapClientStateMachine.obtainMessage(HapClientStateMachine.STACK_EVENT, connStCh), HapClientStateMachine.Disconnecting.class); // disconnecting -> connecting - connStCh = new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connStCh = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTING; sendMessageAndVerifyTransition( mHapClientStateMachine.obtainMessage(HapClientStateMachine.STACK_EVENT, connStCh), HapClientStateMachine.Connecting.class); // connecting -> connected - connStCh = new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connStCh = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTED; sendMessageAndVerifyTransition( mHapClientStateMachine.obtainMessage(HapClientStateMachine.STACK_EVENT, connStCh), HapClientStateMachine.Connected.class); // connected -> disconnecting - connStCh = new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connStCh = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_DISCONNECTING; sendMessageAndVerifyTransition( @@ -345,8 +345,7 @@ public class HapClientStateMachineTest { HapClientStateMachine.Disconnected.class); // disconnected -> connected - connStCh = new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connStCh = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTED; sendMessageAndVerifyTransition( @@ -358,16 +357,14 @@ public class HapClientStateMachineTest { HapClientStateMachine.Disconnected.class); // disconnected -> connected - connStCh = new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connStCh = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_CONNECTED; sendMessageAndVerifyTransition( mHapClientStateMachine.obtainMessage(HapClientStateMachine.STACK_EVENT, connStCh), HapClientStateMachine.Connected.class); // connected -> disconnected - connStCh = new HapClientStackEvent( - HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connStCh = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = HapClientStackEvent.CONNECTION_STATE_DISCONNECTED; sendMessageAndVerifyTransition( @@ -379,8 +376,8 @@ public class HapClientStateMachineTest { Mockito.clearInvocations(mHapClientService); mHapClientStateMachine.sendMessage(msg); // Verify that one connection state broadcast is executed - verify(mHapClientService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - any(Intent.class), anyString()); + verify(mHapClientService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(any(Intent.class), anyString()); Assert.assertThat(mHapClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(type)); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java index 9188a640fee..4b8f108a06e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java @@ -117,7 +117,6 @@ public class HapClientTest { System.setProperty("dexmaker.share_classloader", "true"); } - HapClientStateMachine.sConnectTimeoutMs = TIMEOUT_MS; doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); @@ -141,19 +140,25 @@ public class HapClientTest { mDevice3 = TestUtils.getTestDevice(mAdapter, 2); when(mNativeInterface.getDevice(getByteAddress(mDevice3))).thenReturn(mDevice3); - doCallRealMethod().when(mNativeInterface) + doCallRealMethod() + .when(mNativeInterface) .sendMessageToService(any(HapClientStackEvent.class)); doCallRealMethod().when(mNativeInterface).onFeaturesUpdate(any(byte[].class), anyInt()); doCallRealMethod().when(mNativeInterface).onDeviceAvailable(any(byte[].class), anyInt()); - doCallRealMethod().when(mNativeInterface) + doCallRealMethod() + .when(mNativeInterface) .onActivePresetSelected(any(byte[].class), anyInt()); - doCallRealMethod().when(mNativeInterface) + doCallRealMethod() + .when(mNativeInterface) .onActivePresetSelectError(any(byte[].class), anyInt()); - doCallRealMethod().when(mNativeInterface) + doCallRealMethod() + .when(mNativeInterface) .onPresetNameSetError(any(byte[].class), anyInt(), anyInt()); - doCallRealMethod().when(mNativeInterface) + doCallRealMethod() + .when(mNativeInterface) .onPresetInfo(any(byte[].class), anyInt(), any(BluetoothHapPresetInfo[].class)); - doCallRealMethod().when(mNativeInterface) + doCallRealMethod() + .when(mNativeInterface) .onGroupPresetNameSetError(anyInt(), anyInt(), anyInt()); /* Prepare CAS groups */ @@ -165,11 +170,11 @@ public class HapClientTest { int groupId3 = 0x03; Map groups3 = new HashMap(); - groups3.put(groupId3, - ParcelUuid.fromString("00001853-0000-1000-8000-00805F9B34FB")); + groups3.put(groupId3, ParcelUuid.fromString("00001853-0000-1000-8000-00805F9B34FB")); - doReturn(Arrays.asList(mDevice, mDevice2)).when(mCsipService) - .getGroupDevicesOrdered(groupId2); + doReturn(Arrays.asList(mDevice, mDevice2)) + .when(mCsipService) + .getGroupDevicesOrdered(groupId2); doReturn(groups2).when(mCsipService).getGroupUuidMapByDevice(mDevice); doReturn(groups2).when(mCsipService).getGroupUuidMapByDevice(mDevice2); @@ -178,9 +183,11 @@ public class HapClientTest { doReturn(Arrays.asList(mDevice)).when(mCsipService).getGroupDevicesOrdered(0x01); - doReturn(BluetoothDevice.BOND_BONDED).when(mAdapterService) + doReturn(BluetoothDevice.BOND_BONDED) + .when(mAdapterService) .getBondState(any(BluetoothDevice.class)); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); } @@ -214,17 +221,13 @@ public class HapClientTest { Assert.assertNull(mService); } - /** - * Test getting HA Service Client - */ + /** Test getting HA Service Client */ @Test public void testGetHapService() { Assert.assertEquals(mService, HapClientService.getHapClientService()); } - /** - * Test stop HA Service Client - */ + /** Test stop HA Service Client */ @Test public void testStopHapService() { Assert.assertEquals(mService, HapClientService.getHapClientService()); @@ -236,117 +239,133 @@ public class HapClientTest { /** Test get/set policy for BluetoothDevice */ @Test public void testGetSetPolicy() throws Exception { - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - Assert.assertEquals("Initial device policy", + Assert.assertEquals( + "Initial device policy", BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mService.getConnectionPolicy(mDevice)); - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - Assert.assertEquals("Setting device policy to POLICY_FORBIDDEN", + Assert.assertEquals( + "Setting device policy to POLICY_FORBIDDEN", BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, mService.getConnectionPolicy(mDevice)); - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); // call getConnectionPolicy via binder int policy = mServiceBinder.getConnectionPolicy(mDevice, mAttributionSource); - Assert.assertEquals("Setting device policy to POLICY_ALLOWED", - BluetoothProfile.CONNECTION_POLICY_ALLOWED, policy); + Assert.assertEquals( + "Setting device policy to POLICY_ALLOWED", + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + policy); } - /** - * Test if getProfileConnectionPolicy works after the service is stopped. - */ + /** Test if getProfileConnectionPolicy works after the service is stopped. */ @Test public void testGetPolicyAfterStopped() { mService.stop(); - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - Assert.assertEquals("Initial device policy", + Assert.assertEquals( + "Initial device policy", BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mService.getConnectionPolicy(mDevice)); } - /** - * Test okToConnect method using various test cases - */ + /** Test okToConnect method using various test cases */ @Test public void testOkToConnect() { int badPolicyValue = 1024; int badBondState = 42; - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_NONE, badPolicyValue, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_BONDING, badPolicyValue, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_ALLOWED, true); - testOkToConnectCase(mDevice, - BluetoothDevice.BOND_BONDED, badPolicyValue, false); - testOkToConnectCase(mDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mDevice, - badBondState, badPolicyValue, false); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); + testOkToConnectCase(mDevice, BluetoothDevice.BOND_NONE, badPolicyValue, false); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); + testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDING, badPolicyValue, false); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + true); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + true); + testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDED, badPolicyValue, false); + testOkToConnectCase( + mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); + testOkToConnectCase( + mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); + testOkToConnectCase( + mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); + testOkToConnectCase(mDevice, badBondState, badPolicyValue, false); } - /** - * Test that an outgoing connection to device that does not have HAS UUID is rejected - */ + /** Test that an outgoing connection to device that does not have HAS UUID is rejected */ @Test public void testOutgoingConnectMissingHasUuid() { // Update the device policy so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mNativeInterface).connectHapClient(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectHapClient(any(BluetoothDevice.class)); // Return No UUID - doReturn(new ParcelUuid[]{}).when(mAdapterService) + doReturn(new ParcelUuid[] {}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Send a connect request Assert.assertFalse("Connect expected to fail", mService.connect(mDevice)); } - /** - * Test that an outgoing connection to device that have HAS UUID is successful - */ + /** Test that an outgoing connection to device that have HAS UUID is successful */ @Test public void testOutgoingConnectExistingHasUuid() { // Update the device policy so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mNativeInterface).connectHapClient(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectHapClient(any(BluetoothDevice.class)); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Send a connect request @@ -355,33 +374,27 @@ public class HapClientTest { verify(mAdapterService, timeout(TIMEOUT_MS)).sendBroadcast(any(), any()); } - /** - * Test that an outgoing connection to device with POLICY_FORBIDDEN is rejected - */ + /** Test that an outgoing connection to device with POLICY_FORBIDDEN is rejected */ @Test public void testOutgoingConnectPolicyForbidden() { doReturn(true).when(mNativeInterface).connectHapClient(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectHapClient(any(BluetoothDevice.class)); // Set the device policy to POLICY_FORBIDDEN so connect() should fail - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Send a connect request Assert.assertFalse("Connect expected to fail", mService.connect(mDevice)); } - /** - * Test that an outgoing connection times out - */ + /** Test that an outgoing connection times out */ @Test public void testOutgoingConnectTimeout() throws Exception { InOrder order = inOrder(mAdapterService); // Update the device policy so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mNativeInterface).connectHapClient(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectHapClient(any(BluetoothDevice.class)); @@ -399,8 +412,8 @@ public class HapClientTest { hasExtra(EXTRA_PREVIOUS_STATE, STATE_DISCONNECTED))), any()); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, - mService.getConnectionState(mDevice)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(mDevice)); // Verify the connection state broadcast, and that we are in Disconnected state via binder order.verify(mAdapterService, timeout(HapClientStateMachine.sConnectTimeoutMs * 2)) @@ -417,13 +430,12 @@ public class HapClientTest { Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, state); } - /** - * Test that an outgoing connection to two device that have HAS UUID is successful - */ + /** Test that an outgoing connection to two device that have HAS UUID is successful */ @Test public void testConnectTwo() throws Exception { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Send a connect request for the 1st device @@ -445,17 +457,17 @@ public class HapClientTest { */ @Test public void testCallsForNotConnectedDevice() { - Assert.assertEquals(BluetoothHapClient.PRESET_INDEX_UNAVAILABLE, + Assert.assertEquals( + BluetoothHapClient.PRESET_INDEX_UNAVAILABLE, mService.getActivePresetIndex(mDevice)); } - /** - * Test getting HAS coordinated sets. - */ + /** Test getting HAS coordinated sets. */ @Test public void testGetHapGroupCoordinatedOps() throws Exception { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice); testConnectingDevice(order, mDevice2); @@ -483,39 +495,36 @@ public class HapClientTest { Assert.assertEquals(2, hapGroup); } - /** - * Test that selectPreset properly calls the native method. - */ + /** Test that selectPreset properly calls the native method. */ @Test public void testSelectPresetNative() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice); // Verify Native Interface call mService.selectPreset(mDevice, 0x00); - verify(mNativeInterface, times(0)) - .selectActivePreset(eq(mDevice), eq(0x00)); + verify(mNativeInterface, times(0)).selectActivePreset(eq(mDevice), eq(0x00)); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onPresetSelectionFailed(eq(mDevice), - eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onPresetSelectionFailed( + eq(mDevice), eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } mServiceBinder.selectPreset(mDevice, 0x01, mAttributionSource); - verify(mNativeInterface, times(1)) - .selectActivePreset(eq(mDevice), eq(0x01)); + verify(mNativeInterface, times(1)).selectActivePreset(eq(mDevice), eq(0x01)); } - /** - * Test that groupSelectActivePreset properly calls the native method. - */ + /** Test that groupSelectActivePreset properly calls the native method. */ @Test public void testGroupSelectActivePresetNative() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice3); @@ -525,40 +534,37 @@ public class HapClientTest { // Verify Native Interface call mService.selectPresetForGroup(0x03, 0x00); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onPresetSelectionForGroupFailed( - eq(0x03), eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onPresetSelectionForGroupFailed( + eq(0x03), eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } mServiceBinder.selectPresetForGroup(0x03, 0x01, mAttributionSource); - verify(mNativeInterface, times(1)) - .groupSelectActivePreset(eq(0x03), eq(0x01)); + verify(mNativeInterface, times(1)).groupSelectActivePreset(eq(0x03), eq(0x01)); } - /** - * Test that nextActivePreset properly calls the native method. - */ + /** Test that nextActivePreset properly calls the native method. */ @Test public void testSwitchToNextPreset() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice); // Verify Native Interface call mServiceBinder.switchToNextPreset(mDevice, mAttributionSource); - verify(mNativeInterface, times(1)) - .nextActivePreset(eq(mDevice)); + verify(mNativeInterface, times(1)).nextActivePreset(eq(mDevice)); } - /** - * Test that groupNextActivePreset properly calls the native method. - */ + /** Test that groupNextActivePreset properly calls the native method. */ @Test public void testSwitchToNextPresetForGroup() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice3); int flags = 0x01; @@ -569,29 +575,26 @@ public class HapClientTest { verify(mNativeInterface, times(1)).groupNextActivePreset(eq(0x03)); } - /** - * Test that previousActivePreset properly calls the native method. - */ + /** Test that previousActivePreset properly calls the native method. */ @Test public void testSwitchToPreviousPreset() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice); // Verify Native Interface call mServiceBinder.switchToPreviousPreset(mDevice, mAttributionSource); - verify(mNativeInterface, times(1)) - .previousActivePreset(eq(mDevice)); + verify(mNativeInterface, times(1)).previousActivePreset(eq(mDevice)); } - /** - * Test that groupPreviousActivePreset properly calls the native method. - */ + /** Test that groupPreviousActivePreset properly calls the native method. */ @Test public void testSwitchToPreviousPresetForGroup() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice); testConnectingDevice(order, mDevice2); @@ -604,13 +607,12 @@ public class HapClientTest { verify(mNativeInterface, times(1)).groupPreviousActivePreset(eq(0x02)); } - /** - * Test that getActivePresetIndex returns cached value. - */ + /** Test that getActivePresetIndex returns cached value. */ @Test public void testGetActivePresetIndex() throws Exception { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice); testOnPresetSelected(mDevice, 0x01); @@ -620,13 +622,12 @@ public class HapClientTest { Assert.assertEquals(0x01, presetIndex); } - /** - * Test that getActivePresetInfo returns cached value for valid parameters. - */ + /** Test that getActivePresetInfo returns cached value for valid parameters. */ @Test public void testGetPresetInfoAndActivePresetInfo() throws Exception { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice2); @@ -639,7 +640,8 @@ public class HapClientTest { Assert.assertTrue(presetList.contains(presetInfo)); Assert.assertEquals(0x01, presetInfo.getIndex()); - Assert.assertEquals(BluetoothHapClient.PRESET_INDEX_UNAVAILABLE, + Assert.assertEquals( + BluetoothHapClient.PRESET_INDEX_UNAVAILABLE, mService.getActivePresetIndex(mDevice2)); Assert.assertEquals(null, mService.getActivePresetInfo(mDevice2)); @@ -654,13 +656,12 @@ public class HapClientTest { Assert.assertEquals("One", info.getName()); } - /** - * Test that setPresetName properly calls the native method for the valid parameters. - */ + /** Test that setPresetName properly calls the native method for the valid parameters. */ @Test public void testSetPresetNameNative() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); testConnectingDevice(order, mDevice); @@ -668,8 +669,9 @@ public class HapClientTest { verify(mNativeInterface, times(0)) .setPresetName(eq(mDevice), eq(0x00), eq("ExamplePresetName")); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameFailed(eq(mDevice), - eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameFailed( + eq(mDevice), eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } @@ -686,7 +688,8 @@ public class HapClientTest { @Test public void testSetPresetNameForGroup() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); int test_group = 0x02; for (BluetoothDevice device : mCsipService.getGroupDevicesOrdered(test_group)) { @@ -699,16 +702,19 @@ public class HapClientTest { mServiceBinder.setPresetNameForGroup( test_group, 0x00, "ExamplePresetName", mAttributionSource); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameForGroupFailed(eq(test_group), - eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameForGroupFailed( + eq(test_group), + eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } mService.setPresetNameForGroup(-1, 0x01, "ExamplePresetName"); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameForGroupFailed(eq(-1), - eq(BluetoothStatusCodes.ERROR_CSIP_INVALID_GROUP_ID)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameForGroupFailed( + eq(-1), eq(BluetoothStatusCodes.ERROR_CSIP_INVALID_GROUP_ID)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } @@ -719,17 +725,14 @@ public class HapClientTest { .groupSetPresetName(eq(test_group), eq(0x01), eq("ExamplePresetName")); } - /** - * Test that native callback generates proper intent. - */ + /** Test that native callback generates proper intent. */ @Test public void testStackEventDeviceAvailable() { - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - doCallRealMethod() - .when(mNativeInterface) - .onDeviceAvailable(any(byte[].class), anyInt()); + doCallRealMethod().when(mNativeInterface).onDeviceAvailable(any(byte[].class), anyInt()); mNativeInterface.onDeviceAvailable(getByteAddress(mDevice), 0x03); verify(mAdapterService, timeout(TIMEOUT_MS)) @@ -742,12 +745,11 @@ public class HapClientTest { any()); } - /** - * Test that native callback generates proper callback call. - */ + /** Test that native callback generates proper callback call. */ @Test public void testStackEventOnPresetSelected() { - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); doCallRealMethod() @@ -756,8 +758,11 @@ public class HapClientTest { mNativeInterface.onActivePresetSelected(getByteAddress(mDevice), 0x01); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onPresetSelected(eq(mDevice), - eq(0x01), eq(BluetoothStatusCodes.REASON_LOCAL_STACK_REQUEST)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onPresetSelected( + eq(mDevice), + eq(0x01), + eq(BluetoothStatusCodes.REASON_LOCAL_STACK_REQUEST)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } @@ -766,15 +771,13 @@ public class HapClientTest { Assert.assertEquals(0x01, mService.getActivePresetIndex(mDevice)); } - /** - * Test that native callback generates proper callback call. - */ + /** Test that native callback generates proper callback call. */ @Test public void testStackEventOnActivePresetSelectError() { - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - doCallRealMethod() .when(mNativeInterface) .onActivePresetSelectError(any(byte[].class), anyInt()); @@ -782,126 +785,132 @@ public class HapClientTest { mNativeInterface.onActivePresetSelectError(getByteAddress(mDevice), 0x05); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onPresetSelectionFailed(eq(mDevice), - eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onPresetSelectionFailed( + eq(mDevice), eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } } - /** - * Test that native callback generates proper callback call. - */ + /** Test that native callback generates proper callback call. */ @Test public void testStackEventOnPresetInfo() { InOrder order = inOrder(mAdapterService); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Connect and inject initial presets testConnectingDevice(order, mDevice); int info_reason = HapClientStackEvent.PRESET_INFO_REASON_PRESET_INFO_UPDATE; - BluetoothHapPresetInfo[] info = - {new BluetoothHapPresetInfo.Builder(0x01, "OneChangedToUnavailable") - .setWritable(true) - .setAvailable(false) - .build()}; - - doCallRealMethod() - .when(mNativeInterface) - .onPresetInfo(any(byte[].class), anyInt(), any()); + BluetoothHapPresetInfo[] info = { + new BluetoothHapPresetInfo.Builder(0x01, "OneChangedToUnavailable") + .setWritable(true) + .setAvailable(false) + .build() + }; + + doCallRealMethod().when(mNativeInterface).onPresetInfo(any(byte[].class), anyInt(), any()); mNativeInterface.onPresetInfo(getByteAddress(mDevice), info_reason, info); ArgumentCaptor> presetsCaptor = ArgumentCaptor.forClass(List.class); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onPresetInfoChanged(eq(mDevice), - presetsCaptor.capture(), eq(BluetoothStatusCodes.REASON_REMOTE_REQUEST)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onPresetInfoChanged( + eq(mDevice), + presetsCaptor.capture(), + eq(BluetoothStatusCodes.REASON_REMOTE_REQUEST)); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } List presets = presetsCaptor.getValue(); Assert.assertEquals(3, presets.size()); - Optional preset = presetsCaptor.getValue() - .stream() - .filter(p -> 0x01 == p.getIndex()) - .findFirst(); + Optional preset = + presetsCaptor.getValue().stream().filter(p -> 0x01 == p.getIndex()).findFirst(); Assert.assertEquals("OneChangedToUnavailable", preset.get().getName()); Assert.assertFalse(preset.get().isAvailable()); Assert.assertTrue(preset.get().isWritable()); } - /** - * Test that native callback generates proper callback call. - */ + /** Test that native callback generates proper callback call. */ @Test public void testStackEventOnPresetNameSetError() { - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); doCallRealMethod() .when(mNativeInterface) .onPresetNameSetError(any(byte[].class), anyInt(), anyInt()); /* Not a valid name length */ - mNativeInterface.onPresetNameSetError(getByteAddress(mDevice), 0x01, + mNativeInterface.onPresetNameSetError( + getByteAddress(mDevice), + 0x01, HapClientStackEvent.STATUS_INVALID_PRESET_NAME_LENGTH); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameFailed(eq(mDevice), - eq(BluetoothStatusCodes.ERROR_HAP_PRESET_NAME_TOO_LONG)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameFailed( + eq(mDevice), eq(BluetoothStatusCodes.ERROR_HAP_PRESET_NAME_TOO_LONG)); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } /* Invalid preset index provided */ - mNativeInterface.onPresetNameSetError(getByteAddress(mDevice), 0x01, - HapClientStackEvent.STATUS_INVALID_PRESET_INDEX); + mNativeInterface.onPresetNameSetError( + getByteAddress(mDevice), 0x01, HapClientStackEvent.STATUS_INVALID_PRESET_INDEX); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameFailed(eq(mDevice), - eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameFailed( + eq(mDevice), eq(BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX)); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } /* Not allowed on this particular preset */ - mNativeInterface.onPresetNameSetError(getByteAddress(mDevice), 0x01, - HapClientStackEvent.STATUS_SET_NAME_NOT_ALLOWED); + mNativeInterface.onPresetNameSetError( + getByteAddress(mDevice), 0x01, HapClientStackEvent.STATUS_SET_NAME_NOT_ALLOWED); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameFailed(eq(mDevice), - eq(BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameFailed( + eq(mDevice), eq(BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED)); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } /* Not allowed on this particular preset at this time, might be possible later on */ - mNativeInterface.onPresetNameSetError(getByteAddress(mDevice), 0x01, - HapClientStackEvent.STATUS_OPERATION_NOT_POSSIBLE); + mNativeInterface.onPresetNameSetError( + getByteAddress(mDevice), 0x01, HapClientStackEvent.STATUS_OPERATION_NOT_POSSIBLE); try { - verify(mCallback, after(TIMEOUT_MS).times(2)).onSetPresetNameFailed(eq(mDevice), - eq(BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED)); + verify(mCallback, after(TIMEOUT_MS).times(2)) + .onSetPresetNameFailed( + eq(mDevice), eq(BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED)); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } /* Not allowed on all presets - for example missing characteristic */ - mNativeInterface.onPresetNameSetError(getByteAddress(mDevice), 0x01, - HapClientStackEvent.STATUS_OPERATION_NOT_SUPPORTED); + mNativeInterface.onPresetNameSetError( + getByteAddress(mDevice), 0x01, HapClientStackEvent.STATUS_OPERATION_NOT_SUPPORTED); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameFailed(eq(mDevice), - eq(BluetoothStatusCodes.ERROR_REMOTE_OPERATION_NOT_SUPPORTED)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameFailed( + eq(mDevice), + eq(BluetoothStatusCodes.ERROR_REMOTE_OPERATION_NOT_SUPPORTED)); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } } - /** - * Test that native callback generates proper callback call. - */ + /** Test that native callback generates proper callback call. */ @Test public void testStackEventOnGroupPresetNameSetError() { - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); doCallRealMethod() @@ -909,53 +918,58 @@ public class HapClientTest { .onGroupPresetNameSetError(anyInt(), anyInt(), anyInt()); /* Not a valid name length */ - mNativeInterface.onGroupPresetNameSetError(0x01, 0x01, - HapClientStackEvent.STATUS_INVALID_PRESET_NAME_LENGTH); + mNativeInterface.onGroupPresetNameSetError( + 0x01, 0x01, HapClientStackEvent.STATUS_INVALID_PRESET_NAME_LENGTH); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameForGroupFailed(0x01, - BluetoothStatusCodes.ERROR_HAP_PRESET_NAME_TOO_LONG); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameForGroupFailed( + 0x01, BluetoothStatusCodes.ERROR_HAP_PRESET_NAME_TOO_LONG); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } /* Invalid preset index provided */ - mNativeInterface.onGroupPresetNameSetError(0x01, 0x01, - HapClientStackEvent.STATUS_INVALID_PRESET_INDEX); + mNativeInterface.onGroupPresetNameSetError( + 0x01, 0x01, HapClientStackEvent.STATUS_INVALID_PRESET_INDEX); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameForGroupFailed(0x01, - BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameForGroupFailed( + 0x01, BluetoothStatusCodes.ERROR_HAP_INVALID_PRESET_INDEX); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } /* Not allowed on this particular preset */ - mNativeInterface.onGroupPresetNameSetError(0x01, 0x01, - HapClientStackEvent.STATUS_SET_NAME_NOT_ALLOWED); + mNativeInterface.onGroupPresetNameSetError( + 0x01, 0x01, HapClientStackEvent.STATUS_SET_NAME_NOT_ALLOWED); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameForGroupFailed(0x01, - BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameForGroupFailed( + 0x01, BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } /* Not allowed on this particular preset at this time, might be possible later on */ - mNativeInterface.onGroupPresetNameSetError(0x01, 0x01, - HapClientStackEvent.STATUS_OPERATION_NOT_POSSIBLE); + mNativeInterface.onGroupPresetNameSetError( + 0x01, 0x01, HapClientStackEvent.STATUS_OPERATION_NOT_POSSIBLE); try { - verify(mCallback, after(TIMEOUT_MS).times(2)).onSetPresetNameForGroupFailed(0x01, - BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED); + verify(mCallback, after(TIMEOUT_MS).times(2)) + .onSetPresetNameForGroupFailed( + 0x01, BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } /* Not allowed on all presets - for example if peer is missing optional CP characteristic */ - mNativeInterface.onGroupPresetNameSetError(0x01, 0x01, - HapClientStackEvent.STATUS_OPERATION_NOT_SUPPORTED); + mNativeInterface.onGroupPresetNameSetError( + 0x01, 0x01, HapClientStackEvent.STATUS_OPERATION_NOT_SUPPORTED); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onSetPresetNameForGroupFailed(0x01, - BluetoothStatusCodes.ERROR_REMOTE_OPERATION_NOT_SUPPORTED); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onSetPresetNameForGroupFailed( + 0x01, BluetoothStatusCodes.ERROR_REMOTE_OPERATION_NOT_SUPPORTED); } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + throw e.rethrowFromSystemServer(); } } @@ -971,8 +985,11 @@ public class HapClientTest { Assert.assertTrue( mServiceBinder.setConnectionPolicy( mDevice, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mAttributionSource)); - verify(mDatabaseManager).setProfileConnectionPolicy( - mDevice, BluetoothProfile.HAP_CLIENT, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + verify(mDatabaseManager) + .setProfileConnectionPolicy( + mDevice, + BluetoothProfile.HAP_CLIENT, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN); } @Test @@ -993,19 +1010,18 @@ public class HapClientTest { mServiceBinder.unregisterCallback(callback, mAttributionSource); Assert.assertEquals(size, mService.mCallbacks.getRegisteredCallbackCount()); - } @Test public void testDumpDoesNotCrash() { // Update the device policy so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mNativeInterface).connectHapClient(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectHapClient(any(BluetoothDevice.class)); - doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.HAS}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Add state machine for testing dump() @@ -1016,14 +1032,11 @@ public class HapClientTest { mService.dump(new StringBuilder()); } - /** - * Helper function to test device connecting - */ + /** Helper function to test device connecting */ private void prepareConnectingDevice(BluetoothDevice device) { // Prepare intent queue and all the mocks when(mNativeInterface.getDevice(getByteAddress(device))).thenReturn(device); - when(mDatabaseManager - .getProfileConnectionPolicy(device, BluetoothProfile.HAP_CLIENT)) + when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.HAP_CLIENT)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mNativeInterface).connectHapClient(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectHapClient(any(BluetoothDevice.class)); @@ -1072,7 +1085,7 @@ public class HapClientTest { evt = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_DEVICE_AVAILABLE); evt.device = device; - evt.valueInt1 = 0x01; // features + evt.valueInt1 = 0x01; // features mService.messageFromNative(evt); order.verify(mAdapterService, timeout(TIMEOUT_MS)) @@ -1091,21 +1104,22 @@ public class HapClientTest { // Inject some initial presets List presets = - new ArrayList(Arrays.asList( - new BluetoothHapPresetInfo.Builder(0x01, "One") - .setAvailable(true) - .setWritable(false) - .build(), - new BluetoothHapPresetInfo.Builder(0x02, "Two") - .setAvailable(true) - .setWritable(true) - .build(), - new BluetoothHapPresetInfo.Builder(0x03, "Three") - .setAvailable(false) - .setWritable(false) - .build())); - mService.updateDevicePresetsCache(device, - HapClientStackEvent.PRESET_INFO_REASON_ALL_PRESET_INFO, presets); + new ArrayList( + Arrays.asList( + new BluetoothHapPresetInfo.Builder(0x01, "One") + .setAvailable(true) + .setWritable(false) + .build(), + new BluetoothHapPresetInfo.Builder(0x02, "Two") + .setAvailable(true) + .setWritable(true) + .build(), + new BluetoothHapPresetInfo.Builder(0x03, "Three") + .setAvailable(false) + .setWritable(false) + .build())); + mService.updateDevicePresetsCache( + device, HapClientStackEvent.PRESET_INFO_REASON_ALL_PRESET_INFO, presets); } private void testOnPresetSelected(BluetoothDevice device, int index) { @@ -1116,27 +1130,26 @@ public class HapClientTest { mService.messageFromNative(evt); try { - verify(mCallback, after(TIMEOUT_MS).times(1)).onPresetSelected(eq(device), - eq(evt.valueInt1), eq(BluetoothStatusCodes.REASON_LOCAL_STACK_REQUEST)); + verify(mCallback, after(TIMEOUT_MS).times(1)) + .onPresetSelected( + eq(device), + eq(evt.valueInt1), + eq(BluetoothStatusCodes.REASON_LOCAL_STACK_REQUEST)); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } - /** - * Helper function to test okToConnect() method - */ - private void testOkToConnectCase(BluetoothDevice device, int bondState, int policy, - boolean expected) { + /** Helper function to test okToConnect() method */ + private void testOkToConnectCase( + BluetoothDevice device, int bondState, int policy, boolean expected) { doReturn(bondState).when(mAdapterService).getBondState(device); when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.HAP_CLIENT)) .thenReturn(policy); Assert.assertEquals(expected, mService.okToConnect(device)); } - /** - * Helper function to get byte array for a device address - */ + /** Helper function to get byte array for a device address */ private byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java index c730910e334..a49b1d53c5d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java @@ -75,20 +75,20 @@ public class HearingAidNativeInterfaceTest { @Test public void onConnectionStateChanged() { BluetoothDevice device = TestUtils.getTestDevice(mAdapter, 0); - mNativeInterface.onConnectionStateChanged(BluetoothProfile.STATE_CONNECTED, - mNativeInterface.getByteAddress(device)); + mNativeInterface.onConnectionStateChanged( + BluetoothProfile.STATE_CONNECTED, mNativeInterface.getByteAddress(device)); ArgumentCaptor event = ArgumentCaptor.forClass(HearingAidStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HearingAidStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + assertThat(event.getValue().type) + .isEqualTo(HearingAidStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); assertThat(event.getValue().valueInt1).isEqualTo(BluetoothProfile.STATE_CONNECTED); Mockito.clearInvocations(mService); HearingAidService.setHearingAidService(null); - mNativeInterface.onConnectionStateChanged(BluetoothProfile.STATE_CONNECTED, - mNativeInterface.getByteAddress(device)); + mNativeInterface.onConnectionStateChanged( + BluetoothProfile.STATE_CONNECTED, mNativeInterface.getByteAddress(device)); verify(mService, never()).messageFromNative(any()); } @@ -97,21 +97,21 @@ public class HearingAidNativeInterfaceTest { BluetoothDevice device = TestUtils.getTestDevice(mAdapter, 0); byte capabilities = 0; long hiSyncId = 100; - mNativeInterface.onDeviceAvailable(capabilities, hiSyncId, - mNativeInterface.getByteAddress(device)); + mNativeInterface.onDeviceAvailable( + capabilities, hiSyncId, mNativeInterface.getByteAddress(device)); ArgumentCaptor event = ArgumentCaptor.forClass(HearingAidStackEvent.class); verify(mService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - HearingAidStackEvent.EVENT_TYPE_DEVICE_AVAILABLE); + assertThat(event.getValue().type) + .isEqualTo(HearingAidStackEvent.EVENT_TYPE_DEVICE_AVAILABLE); assertThat(event.getValue().valueInt1).isEqualTo(capabilities); assertThat(event.getValue().valueLong2).isEqualTo(hiSyncId); Mockito.clearInvocations(mService); HearingAidService.setHearingAidService(null); - mNativeInterface.onDeviceAvailable(capabilities, hiSyncId, - mNativeInterface.getByteAddress(device)); + mNativeInterface.onDeviceAvailable( + capabilities, hiSyncId, mNativeInterface.getByteAddress(device)); verify(mService, never()).messageFromNative(any()); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidStateMachineTest.java index f35f6b34359..3c58462a17e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidStateMachineTest.java @@ -74,10 +74,14 @@ public class HearingAidStateMachineTest { // Set up thread and looper mHandlerThread = new HandlerThread("HearingAidStateMachineTestHandlerThread"); mHandlerThread.start(); - mHearingAidStateMachine = new HearingAidStateMachine(mTestDevice, mHearingAidService, - mHearingAidNativeInterface, mHandlerThread.getLooper()); + mHearingAidStateMachine = + new HearingAidStateMachine( + mTestDevice, + mHearingAidService, + mHearingAidNativeInterface, + mHandlerThread.getLooper()); // Override the timeout value to speed up the test - mHearingAidStateMachine.sConnectTimeoutMs = 1000; // 1s + mHearingAidStateMachine.sConnectTimeoutMs = 1000; // 1s mHearingAidStateMachine.start(); } @@ -88,13 +92,11 @@ public class HearingAidStateMachineTest { TestUtils.clearAdapterService(mAdapterService); } - /** - * Test that default state is disconnected - */ + /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, - mHearingAidStateMachine.getConnectionState()); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mHearingAidStateMachine.getConnectionState()); } /** @@ -106,9 +108,7 @@ public class HearingAidStateMachineTest { doReturn(allow).when(mHearingAidService).okToConnect(any(BluetoothDevice.class)); } - /** - * Test that an incoming connection with low priority is rejected - */ + /** Test that an incoming connection with low priority is rejected */ @Test public void testIncomingPriorityReject() { allowConnection(false); @@ -121,16 +121,15 @@ public class HearingAidStateMachineTest { mHearingAidStateMachine.sendMessage(HearingAidStateMachine.STACK_EVENT, connStCh); // Verify that no connection state broadcast is executed - verify(mHearingAidService, after(TIMEOUT_MS).never()).sendBroadcast(any(Intent.class), - anyString(), any(Bundle.class)); + verify(mHearingAidService, after(TIMEOUT_MS).never()) + .sendBroadcast(any(Intent.class), anyString(), any(Bundle.class)); // Check that we are in Disconnected state - Assert.assertThat(mHearingAidStateMachine.getCurrentState(), + Assert.assertThat( + mHearingAidStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HearingAidStateMachine.Disconnected.class)); } - /** - * Test that an incoming connection with high priority is accepted - */ + /** Test that an incoming connection with high priority is accepted */ @Test public void testIncomingPriorityAccept() { allowConnection(true); @@ -144,13 +143,15 @@ public class HearingAidStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mHearingAidService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - intentArgument1.capture(), anyString(), any(Bundle.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify(mHearingAidService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mHearingAidStateMachine.getCurrentState(), + Assert.assertThat( + mHearingAidStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HearingAidStateMachine.Connecting.class)); // Send a message to trigger connection completed @@ -163,23 +164,24 @@ public class HearingAidStateMachineTest { // Verify that the expected number of broadcasts are executed: // - two calls to broadcastConnectionState(): Disconnected -> Conecting -> Connected ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mHearingAidService, timeout(TIMEOUT_MS).times(2)).sendBroadcast( - intentArgument2.capture(), anyString(), any(Bundle.class)); + verify(mHearingAidService, timeout(TIMEOUT_MS).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); // Check that we are in Connected state - Assert.assertThat(mHearingAidStateMachine.getCurrentState(), + Assert.assertThat( + mHearingAidStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HearingAidStateMachine.Connected.class)); } - /** - * Test that an outgoing connection times out - */ + /** Test that an outgoing connection times out */ @Test public void testOutgoingTimeout() { allowConnection(true); - doReturn(true).when(mHearingAidNativeInterface).connectHearingAid(any( - BluetoothDevice.class)); - doReturn(true).when(mHearingAidNativeInterface).disconnectHearingAid(any( - BluetoothDevice.class)); + doReturn(true) + .when(mHearingAidNativeInterface) + .connectHearingAid(any(BluetoothDevice.class)); + doReturn(true) + .when(mHearingAidNativeInterface) + .disconnectHearingAid(any(BluetoothDevice.class)); when(mHearingAidService.isConnectedPeerDevices(mTestDevice)).thenReturn(true); // Send a connect request @@ -187,40 +189,42 @@ public class HearingAidStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mHearingAidService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - intentArgument1.capture(), - anyString(), any(Bundle.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify(mHearingAidService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mHearingAidStateMachine.getCurrentState(), + Assert.assertThat( + mHearingAidStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HearingAidStateMachine.Connecting.class)); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mHearingAidService, timeout(HearingAidStateMachine.sConnectTimeoutMs * 2).times( - 2)).sendBroadcast(intentArgument2.capture(), anyString(), - any(Bundle.class)); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + verify(mHearingAidService, timeout(HearingAidStateMachine.sConnectTimeoutMs * 2).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Disconnected state - Assert.assertThat(mHearingAidStateMachine.getCurrentState(), + Assert.assertThat( + mHearingAidStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HearingAidStateMachine.Disconnected.class)); verify(mHearingAidNativeInterface).addToAcceptlist(eq(mTestDevice)); } - /** - * Test that an incoming connection times out - */ + /** Test that an incoming connection times out */ @Test public void testIncomingTimeout() { allowConnection(true); - doReturn(true).when(mHearingAidNativeInterface).connectHearingAid(any( - BluetoothDevice.class)); - doReturn(true).when(mHearingAidNativeInterface).disconnectHearingAid(any( - BluetoothDevice.class)); + doReturn(true) + .when(mHearingAidNativeInterface) + .connectHearingAid(any(BluetoothDevice.class)); + doReturn(true) + .when(mHearingAidNativeInterface) + .disconnectHearingAid(any(BluetoothDevice.class)); when(mHearingAidService.isConnectedPeerDevices(mTestDevice)).thenReturn(true); // Inject an event for when incoming connection is requested @@ -232,26 +236,28 @@ public class HearingAidStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); - verify(mHearingAidService, timeout(TIMEOUT_MS).times(1)).sendBroadcast( - intentArgument1.capture(), - anyString(), any(Bundle.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify(mHearingAidService, timeout(TIMEOUT_MS).times(1)) + .sendBroadcast(intentArgument1.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Connecting state - Assert.assertThat(mHearingAidStateMachine.getCurrentState(), + Assert.assertThat( + mHearingAidStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HearingAidStateMachine.Connecting.class)); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mHearingAidService, timeout(HearingAidStateMachine.sConnectTimeoutMs * 2).times( - 2)).sendBroadcast(intentArgument2.capture(), anyString(), - any(Bundle.class)); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + verify(mHearingAidService, timeout(HearingAidStateMachine.sConnectTimeoutMs * 2).times(2)) + .sendBroadcast(intentArgument2.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check that we are in Disconnected state - Assert.assertThat(mHearingAidStateMachine.getCurrentState(), + Assert.assertThat( + mHearingAidStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HearingAidStateMachine.Disconnected.class)); verify(mHearingAidNativeInterface).addToAcceptlist(eq(mTestDevice)); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java index 1ca0830d79e..78a838fffeb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java @@ -67,8 +67,7 @@ public class AtPhonebookTest { @Mock private HeadsetNativeInterface mNativeInterface; private AtPhonebook mAtPhonebook; - @Spy - private BluetoothMethodProxy mHfpMethodProxy = BluetoothMethodProxy.getInstance(); + @Spy private BluetoothMethodProxy mHfpMethodProxy = BluetoothMethodProxy.getInstance(); @Before public void setUp() throws Exception { @@ -90,8 +89,8 @@ public class AtPhonebookTest { @Test public void checkAccessPermission_returnsCorrectPermission() { - assertThat(mAtPhonebook.checkAccessPermission(mTestDevice)).isEqualTo( - BluetoothDevice.ACCESS_UNKNOWN); + assertThat(mAtPhonebook.checkAccessPermission(mTestDevice)) + .isEqualTo(BluetoothDevice.ACCESS_UNKNOWN); } @Test @@ -104,28 +103,33 @@ public class AtPhonebookTest { @Test public void handleCscsCommand() { mAtPhonebook.handleCscsCommand(INVALID_COMMAND, AtPhonebook.TYPE_READ, mTestDevice); - verify(mNativeInterface).atResponseString(mTestDevice, - "+CSCS: \"" + "UTF-8" + "\""); + verify(mNativeInterface).atResponseString(mTestDevice, "+CSCS: \"" + "UTF-8" + "\""); mAtPhonebook.handleCscsCommand(INVALID_COMMAND, AtPhonebook.TYPE_TEST, mTestDevice); - verify(mNativeInterface).atResponseString(mTestDevice, - "+CSCS: (\"UTF-8\",\"IRA\",\"GSM\")"); + verify(mNativeInterface) + .atResponseString(mTestDevice, "+CSCS: (\"UTF-8\",\"IRA\",\"GSM\")"); mAtPhonebook.handleCscsCommand(INVALID_COMMAND, AtPhonebook.TYPE_SET, mTestDevice); - verify(mNativeInterface, atLeastOnce()).atResponseCode(mTestDevice, - HeadsetHalConstants.AT_RESPONSE_ERROR, -1); + verify(mNativeInterface, atLeastOnce()) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, -1); mAtPhonebook.handleCscsCommand("command=GSM", AtPhonebook.TYPE_SET, mTestDevice); - verify(mNativeInterface, atLeastOnce()).atResponseCode(mTestDevice, - HeadsetHalConstants.AT_RESPONSE_OK, -1); + verify(mNativeInterface, atLeastOnce()) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, -1); mAtPhonebook.handleCscsCommand("command=ERR", AtPhonebook.TYPE_SET, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.OPERATION_NOT_SUPPORTED); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.OPERATION_NOT_SUPPORTED); mAtPhonebook.handleCscsCommand(INVALID_COMMAND, AtPhonebook.TYPE_UNKNOWN, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.TEXT_HAS_INVALID_CHARS); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.TEXT_HAS_INVALID_CHARS); } @Test @@ -133,28 +137,37 @@ public class AtPhonebookTest { mAtPhonebook.handleCpbsCommand(INVALID_COMMAND, AtPhonebook.TYPE_READ, mTestDevice); int size = mAtPhonebook.getPhonebookResult("ME", true).cursor.getCount(); int maxSize = mAtPhonebook.getMaxPhoneBookSize(size); - verify(mNativeInterface).atResponseString(mTestDevice, - "+CPBS: \"" + "ME" + "\"," + size + "," + maxSize); + verify(mNativeInterface) + .atResponseString(mTestDevice, "+CPBS: \"" + "ME" + "\"," + size + "," + maxSize); mAtPhonebook.handleCpbsCommand(INVALID_COMMAND, AtPhonebook.TYPE_TEST, mTestDevice); - verify(mNativeInterface).atResponseString(mTestDevice, - "+CPBS: (\"ME\",\"SM\",\"DC\",\"RC\",\"MC\")"); + verify(mNativeInterface) + .atResponseString(mTestDevice, "+CPBS: (\"ME\",\"SM\",\"DC\",\"RC\",\"MC\")"); mAtPhonebook.handleCpbsCommand(INVALID_COMMAND, AtPhonebook.TYPE_SET, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.OPERATION_NOT_SUPPORTED); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.OPERATION_NOT_SUPPORTED); mAtPhonebook.handleCpbsCommand("command=ERR", AtPhonebook.TYPE_SET, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.OPERATION_NOT_ALLOWED); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.OPERATION_NOT_ALLOWED); mAtPhonebook.handleCpbsCommand("command=SM", AtPhonebook.TYPE_SET, mTestDevice); - verify(mNativeInterface, atLeastOnce()).atResponseCode(mTestDevice, - HeadsetHalConstants.AT_RESPONSE_OK, -1); + verify(mNativeInterface, atLeastOnce()) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, -1); mAtPhonebook.handleCpbsCommand(INVALID_COMMAND, AtPhonebook.TYPE_UNKNOWN, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.TEXT_HAS_INVALID_CHARS); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.TEXT_HAS_INVALID_CHARS); } @Test @@ -165,53 +178,60 @@ public class AtPhonebookTest { size = 1; } verify(mNativeInterface).atResponseString(mTestDevice, "+CPBR: (1-" + size + "),30,30"); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, - -1); + verify(mNativeInterface) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, -1); mAtPhonebook.handleCpbrCommand(INVALID_COMMAND, AtPhonebook.TYPE_SET, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - -1); + verify(mNativeInterface) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, -1); mAtPhonebook.handleCpbrCommand("command=ERR", AtPhonebook.TYPE_SET, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.TEXT_HAS_INVALID_CHARS); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.TEXT_HAS_INVALID_CHARS); mAtPhonebook.handleCpbrCommand("command=123,123", AtPhonebook.TYPE_SET, mTestDevice); assertThat(mAtPhonebook.getCheckingAccessPermission()).isTrue(); mAtPhonebook.handleCpbrCommand(INVALID_COMMAND, AtPhonebook.TYPE_UNKNOWN, mTestDevice); - verify(mNativeInterface, atLeastOnce()).atResponseCode(mTestDevice, - HeadsetHalConstants.AT_RESPONSE_ERROR, BluetoothCmeError.TEXT_HAS_INVALID_CHARS); + verify(mNativeInterface, atLeastOnce()) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.TEXT_HAS_INVALID_CHARS); } @Test public void processCpbrCommand() { mAtPhonebook.handleCpbsCommand("command=SM", AtPhonebook.TYPE_SET, mTestDevice); - assertThat(mAtPhonebook.processCpbrCommand(mTestDevice)).isEqualTo( - HeadsetHalConstants.AT_RESPONSE_OK); + assertThat(mAtPhonebook.processCpbrCommand(mTestDevice)) + .isEqualTo(HeadsetHalConstants.AT_RESPONSE_OK); mAtPhonebook.handleCpbsCommand("command=ME", AtPhonebook.TYPE_SET, mTestDevice); - assertThat(mAtPhonebook.processCpbrCommand(mTestDevice)).isEqualTo( - HeadsetHalConstants.AT_RESPONSE_OK); + assertThat(mAtPhonebook.processCpbrCommand(mTestDevice)) + .isEqualTo(HeadsetHalConstants.AT_RESPONSE_OK); mAtPhonebook.mCurrentPhonebook = "ER"; - assertThat(mAtPhonebook.processCpbrCommand(mTestDevice)).isEqualTo( - HeadsetHalConstants.AT_RESPONSE_ERROR); + assertThat(mAtPhonebook.processCpbrCommand(mTestDevice)) + .isEqualTo(HeadsetHalConstants.AT_RESPONSE_ERROR); } @Test public void processCpbrCommand_withMobilePhonebook() { Cursor mockCursorOne = mock(Cursor.class); when(mockCursorOne.getCount()).thenReturn(1); - when(mockCursorOne.getColumnIndex(Phone.TYPE)).thenReturn(1); //TypeColumn - when(mockCursorOne.getColumnIndex(Phone.NUMBER)).thenReturn(2); //numberColumn + when(mockCursorOne.getColumnIndex(Phone.TYPE)).thenReturn(1); // TypeColumn + when(mockCursorOne.getColumnIndex(Phone.NUMBER)).thenReturn(2); // numberColumn when(mockCursorOne.getColumnIndex(Phone.DISPLAY_NAME)).thenReturn(3); // nameColumn when(mockCursorOne.getInt(1)).thenReturn(Phone.TYPE_WORK); when(mockCursorOne.getString(2)).thenReturn(null); when(mockCursorOne.getString(3)).thenReturn(null); when(mockCursorOne.moveToNext()).thenReturn(false); - doReturn(mockCursorOne).when(mHfpMethodProxy).contentResolverQuery(any(), any(), any(), - any(), any()); + doReturn(mockCursorOne) + .when(mHfpMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any()); mAtPhonebook.mCurrentPhonebook = "ME"; mAtPhonebook.mCpbrIndex1 = 1; @@ -219,8 +239,19 @@ public class AtPhonebookTest { mAtPhonebook.processCpbrCommand(mTestDevice); - String expected = "+CPBR: " + 1 + ",\"" + "" + "\"," + PhoneNumberUtils.toaFromString("") - + ",\"" + "" + "/" + AtPhonebook.getPhoneType(Phone.TYPE_WORK) + "\"" + "\r\n\r\n"; + String expected = + "+CPBR: " + + 1 + + ",\"" + + "" + + "\"," + + PhoneNumberUtils.toaFromString("") + + ",\"" + + "" + + "/" + + AtPhonebook.getPhoneType(Phone.TYPE_WORK) + + "\"" + + "\r\n\r\n"; verify(mNativeInterface).atResponseString(mTestDevice, expected); } @@ -233,16 +264,18 @@ public class AtPhonebookTest { String number = "1".repeat(31); when(mockCursorOne.getString(1)).thenReturn(number); when(mockCursorOne.getInt(2)).thenReturn(CallLog.Calls.PRESENTATION_RESTRICTED); - doReturn(mockCursorOne).when(mHfpMethodProxy).contentResolverQuery(any(), any(), any(), - any(), any()); + doReturn(mockCursorOne) + .when(mHfpMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any()); Cursor mockCursorTwo = mock(Cursor.class); when(mockCursorTwo.moveToFirst()).thenReturn(true); String name = "k".repeat(30); when(mockCursorTwo.getString(0)).thenReturn(name); when(mockCursorTwo.getInt(1)).thenReturn(1); - doReturn(mockCursorTwo).when(mHfpMethodProxy).contentResolverQuery(any(), any(), any(), - any(), any(), any()); + doReturn(mockCursorTwo) + .when(mHfpMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mAtPhonebook.mCurrentPhonebook = "MC"; mAtPhonebook.mCpbrIndex1 = 1; @@ -250,9 +283,17 @@ public class AtPhonebookTest { mAtPhonebook.processCpbrCommand(mTestDevice); - String expected = "+CPBR: " + 1 + ",\"" + "" + "\"," + PhoneNumberUtils.toaFromString( - number) + ",\"" + mTargetContext.getString(R.string.unknownNumber) + "\"" - + "\r\n\r\n"; + String expected = + "+CPBR: " + + 1 + + ",\"" + + "" + + "\"," + + PhoneNumberUtils.toaFromString(number) + + ",\"" + + mTargetContext.getString(R.string.unknownNumber) + + "\"" + + "\r\n\r\n"; verify(mNativeInterface).atResponseString(mTestDevice, expected); } @@ -265,16 +306,18 @@ public class AtPhonebookTest { String number = "1".repeat(31); when(mockCursorOne.getString(1)).thenReturn(number); when(mockCursorOne.getInt(2)).thenReturn(CallLog.Calls.PRESENTATION_RESTRICTED); - doReturn(mockCursorOne).when(mHfpMethodProxy).contentResolverQuery(any(), any(), any(), - any(), any()); + doReturn(mockCursorOne) + .when(mHfpMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any()); Cursor mockCursorTwo = mock(Cursor.class); when(mockCursorTwo.moveToFirst()).thenReturn(true); String name = "k".repeat(30); when(mockCursorTwo.getString(0)).thenReturn(name); when(mockCursorTwo.getInt(1)).thenReturn(1); - doReturn(mockCursorTwo).when(mHfpMethodProxy).contentResolverQuery(any(), any(), any(), - any(), any(), any()); + doReturn(mockCursorTwo) + .when(mHfpMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mAtPhonebook.mCurrentPhonebook = "RC"; mAtPhonebook.mCpbrIndex1 = 1; @@ -284,8 +327,17 @@ public class AtPhonebookTest { mAtPhonebook.processCpbrCommand(mTestDevice); String expectedName = new String(GsmAlphabet.stringToGsm8BitPacked(name.substring(0, 28))); - String expected = "+CPBR: " + 1 + ",\"" + number.substring(0, 30) + "\"," - + PhoneNumberUtils.toaFromString(number) + ",\"" + expectedName + "\"" + "\r\n\r\n"; + String expected = + "+CPBR: " + + 1 + + ",\"" + + number.substring(0, 30) + + "\"," + + PhoneNumberUtils.toaFromString(number) + + ",\"" + + expectedName + + "\"" + + "\r\n\r\n"; verify(mNativeInterface).atResponseString(mTestDevice, expected); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java index 3034d5edb37..a97c4f15db1 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java @@ -35,8 +35,7 @@ public class BluetoothHeadsetBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private HeadsetService mService; + @Mock private HeadsetService mService; private AttributionSource mAttributionSource; private BluetoothDevice mTestDevice; @@ -70,7 +69,7 @@ public class BluetoothHeadsetBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] { BluetoothProfile.STATE_CONNECTED }; + int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); verify(mService).getDevicesMatchingConnectionStates(states); } @@ -190,7 +189,7 @@ public class BluetoothHeadsetBinderTest { String name = "Unknown"; mBinder.phoneStateChanged( numActive, numHeld, callState, number, type, name, mAttributionSource); - verify(mService).phoneStateChanged( - numActive, numHeld, callState, number, type, name, false); + verify(mService) + .phoneStateChanged(numActive, numHeld, callState, number, type, name, false); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetAgIndicatorEnableStateTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetAgIndicatorEnableStateTest.java index 5c2850472ea..f034bf44cf9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetAgIndicatorEnableStateTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetAgIndicatorEnableStateTest.java @@ -30,8 +30,8 @@ public class HeadsetAgIndicatorEnableStateTest { @Test public void hashCode_returnsCorrectResult() { - HeadsetAgIndicatorEnableState state = new HeadsetAgIndicatorEnableState(true, true, true, - true); + HeadsetAgIndicatorEnableState state = + new HeadsetAgIndicatorEnableState(true, true, true, true); assertThat(state.hashCode()).isEqualTo(15); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetClccResponseTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetClccResponseTest.java index 9e5788afe52..3f6603ff3af 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetClccResponseTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetClccResponseTest.java @@ -37,8 +37,15 @@ public class HeadsetClccResponseTest { @Test public void constructor() { - HeadsetClccResponse response = new HeadsetClccResponse(TEST_INDEX, TEST_DIRECTION, - TEST_STATUS, TEST_MODE, TEST_MPTY, TEST_NUMBER, TEST_TYPE); + HeadsetClccResponse response = + new HeadsetClccResponse( + TEST_INDEX, + TEST_DIRECTION, + TEST_STATUS, + TEST_MODE, + TEST_MPTY, + TEST_NUMBER, + TEST_TYPE); assertThat(response.mIndex).isEqualTo(TEST_INDEX); assertThat(response.mDirection).isEqualTo(TEST_DIRECTION); @@ -51,33 +58,71 @@ public class HeadsetClccResponseTest { @Test public void buildString() { - HeadsetClccResponse response = new HeadsetClccResponse(TEST_INDEX, TEST_DIRECTION, - TEST_STATUS, TEST_MODE, TEST_MPTY, TEST_NUMBER, TEST_TYPE); + HeadsetClccResponse response = + new HeadsetClccResponse( + TEST_INDEX, + TEST_DIRECTION, + TEST_STATUS, + TEST_MODE, + TEST_MPTY, + TEST_NUMBER, + TEST_TYPE); StringBuilder builder = new StringBuilder(); response.buildString(builder); String expectedString = - response.getClass().getSimpleName() + "[index=" + TEST_INDEX + ", direction=" - + TEST_DIRECTION + ", status=" + TEST_STATUS + ", callMode=" + TEST_MODE - + ", isMultiParty=" + TEST_MPTY + ", number=" + "***" + ", type=" - + TEST_TYPE + "]"; + response.getClass().getSimpleName() + + "[index=" + + TEST_INDEX + + ", direction=" + + TEST_DIRECTION + + ", status=" + + TEST_STATUS + + ", callMode=" + + TEST_MODE + + ", isMultiParty=" + + TEST_MPTY + + ", number=" + + "***" + + ", type=" + + TEST_TYPE + + "]"; assertThat(response.toString()).isEqualTo(expectedString); } @Test public void buildString_withNoNumber() { - HeadsetClccResponse response = new HeadsetClccResponse(TEST_INDEX, TEST_DIRECTION, - TEST_STATUS, TEST_MODE, TEST_MPTY, null, TEST_TYPE); + HeadsetClccResponse response = + new HeadsetClccResponse( + TEST_INDEX, + TEST_DIRECTION, + TEST_STATUS, + TEST_MODE, + TEST_MPTY, + null, + TEST_TYPE); StringBuilder builder = new StringBuilder(); response.buildString(builder); String expectedString = - response.getClass().getSimpleName() + "[index=" + TEST_INDEX + ", direction=" - + TEST_DIRECTION + ", status=" + TEST_STATUS + ", callMode=" + TEST_MODE - + ", isMultiParty=" + TEST_MPTY + ", number=" + "null" + ", type=" - + TEST_TYPE + "]"; + response.getClass().getSimpleName() + + "[index=" + + TEST_INDEX + + ", direction=" + + TEST_DIRECTION + + ", status=" + + TEST_STATUS + + ", callMode=" + + TEST_MODE + + ", isMultiParty=" + + TEST_MPTY + + ", number=" + + "null" + + ", type=" + + TEST_TYPE + + "]"; assertThat(response.toString()).isEqualTo(expectedString); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java index 2fb01939b7f..7a9c409fb3c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java @@ -48,9 +48,7 @@ import org.mockito.junit.MockitoRule; import java.util.HashMap; -/** - * Unit test to verify various methods in {@link HeadsetPhoneState} - */ +/** Unit test to verify various methods in {@link HeadsetPhoneState} */ @MediumTest @RunWith(AndroidJUnit4.class) public class HeadsetPhoneStateTest { @@ -81,18 +79,18 @@ public class HeadsetPhoneStateTest { when(mISubBinder.queryLocalInterface(anyString())).thenReturn(mISub); mServiceManagerMockedServices.put("isub", mISubBinder); mServiceManagerOriginalServices = - TestUtils.replaceField(ServiceManager.class, "sCache", null, - mServiceManagerMockedServices); + TestUtils.replaceField( + ServiceManager.class, "sCache", null, mServiceManagerMockedServices); // Stub other methods - when(mHeadsetService.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn( - mTelephonyManager); - when(mHeadsetService.getSystemServiceName(TelephonyManager.class)).thenReturn( - Context.TELEPHONY_SERVICE); + when(mHeadsetService.getSystemService(Context.TELEPHONY_SERVICE)) + .thenReturn(mTelephonyManager); + when(mHeadsetService.getSystemServiceName(TelephonyManager.class)) + .thenReturn(Context.TELEPHONY_SERVICE); when(mTelephonyManager.createForSubscriptionId(anyInt())).thenReturn(mTelephonyManager); - when(mHeadsetService.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE)).thenReturn( - mSubscriptionManager); - when(mHeadsetService.getSystemServiceName(SubscriptionManager.class)).thenReturn( - Context.TELEPHONY_SUBSCRIPTION_SERVICE); + when(mHeadsetService.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE)) + .thenReturn(mSubscriptionManager); + when(mHeadsetService.getSystemServiceName(SubscriptionManager.class)) + .thenReturn(Context.TELEPHONY_SUBSCRIPTION_SERVICE); mHandlerThread = new HandlerThread("HeadsetStateMachineTestHandlerThread"); mHandlerThread.start(); when(mHeadsetService.getStateMachinesThreadLooper()).thenReturn(mHandlerThread.getLooper()); @@ -104,16 +102,14 @@ public class HeadsetPhoneStateTest { mHeadsetPhoneState.cleanup(); mHandlerThread.quit(); if (mServiceManagerOriginalServices != null) { - TestUtils.replaceField(ServiceManager.class, "sCache", null, - mServiceManagerOriginalServices); + TestUtils.replaceField( + ServiceManager.class, "sCache", null, mServiceManagerOriginalServices); mServiceManagerOriginalServices = null; } TelephonyManager.enableServiceHandleCaching(); } - /** - * Verify that {@link PhoneStateListener#LISTEN_NONE} should result in no subscription - */ + /** Verify that {@link PhoneStateListener#LISTEN_NONE} should result in no subscription */ @Test public void testListenForPhoneState_NoneResultsNoListen() { BluetoothDevice device1 = TestUtils.getTestDevice(mAdapter, 1); @@ -130,25 +126,30 @@ public class HeadsetPhoneStateTest { BluetoothDevice device1 = TestUtils.getTestDevice(mAdapter, 1); mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_SERVICE_STATE); verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SERVICE_STATE)); - verify(mTelephonyManager).clearSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + verify(mTelephonyManager) + .clearSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); verifyNoMoreInteractions(mTelephonyManager); } /** - * Verify that {@link PhoneStateListener#LISTEN_SERVICE_STATE} and - * {@link PhoneStateListener#LISTEN_SIGNAL_STRENGTHS} should result in corresponding - * subscription + * Verify that {@link PhoneStateListener#LISTEN_SERVICE_STATE} and {@link + * PhoneStateListener#LISTEN_SIGNAL_STRENGTHS} should result in corresponding subscription */ @Test public void testListenForPhoneState_ServiceAndSignalStrength() { BluetoothDevice device1 = TestUtils.getTestDevice(mAdapter, 1); - mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); - verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); - verify(mTelephonyManager).setSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + mHeadsetPhoneState.listenForPhoneState( + device1, + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); + verify(mTelephonyManager) + .listen( + any(), + eq( + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); + verify(mTelephonyManager) + .setSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); } /** @@ -158,37 +159,47 @@ public class HeadsetPhoneStateTest { @Test public void testListenForPhoneState_ServiceAndSignalStrengthUpdateTurnOffSignalStrengh() { BluetoothDevice device1 = TestUtils.getTestDevice(mAdapter, 1); - mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); - verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); - verify(mTelephonyManager).setSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + mHeadsetPhoneState.listenForPhoneState( + device1, + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); + verify(mTelephonyManager) + .listen( + any(), + eq( + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); + verify(mTelephonyManager) + .setSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_SERVICE_STATE); verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_NONE)); verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SERVICE_STATE)); - verify(mTelephonyManager, times(2)).clearSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + verify(mTelephonyManager, times(2)) + .clearSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); } - /** - * Verify that completely disabling all updates should unsubscribe from everything - */ + /** Verify that completely disabling all updates should unsubscribe from everything */ @Test public void testListenForPhoneState_ServiceAndSignalStrengthUpdateTurnOffAll() { BluetoothDevice device1 = TestUtils.getTestDevice(mAdapter, 1); - mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); - verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); - verify(mTelephonyManager).setSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + mHeadsetPhoneState.listenForPhoneState( + device1, + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); + verify(mTelephonyManager) + .listen( + any(), + eq( + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); + verify(mTelephonyManager) + .setSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_NONE); verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_NONE)); - verify(mTelephonyManager, times(2)).clearSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + verify(mTelephonyManager, times(2)) + .clearSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); } /** @@ -201,23 +212,31 @@ public class HeadsetPhoneStateTest { BluetoothDevice device1 = TestUtils.getTestDevice(mAdapter, 1); BluetoothDevice device2 = TestUtils.getTestDevice(mAdapter, 2); // Enabling updates from first device should trigger subscription - mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); - verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); - verify(mTelephonyManager).setSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + mHeadsetPhoneState.listenForPhoneState( + device1, + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); + verify(mTelephonyManager) + .listen( + any(), + eq( + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); + verify(mTelephonyManager) + .setSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); // Enabling updates from second device should not trigger the same subscription - mHeadsetPhoneState.listenForPhoneState(device2, PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); + mHeadsetPhoneState.listenForPhoneState( + device2, + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); // Disabling updates from first device should not cancel subscription mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_NONE); // Disabling updates from second device should cancel subscription mHeadsetPhoneState.listenForPhoneState(device2, PhoneStateListener.LISTEN_NONE); verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_NONE)); - verify(mTelephonyManager, times(2)).clearSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + verify(mTelephonyManager, times(2)) + .clearSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); } /** @@ -232,27 +251,29 @@ public class HeadsetPhoneStateTest { // Partially enabling updates from first device should trigger partial subscription mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_SERVICE_STATE); verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SERVICE_STATE)); - verify(mTelephonyManager).clearSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + verify(mTelephonyManager) + .clearSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); verifyNoMoreInteractions(mTelephonyManager); // Partially enabling updates from second device should trigger partial subscription - mHeadsetPhoneState.listenForPhoneState(device2, - PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); + mHeadsetPhoneState.listenForPhoneState(device2, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_NONE)); - verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); - verify(mTelephonyManager).setSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + verify(mTelephonyManager) + .listen( + any(), + eq( + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); + verify(mTelephonyManager) + .setSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); // Partially disabling updates from first device should not cancel all subscription mHeadsetPhoneState.listenForPhoneState(device1, PhoneStateListener.LISTEN_NONE); verify(mTelephonyManager, times(2)).listen(any(), eq(PhoneStateListener.LISTEN_NONE)); - verify(mTelephonyManager).listen( - any(), eq(PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); + verify(mTelephonyManager).listen(any(), eq(PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)); // Partially disabling updates from second device should cancel subscription mHeadsetPhoneState.listenForPhoneState(device2, PhoneStateListener.LISTEN_NONE); verify(mTelephonyManager, times(3)).listen(any(), eq(PhoneStateListener.LISTEN_NONE)); - verify(mTelephonyManager, times(4)).clearSignalStrengthUpdateRequest( - any(SignalStrengthUpdateRequest.class)); + verify(mTelephonyManager, times(4)) + .clearSignalStrengthUpdateRequest(any(SignalStrengthUpdateRequest.class)); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStackEventTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStackEventTest.java index b0016203f90..2d3e4cd9371 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStackEventTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStackEventTest.java @@ -39,8 +39,9 @@ public class HeadsetStackEventTest { HeadsetStackEvent event = new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_NONE, device); assertThat(event.getTypeString()).isEqualTo("EVENT_TYPE_NONE"); - event = new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - device); + event = + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, device); assertThat(event.getTypeString()).isEqualTo("EVENT_TYPE_CONNECTION_STATE_CHANGED"); event = new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, device); @@ -70,8 +71,9 @@ public class HeadsetStackEventTest { event = new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AT_CHLD, device); assertThat(event.getTypeString()).isEqualTo("EVENT_TYPE_AT_CHLD"); - event = new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_SUBSCRIBER_NUMBER_REQUEST, - device); + event = + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_SUBSCRIBER_NUMBER_REQUEST, device); assertThat(event.getTypeString()).isEqualTo("EVENT_TYPE_SUBSCRIBER_NUMBER_REQUEST"); event = new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AT_CIND, device); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java index 6c09a44c079..602339c9d5f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java @@ -75,9 +75,7 @@ import org.mockito.junit.MockitoRule; import java.util.ArrayList; -/** - * Tests for {@link HeadsetStateMachine} - */ +/** Tests for {@link HeadsetStateMachine} */ @MediumTest @RunWith(AndroidJUnit4.class) public class HeadsetStateMachineTest { @@ -138,29 +136,36 @@ public class HeadsetStateMachineTest { // Stub headset service mMockContentResolver = new MockContentResolver(); when(mHeadsetService.getContentResolver()).thenReturn(mMockContentResolver); - doReturn(BluetoothDevice.BOND_BONDED).when(mAdapterService) + doReturn(BluetoothDevice.BOND_BONDED) + .when(mAdapterService) .getBondState(any(BluetoothDevice.class)); when(mHeadsetService.bindService(any(Intent.class), any(ServiceConnection.class), anyInt())) .thenReturn(true); - when(mHeadsetService.getResources()).thenReturn( - InstrumentationRegistry.getTargetContext().getResources()); - when(mHeadsetService.getPackageManager()).thenReturn( - InstrumentationRegistry.getContext().getPackageManager()); - when(mHeadsetService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetService.getResources()) + .thenReturn(InstrumentationRegistry.getTargetContext().getResources()); + when(mHeadsetService.getPackageManager()) + .thenReturn(InstrumentationRegistry.getContext().getPackageManager()); + when(mHeadsetService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); when(mHeadsetService.getForceScoAudio()).thenReturn(true); when(mHeadsetService.okToAcceptConnection(any(BluetoothDevice.class), anyBoolean())) .thenReturn(true); - when(mHeadsetService.isScoAcceptable(any(BluetoothDevice.class))).thenReturn( - BluetoothStatusCodes.SUCCESS); + when(mHeadsetService.isScoAcceptable(any(BluetoothDevice.class))) + .thenReturn(BluetoothStatusCodes.SUCCESS); // Setup thread and looper mHandlerThread = new HandlerThread("HeadsetStateMachineTestHandlerThread"); mHandlerThread.start(); // Modify CONNECT timeout to a smaller value for test only HeadsetStateMachine.sConnectTimeoutMs = CONNECT_TIMEOUT_TEST_MILLIS; - mHeadsetStateMachine = HeadsetObjectsFactory.getInstance() - .makeStateMachine(mTestDevice, mHandlerThread.getLooper(), mHeadsetService, - mAdapterService, mNativeInterface, mSystemInterface); + mHeadsetStateMachine = + HeadsetObjectsFactory.getInstance() + .makeStateMachine( + mTestDevice, + mHandlerThread.getLooper(), + mHeadsetService, + mAdapterService, + mNativeInterface, + mSystemInterface); } @After @@ -170,42 +175,44 @@ public class HeadsetStateMachineTest { TestUtils.clearAdapterService(mAdapterService); } - /** - * Test that default state is Disconnected - */ + /** Test that default state is Disconnected */ @Test public void testDefaultDisconnectedState() { - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, - mHeadsetStateMachine.getConnectionState()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mHeadsetStateMachine.getConnectionState()); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } - /** - * Test that state is Connected after calling setUpConnectedState() - */ + /** Test that state is Connected after calling setUpConnectedState() */ @Test public void testSetupConnectedState() { setUpConnectedState(); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, - mHeadsetStateMachine.getConnectionState()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTED, mHeadsetStateMachine.getConnectionState()); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connected.class)); } - /** - * Test state transition from Disconnected to Connecting state via CONNECT message - */ + /** Test state transition from Disconnected to Connecting state via CONNECT message */ @Test public void testStateTransition_DisconnectedToConnecting_Connect() { mHeadsetStateMachine.sendMessage(HeadsetStateMachine.CONNECT, mTestDevice); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED, + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connecting.class)); } @@ -214,16 +221,25 @@ public class HeadsetStateMachineTest { */ @Test public void testStateTransition_DisconnectedToConnecting_StackConnected() { - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_CONNECTED, mTestDevice)); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_CONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connecting.class)); } @@ -232,16 +248,25 @@ public class HeadsetStateMachineTest { */ @Test public void testStateTransition_DisconnectedToConnecting_StackConnecting() { - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_CONNECTING, mTestDevice)); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_CONNECTING, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connecting.class)); } @@ -253,49 +278,64 @@ public class HeadsetStateMachineTest { public void testStateTransition_ConnectingToDisconnected_StackDisconnected() { int numBroadcastsSent = setUpConnectingState(); // Indicate disconnecting to test state machine, which should do nothing - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, mTestDevice)); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, + mTestDevice)); // Should do nothing new - verify(mHeadsetService, - after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - any(Intent.class), any(UserHandle.class), anyString(), any(Bundle.class)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + any(Intent.class), any(UserHandle.class), anyString(), any(Bundle.class)); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connecting.class)); // Indicate connection failed to test state machine - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, mTestDevice)); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, + mTestDevice)); numBroadcastsSent++; - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING, + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } - /** - * Test state transition from Connecting to Disconnected state via CONNECT_TIMEOUT message - */ + /** Test state transition from Connecting to Disconnected state via CONNECT_TIMEOUT message */ @Test public void testStateTransition_ConnectingToDisconnected_Timeout() { int numBroadcastsSent = setUpConnectingState(); // Let the connection timeout numBroadcastsSent++; - verify(mHeadsetService, timeout(CONNECT_TIMEOUT_TEST_WAIT_MILLIS).times( - numBroadcastsSent)).sendBroadcastAsUser(mIntentArgument.capture(), - eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING, + verify(mHeadsetService, timeout(CONNECT_TIMEOUT_TEST_WAIT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } @@ -306,40 +346,56 @@ public class HeadsetStateMachineTest { public void testStateTransition_ConnectingToConnected_StackSlcConnected() { int numBroadcastsSent = setUpConnectingState(); // Indicate connecting to test state machine - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_CONNECTING, mTestDevice)); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_CONNECTING, + mTestDevice)); // Should do nothing - verify(mHeadsetService, - after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - any(Intent.class), any(UserHandle.class), anyString(), any(Bundle.class)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + any(Intent.class), any(UserHandle.class), anyString(), any(Bundle.class)); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connecting.class)); // Indicate RFCOMM connection is successful to test state machine - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_CONNECTED, mTestDevice)); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_CONNECTED, + mTestDevice)); // Should do nothing - verify(mHeadsetService, - after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - any(Intent.class), any(UserHandle.class), anyString(), any(Bundle.class)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + any(Intent.class), any(UserHandle.class), anyString(), any(Bundle.class)); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connecting.class)); // Indicate SLC connection is successful to test state machine numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_CONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connected.class)); } @@ -352,37 +408,49 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpDisconnectingState(); // Send StackEvent.DISCONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_DISCONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } /** - * Test state transition from Disconnecting to Disconnected state via CONNECT_TIMEOUT - * message + * Test state transition from Disconnecting to Disconnected state via CONNECT_TIMEOUT message */ @Test public void testStateTransition_DisconnectingToDisconnected_Timeout() { int numBroadcastsSent = setUpDisconnectingState(); // Let the connection timeout numBroadcastsSent++; - verify(mHeadsetService, timeout(CONNECT_TIMEOUT_TEST_WAIT_MILLIS).times( - numBroadcastsSent)).sendBroadcastAsUser(mIntentArgument.capture(), - eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTING, + verify(mHeadsetService, timeout(CONNECT_TIMEOUT_TEST_WAIT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_DISCONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } @@ -395,37 +463,48 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpDisconnectingState(); // Send StackEvent.SLC_CONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_DISCONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connected.class)); } - /** - * Test state transition from Connected to Disconnecting state via DISCONNECT message - */ + /** Test state transition from Connected to Disconnecting state via DISCONNECT message */ @Test public void testStateTransition_ConnectedToDisconnecting_Disconnect() { int numBroadcastsSent = setUpConnectedState(); // Send DISCONNECT message numBroadcastsSent++; mHeadsetStateMachine.sendMessage(HeadsetStateMachine.DISCONNECT, mTestDevice); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED, + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTING, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnecting.class)); } @@ -438,17 +517,25 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpConnectedState(); // Send StackEvent.DISCONNECTING message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTING, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnecting.class)); } @@ -461,60 +548,79 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpConnectedState(); // Send StackEvent.DISCONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } - /** - * Test state transition from Connected to AudioConnecting state via CONNECT_AUDIO message - */ + /** Test state transition from Connected to AudioConnecting state via CONNECT_AUDIO message */ @Test public void testStateTransition_ConnectedToAudioConnecting_ConnectAudio() { int numBroadcastsSent = setUpConnectedState(); // Send CONNECT_AUDIO message numBroadcastsSent++; mHeadsetStateMachine.sendMessage(HeadsetStateMachine.CONNECT_AUDIO, mTestDevice); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_CONNECTING, BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_CONNECTING, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioConnecting.class)); } /** - * Test state transition from Connected to AudioConnecting state via - * StackEvent.AUDIO_CONNECTING message + * Test state transition from Connected to AudioConnecting state via StackEvent.AUDIO_CONNECTING + * message */ @Test public void testStateTransition_ConnectedToAudioConnecting_StackAudioConnecting() { int numBroadcastsSent = setUpConnectedState(); // Send StackEvent.AUDIO_CONNECTING message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_CONNECTING, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_CONNECTING, BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_CONNECTING, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_CONNECTING, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioConnecting.class)); } @@ -526,36 +632,47 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpConnectedState(); // Send StackEvent.AUDIO_CONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_CONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_CONNECTED, BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_CONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_CONNECTED, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioOn.class)); } - /** - * Test state transition from AudioConnecting to Connected state via CONNECT_TIMEOUT message - */ + /** Test state transition from AudioConnecting to Connected state via CONNECT_TIMEOUT message */ @Test public void testStateTransition_AudioConnectingToConnected_Timeout() { int numBroadcastsSent = setUpAudioConnectingState(); // Wait for connection to timeout numBroadcastsSent++; - verify(mHeadsetService, timeout(CONNECT_TIMEOUT_TEST_WAIT_MILLIS).times( - numBroadcastsSent)).sendBroadcastAsUser(mIntentArgument.capture(), - eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTING, + verify(mHeadsetService, timeout(CONNECT_TIMEOUT_TEST_WAIT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connected.class)); } @@ -568,43 +685,61 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpAudioConnectingState(); // Send StackEvent.AUDIO_DISCONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_DISCONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_DISCONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connected.class)); } /** - * Test state transition from AudioConnecting to Disconnected state via - * StackEvent.DISCONNECTED message + * Test state transition from AudioConnecting to Disconnected state via StackEvent.DISCONNECTED + * message */ @Test public void testStateTransition_AudioConnectingToDisconnected_StackDisconnected() { int numBroadcastsSent = setUpAudioConnectingState(); // Send StackEvent.DISCONNECTED message numBroadcastsSent += 2; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTING, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED, + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } @@ -617,43 +752,61 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpAudioConnectingState(); // Send StackEvent.DISCONNECTED message numBroadcastsSent += 2; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTING, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED, + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTING, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnecting.class)); } /** - * Test state transition from AudioConnecting to AudioOn state via - * StackEvent.AUDIO_CONNECTED message + * Test state transition from AudioConnecting to AudioOn state via StackEvent.AUDIO_CONNECTED + * message */ @Test public void testStateTransition_AudioConnectingToAudioOn_StackAudioConnected() { int numBroadcastsSent = setUpAudioConnectingState(); // Send StackEvent.AUDIO_DISCONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_CONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_CONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_CONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_CONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioOn.class)); } @@ -665,20 +818,25 @@ public class HeadsetStateMachineTest { public void testStateTransition_AudioOnToAudioDisconnecting_StackAudioDisconnecting() { int numBroadcastsSent = setUpAudioOnState(); // Send StackEvent.AUDIO_DISCONNECTING message - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_DISCONNECTING, mTestDevice)); - verify(mHeadsetService, - after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - any(Intent.class), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_DISCONNECTING, + mTestDevice)); + verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + any(Intent.class), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioDisconnecting.class)); } /** - * Test state transition from AudioOn to AudioDisconnecting state via - * DISCONNECT_AUDIO message + * Test state transition from AudioOn to AudioDisconnecting state via DISCONNECT_AUDIO message */ @Test public void testStateTransition_AudioOnToAudioDisconnecting_DisconnectAudio() { @@ -686,86 +844,111 @@ public class HeadsetStateMachineTest { // Send DISCONNECT_AUDIO message mHeadsetStateMachine.sendMessage(HeadsetStateMachine.DISCONNECT_AUDIO, mTestDevice); // Should not sent any broadcast due to lack of AUDIO_DISCONNECTING intent value - verify(mHeadsetService, - after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - any(Intent.class), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + any(Intent.class), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioDisconnecting.class)); } /** - * Test state transition from AudioOn to AudioDisconnecting state via - * Stack.AUDIO_DISCONNECTED message + * Test state transition from AudioOn to AudioDisconnecting state via Stack.AUDIO_DISCONNECTED + * message */ @Test public void testStateTransition_AudioOnToConnected_StackAudioDisconnected() { int numBroadcastsSent = setUpAudioOnState(); // Send DISCONNECT_AUDIO message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_DISCONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_DISCONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connected.class)); } - /** - * Test state transition from AudioOn to Disconnected state via - * Stack.DISCONNECTED message - */ + /** Test state transition from AudioOn to Disconnected state via Stack.DISCONNECTED message */ @Test public void testStateTransition_AudioOnToDisconnected_StackDisconnected() { int numBroadcastsSent = setUpAudioOnState(); // Send StackEvent.DISCONNECTED message numBroadcastsSent += 2; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED, + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } - /** - * Test state transition from AudioOn to Disconnecting state via - * Stack.DISCONNECTING message - */ + /** Test state transition from AudioOn to Disconnecting state via Stack.DISCONNECTING message */ @Test public void testStateTransition_AudioOnToDisconnecting_StackDisconnecting() { int numBroadcastsSent = setUpAudioOnState(); // Send StackEvent.DISCONNECTING message numBroadcastsSent += 2; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED, + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTING, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnecting.class)); } @@ -782,11 +965,14 @@ public class HeadsetStateMachineTest { if (i > 0) { // Skip first AUDIO_DISCONNECTING init as it was setup before the loop mHeadsetStateMachine.sendMessage(HeadsetStateMachine.DISCONNECT_AUDIO, mTestDevice); // No new broadcast due to lack of AUDIO_DISCONNECTING intent variable - verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS) - .times(numBroadcastsSent)).sendBroadcastAsUser( - any(Intent.class), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + any(Intent.class), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioDisconnecting.class)); if (i == MAX_RETRY_DISCONNECT_AUDIO) { // Increment twice numBroadcastsSent as DISCONNECT message is added on max retry @@ -795,122 +981,167 @@ public class HeadsetStateMachineTest { numBroadcastsSent++; } } - verify(mHeadsetService, timeout(CONNECT_TIMEOUT_TEST_WAIT_MILLIS).times( - numBroadcastsSent)).sendBroadcastAsUser(mIntentArgument.capture(), - eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify( + mHeadsetService, + timeout(CONNECT_TIMEOUT_TEST_WAIT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); if (i < MAX_RETRY_DISCONNECT_AUDIO) { // Test if state is AudioOn before max retry - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, BluetoothHeadset.STATE_AUDIO_CONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioOn.class)); } else { // Max retry count reached, test Disconnecting state - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, BluetoothHeadset.STATE_DISCONNECTING, BluetoothHeadset.STATE_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnecting.class)); } } } /** - * Test state transition from AudioDisconnecting to Connected state via - * Stack.AUDIO_DISCONNECTED message + * Test state transition from AudioDisconnecting to Connected state via Stack.AUDIO_DISCONNECTED + * message */ @Test public void testStateTransition_AudioDisconnectingToConnected_StackAudioDisconnected() { int numBroadcastsSent = setUpAudioDisconnectingState(); // Send Stack.AUDIO_DISCONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_DISCONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_DISCONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connected.class)); } /** - * Test state transition from AudioDisconnecting to AudioOn state via - * Stack.AUDIO_CONNECTED message + * Test state transition from AudioDisconnecting to AudioOn state via Stack.AUDIO_CONNECTED + * message */ @Test public void testStateTransition_AudioDisconnectingToAudioOn_StackAudioConnected() { int numBroadcastsSent = setUpAudioDisconnectingState(); // Send Stack.AUDIO_CONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_CONNECTED, mTestDevice)); - verify(mHeadsetService, - after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_CONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_CONNECTED, + mTestDevice)); + verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_CONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioOn.class)); } /** - * Test state transition from AudioDisconnecting to Disconnecting state via - * Stack.DISCONNECTING message + * Test state transition from AudioDisconnecting to Disconnecting state via Stack.DISCONNECTING + * message */ @Test public void testStateTransition_AudioDisconnectingToDisconnecting_StackDisconnecting() { int numBroadcastsSent = setUpAudioDisconnectingState(); // Send StackEvent.DISCONNECTING message numBroadcastsSent += 2; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED, + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTING, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnecting.class)); } /** - * Test state transition from AudioDisconnecting to Disconnecting state via - * Stack.DISCONNECTED message + * Test state transition from AudioDisconnecting to Disconnecting state via Stack.DISCONNECTED + * message */ @Test public void testStateTransition_AudioDisconnectingToDisconnected_StackDisconnected() { int numBroadcastsSent = setUpAudioDisconnectingState(); // Send StackEvent.DISCONNECTED message numBroadcastsSent += 2; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_DISCONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_DISCONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED, + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnected.class)); } @@ -921,28 +1152,38 @@ public class HeadsetStateMachineTest { @Test public void testAtBiaEvent_initialSubscriptionWithUpdates() { setUpConnectedState(); - verify(mPhoneState).listenForPhoneState(mTestDevice, PhoneStateListener.LISTEN_SERVICE_STATE - | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_BIA, - new HeadsetAgIndicatorEnableState(true, true, false, false), mTestDevice)); - verify(mPhoneState, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).listenForPhoneState(mTestDevice, - PhoneStateListener.LISTEN_SERVICE_STATE); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_BIA, - new HeadsetAgIndicatorEnableState(false, true, true, false), mTestDevice)); - verify(mPhoneState, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).listenForPhoneState(mTestDevice, - PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_BIA, - new HeadsetAgIndicatorEnableState(false, true, false, false), mTestDevice)); - verify(mPhoneState, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).listenForPhoneState(mTestDevice, - PhoneStateListener.LISTEN_NONE); + verify(mPhoneState) + .listenForPhoneState( + mTestDevice, + PhoneStateListener.LISTEN_SERVICE_STATE + | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_BIA, + new HeadsetAgIndicatorEnableState(true, true, false, false), + mTestDevice)); + verify(mPhoneState, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .listenForPhoneState(mTestDevice, PhoneStateListener.LISTEN_SERVICE_STATE); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_BIA, + new HeadsetAgIndicatorEnableState(false, true, true, false), + mTestDevice)); + verify(mPhoneState, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .listenForPhoneState(mTestDevice, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_BIA, + new HeadsetAgIndicatorEnableState(false, true, false, false), + mTestDevice)); + verify(mPhoneState, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .listenForPhoneState(mTestDevice, PhoneStateListener.LISTEN_NONE); } - /** - * A test to verify that we correctly handles key pressed event from a HSP headset - */ + /** A test to verify that we correctly handles key pressed event from a HSP headset */ @Test public void testKeyPressedEventWhenIdleAndAudioOff_dialCall() { setUpConnectedState(); @@ -952,70 +1193,75 @@ public class HeadsetStateMachineTest { int magicNumber = 42; when(cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER)).thenReturn(magicNumber); when(cursor.getString(magicNumber)).thenReturn(TEST_PHONE_NUMBER); - MockContentProvider mockContentProvider = new MockContentProvider() { - @Override - public Cursor query(Uri uri, String[] projection, Bundle queryArgs, - CancellationSignal cancellationSignal) { - if (uri == null || !uri.equals(CallLog.Calls.CONTENT_URI)) { - return null; - } - if (projection == null || (projection.length == 0) || !projection[0].equals( - CallLog.Calls.NUMBER)) { - return null; - } - if (queryArgs == null - || !queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION).equals( - Calls.TYPE + "=" + Calls.OUTGOING_TYPE) - || !queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER).equals( - Calls.DEFAULT_SORT_ORDER) - || queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT) != 1) { - return null; - } - if (cancellationSignal != null) { - return null; - } - return cursor; - } - }; + MockContentProvider mockContentProvider = + new MockContentProvider() { + @Override + public Cursor query( + Uri uri, + String[] projection, + Bundle queryArgs, + CancellationSignal cancellationSignal) { + if (uri == null || !uri.equals(CallLog.Calls.CONTENT_URI)) { + return null; + } + if (projection == null + || (projection.length == 0) + || !projection[0].equals(CallLog.Calls.NUMBER)) { + return null; + } + if (queryArgs == null + || !queryArgs + .getString(ContentResolver.QUERY_ARG_SQL_SELECTION) + .equals(Calls.TYPE + "=" + Calls.OUTGOING_TYPE) + || !queryArgs + .getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER) + .equals(Calls.DEFAULT_SORT_ORDER) + || queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT) != 1) { + return null; + } + if (cancellationSignal != null) { + return null; + } + return cursor; + } + }; mMockContentResolver.addProvider(CallLog.AUTHORITY, mockContentProvider); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_KEY_PRESSED, mTestDevice)); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).dialOutgoingCall(mTestDevice, - TEST_PHONE_NUMBER); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .dialOutgoingCall(mTestDevice, TEST_PHONE_NUMBER); } - /** - * A test to verify that we correctly handles key pressed event from a HSP headset - */ + /** A test to verify that we correctly handles key pressed event from a HSP headset */ @Test public void testKeyPressedEventDuringRinging_answerCall() { setUpConnectedState(); when(mSystemInterface.isRinging()).thenReturn(true); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_KEY_PRESSED, mTestDevice)); verify(mSystemInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).answerCall(mTestDevice); } - /** - * A test to verify that we correctly handles key pressed event from a HSP headset - */ + /** A test to verify that we correctly handles key pressed event from a HSP headset */ @Test public void testKeyPressedEventInCallButAudioOff_setActiveDevice() { setUpConnectedState(); when(mSystemInterface.isInCall()).thenReturn(true); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_KEY_PRESSED, mTestDevice)); verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).setActiveDevice(mTestDevice); } - /** - * A test to verify that we correctly handles key pressed event from a HSP headset - */ + /** A test to verify that we correctly handles key pressed event from a HSP headset */ @Test public void testKeyPressedEventInCallAndAudioOn_hangupCall() { setUpAudioOnState(); when(mSystemInterface.isInCall()).thenReturn(true); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_KEY_PRESSED, mTestDevice)); verify(mSystemInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).hangupCall(mTestDevice); } @@ -1060,111 +1306,119 @@ public class HeadsetStateMachineTest { } } - /** - * A test to verify that we correctly handles key pressed event from a HSP headset - */ + /** A test to verify that we correctly handles key pressed event from a HSP headset */ @Test public void testKeyPressedEventWhenIdleAndAudioOn_disconnectAudio() { setUpAudioOnState(); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_KEY_PRESSED, mTestDevice)); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).disconnectAudio(mTestDevice); } - /** - * A test to verfiy that we correctly handles AT+BIND event with driver safety case from HF - */ + /** A test to verfiy that we correctly handles AT+BIND event with driver safety case from HF */ @Test public void testAtBindWithDriverSafetyEventWhenConnecting() { setUpConnectingState(); String atString = "1"; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_BIND, atString, mTestDevice)); ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcast( - intentArgument.capture(), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - verify(mHeadsetService, times(1)).sendBroadcast(any(), any(), - any()); - Assert.assertEquals(mTestDevice, intentArgument.getValue().getExtra( - BluetoothDevice.EXTRA_DEVICE, null)); - Assert.assertEquals(HeadsetHalConstants.HF_INDICATOR_ENHANCED_DRIVER_SAFETY, - intentArgument.getValue().getIntExtra( - BluetoothHeadset.EXTRA_HF_INDICATORS_IND_ID, -1)); - Assert.assertEquals(-1, intentArgument.getValue().getIntExtra( - BluetoothHeadset.EXTRA_HF_INDICATORS_IND_VALUE, -2)); - } - - /** - * A test to verfiy that we correctly handles AT+BIND event with battery level case from HF - */ + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcast(intentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify(mHeadsetService, times(1)).sendBroadcast(any(), any(), any()); + Assert.assertEquals( + mTestDevice, + intentArgument.getValue().getExtra(BluetoothDevice.EXTRA_DEVICE, null)); + Assert.assertEquals( + HeadsetHalConstants.HF_INDICATOR_ENHANCED_DRIVER_SAFETY, + intentArgument + .getValue() + .getIntExtra(BluetoothHeadset.EXTRA_HF_INDICATORS_IND_ID, -1)); + Assert.assertEquals( + -1, + intentArgument + .getValue() + .getIntExtra(BluetoothHeadset.EXTRA_HF_INDICATORS_IND_VALUE, -2)); + } + + /** A test to verfiy that we correctly handles AT+BIND event with battery level case from HF */ @Test public void testAtBindEventWithBatteryLevelEventWhenConnecting() { setUpConnectingState(); String atString = "2"; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_BIND, atString, mTestDevice)); ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcast( - intentArgument.capture(), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - verify(mHeadsetService, times(1)).sendBroadcast(any(), any(), - any()); - Assert.assertEquals(mTestDevice, intentArgument.getValue().getExtra( - BluetoothDevice.EXTRA_DEVICE, null)); - Assert.assertEquals(HeadsetHalConstants.HF_INDICATOR_BATTERY_LEVEL_STATUS, - intentArgument.getValue().getIntExtra( - BluetoothHeadset.EXTRA_HF_INDICATORS_IND_ID, -1)); - Assert.assertEquals(-1, intentArgument.getValue().getIntExtra( - BluetoothHeadset.EXTRA_HF_INDICATORS_IND_VALUE, -2)); - } - - /** - * A test to verfiy that we correctly handles AT+BIND event with error case from HF - */ + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcast(intentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify(mHeadsetService, times(1)).sendBroadcast(any(), any(), any()); + Assert.assertEquals( + mTestDevice, + intentArgument.getValue().getExtra(BluetoothDevice.EXTRA_DEVICE, null)); + Assert.assertEquals( + HeadsetHalConstants.HF_INDICATOR_BATTERY_LEVEL_STATUS, + intentArgument + .getValue() + .getIntExtra(BluetoothHeadset.EXTRA_HF_INDICATORS_IND_ID, -1)); + Assert.assertEquals( + -1, + intentArgument + .getValue() + .getIntExtra(BluetoothHeadset.EXTRA_HF_INDICATORS_IND_VALUE, -2)); + } + + /** A test to verfiy that we correctly handles AT+BIND event with error case from HF */ @Test public void testAtBindEventWithErrorEventWhenConnecting() { setUpConnectingState(); String atString = "err,A,123,,1"; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_BIND, atString, mTestDevice)); ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcast( - intentArgument.capture(), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - verify(mHeadsetService, times(1)).sendBroadcast(any(), any(), - any()); - Assert.assertEquals(mTestDevice, intentArgument.getValue().getExtra( - BluetoothDevice.EXTRA_DEVICE, null)); - Assert.assertEquals(HeadsetHalConstants.HF_INDICATOR_ENHANCED_DRIVER_SAFETY, - intentArgument.getValue().getIntExtra( - BluetoothHeadset.EXTRA_HF_INDICATORS_IND_ID, -1)); - Assert.assertEquals(-1, intentArgument.getValue().getIntExtra( - BluetoothHeadset.EXTRA_HF_INDICATORS_IND_VALUE, -2)); - } - - /** - * A test to verify that we correctly set AG indicator mask when enter/exit silence mode - */ + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcast(intentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify(mHeadsetService, times(1)).sendBroadcast(any(), any(), any()); + Assert.assertEquals( + mTestDevice, + intentArgument.getValue().getExtra(BluetoothDevice.EXTRA_DEVICE, null)); + Assert.assertEquals( + HeadsetHalConstants.HF_INDICATOR_ENHANCED_DRIVER_SAFETY, + intentArgument + .getValue() + .getIntExtra(BluetoothHeadset.EXTRA_HF_INDICATORS_IND_ID, -1)); + Assert.assertEquals( + -1, + intentArgument + .getValue() + .getIntExtra(BluetoothHeadset.EXTRA_HF_INDICATORS_IND_VALUE, -2)); + } + + /** A test to verify that we correctly set AG indicator mask when enter/exit silence mode */ @Test public void testSetSilenceDevice() { doNothing().when(mPhoneState).listenForPhoneState(any(BluetoothDevice.class), anyInt()); mHeadsetStateMachine.setSilenceDevice(true); mHeadsetStateMachine.setSilenceDevice(false); - verify(mPhoneState, times(2)).listenForPhoneState(mTestDevice, - PhoneStateListener.LISTEN_NONE); + verify(mPhoneState, times(2)) + .listenForPhoneState(mTestDevice, PhoneStateListener.LISTEN_NONE); } @Test public void testBroadcastVendorSpecificEventIntent() { - mHeadsetStateMachine.broadcastVendorSpecificEventIntent( - "command", 1, 1, null, mTestDevice); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); + mHeadsetStateMachine.broadcastVendorSpecificEventIntent("command", 1, 1, null, mTestDevice); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); } @Test @@ -1207,19 +1461,19 @@ public class HeadsetStateMachineTest { @Test public void testGetAtCommandType() { String atCommand = "start?"; - Assert.assertEquals(mHeadsetStateMachine.getAtCommandType(atCommand), - AtPhonebook.TYPE_READ); + Assert.assertEquals( + mHeadsetStateMachine.getAtCommandType(atCommand), AtPhonebook.TYPE_READ); atCommand = "start=?"; - Assert.assertEquals(mHeadsetStateMachine.getAtCommandType(atCommand), - AtPhonebook.TYPE_TEST); + Assert.assertEquals( + mHeadsetStateMachine.getAtCommandType(atCommand), AtPhonebook.TYPE_TEST); atCommand = "start=comm"; Assert.assertEquals(mHeadsetStateMachine.getAtCommandType(atCommand), AtPhonebook.TYPE_SET); atCommand = "start!"; - Assert.assertEquals(mHeadsetStateMachine.getAtCommandType(atCommand), - AtPhonebook.TYPE_UNKNOWN); + Assert.assertEquals( + mHeadsetStateMachine.getAtCommandType(atCommand), AtPhonebook.TYPE_UNKNOWN); } @Test @@ -1248,8 +1502,9 @@ public class HeadsetStateMachineTest { public void testHandleAccessPermissionResult_withNoChangeInAtCommandResult() { when(mIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)).thenReturn(null); when(mIntent.getAction()).thenReturn(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY); - when(mIntent.getIntExtra(BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT, - BluetoothDevice.CONNECTION_ACCESS_NO)) + when(mIntent.getIntExtra( + BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT, + BluetoothDevice.CONNECTION_ACCESS_NO)) .thenReturn(BluetoothDevice.CONNECTION_ACCESS_NO); when(mIntent.getBooleanExtra(BluetoothDevice.EXTRA_ALWAYS_ALLOWED, false)).thenReturn(true); mHeadsetStateMachine.mPhonebook.setCheckingAccessPermission(true); @@ -1263,8 +1518,8 @@ public class HeadsetStateMachineTest { public void testProcessAtBievCommand() { mHeadsetStateMachine.processAtBiev(1, 1, mTestDevice); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcast( - mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcast(mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); } @Test @@ -1284,8 +1539,8 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.processAtChld(chld, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - 0); + verify(mNativeInterface) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, 0); } @Test @@ -1331,8 +1586,11 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.processAtCpbr(atString, type, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.TEXT_HAS_INVALID_CHARS); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.TEXT_HAS_INVALID_CHARS); } @Test @@ -1342,8 +1600,11 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.processAtCpbs(atString, type, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.OPERATION_NOT_ALLOWED); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.OPERATION_NOT_ALLOWED); } @Test @@ -1353,8 +1614,8 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.processAtCscs(atString, type, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, - -1); + verify(mNativeInterface) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, -1); } @Test @@ -1370,8 +1631,8 @@ public class HeadsetStateMachineTest { @Test public void testProcessSendVendorSpecificResultCode() { - HeadsetVendorSpecificResultCode resultCode = new HeadsetVendorSpecificResultCode( - mTestDevice, "command", "arg"); + HeadsetVendorSpecificResultCode resultCode = + new HeadsetVendorSpecificResultCode(mTestDevice, "command", "arg"); mHeadsetStateMachine.processSendVendorSpecificResultCode(resultCode); @@ -1394,8 +1655,14 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.processSubscriberNumberRequest(mTestDevice); - verify(mNativeInterface).atResponseString(mTestDevice, - "+CNUM: ,\"" + number + "\"," + PhoneNumberUtils.toaFromString(number) + ",,4"); + verify(mNativeInterface) + .atResponseString( + mTestDevice, + "+CNUM: ,\"" + + number + + "\"," + + PhoneNumberUtils.toaFromString(number) + + ",,4"); verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, 0); } @@ -1403,24 +1670,33 @@ public class HeadsetStateMachineTest { public void testProcessUnknownAt() { String atString = "+CSCS=invalid"; mHeadsetStateMachine.processUnknownAt(atString, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.OPERATION_NOT_SUPPORTED); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.OPERATION_NOT_SUPPORTED); Mockito.clearInvocations(mNativeInterface); atString = "+CPBS="; mHeadsetStateMachine.processUnknownAt(atString, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.OPERATION_NOT_SUPPORTED); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.OPERATION_NOT_SUPPORTED); atString = "+CPBR=ERR"; mHeadsetStateMachine.processUnknownAt(atString, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - BluetoothCmeError.TEXT_HAS_INVALID_CHARS); + verify(mNativeInterface) + .atResponseCode( + mTestDevice, + HeadsetHalConstants.AT_RESPONSE_ERROR, + BluetoothCmeError.TEXT_HAS_INVALID_CHARS); atString = "inval="; mHeadsetStateMachine.processUnknownAt(atString, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - 0); + verify(mNativeInterface) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, 0); } @Test @@ -1429,8 +1705,8 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.processVendorSpecificAt(atString, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - 0); + verify(mNativeInterface) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, 0); } @Test @@ -1439,8 +1715,8 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.processVendorSpecificAt(atString, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - 0); + verify(mNativeInterface) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, 0); } @Test @@ -1449,8 +1725,8 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.processVendorSpecificAt(atString, mTestDevice); - verify(mNativeInterface).atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, - 0); + verify(mNativeInterface) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, 0); } @Test @@ -1535,28 +1811,28 @@ public class HeadsetStateMachineTest { mHeadsetStateMachine.dump(sb); } - /** - * A test to validate received Android AT commands and processing - */ + /** A test to validate received Android AT commands and processing */ @Test public void testCheckAndProcessAndroidAt() { // Commands that will be handled int counter_ok = 0; int counter_error = 0; - Assert.assertTrue(mHeadsetStateMachine.checkAndProcessAndroidAt( - "+ANDROID=?" , mTestDevice)); + Assert.assertTrue(mHeadsetStateMachine.checkAndProcessAndroidAt("+ANDROID=?", mTestDevice)); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(++counter_ok)) .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, 0); - Assert.assertTrue(mHeadsetStateMachine.checkAndProcessAndroidAt( - "+ANDROID=SINKAUDIOPOLICY,1,1,1" , mTestDevice)); + Assert.assertTrue( + mHeadsetStateMachine.checkAndProcessAndroidAt( + "+ANDROID=SINKAUDIOPOLICY,1,1,1", mTestDevice)); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(++counter_ok)) .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, 0); - Assert.assertTrue(mHeadsetStateMachine.checkAndProcessAndroidAt( - "+ANDROID=SINKAUDIOPOLICY,100,100,100" , mTestDevice)); + Assert.assertTrue( + mHeadsetStateMachine.checkAndProcessAndroidAt( + "+ANDROID=SINKAUDIOPOLICY,100,100,100", mTestDevice)); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(++counter_ok)) .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, 0); - Assert.assertTrue(mHeadsetStateMachine.checkAndProcessAndroidAt( - "+ANDROID=SINKAUDIOPOLICY,1,2,3,4,5" , mTestDevice)); + Assert.assertTrue( + mHeadsetStateMachine.checkAndProcessAndroidAt( + "+ANDROID=SINKAUDIOPOLICY,1,2,3,4,5", mTestDevice)); verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(++counter_error)) .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, 0); Assert.assertTrue(mHeadsetStateMachine.checkAndProcessAndroidAt("+ANDROID=1", mTestDevice)); @@ -1577,18 +1853,20 @@ public class HeadsetStateMachineTest { .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_ERROR, 0); // Commands with correct format but will not be handled - Assert.assertFalse(mHeadsetStateMachine.checkAndProcessAndroidAt( - "+ANDROID=" , mTestDevice)); - Assert.assertFalse(mHeadsetStateMachine.checkAndProcessAndroidAt( - "+ANDROID: PROBE,1,\"`AB\"" , mTestDevice)); - Assert.assertFalse(mHeadsetStateMachine.checkAndProcessAndroidAt( - "+ANDROID= PROBE,1,\"`AB\"" , mTestDevice)); - Assert.assertFalse(mHeadsetStateMachine.checkAndProcessAndroidAt( - "AT+ANDROID=PROBE,1,1,\"PQGHRSBCTU__\"" , mTestDevice)); + Assert.assertFalse(mHeadsetStateMachine.checkAndProcessAndroidAt("+ANDROID=", mTestDevice)); + Assert.assertFalse( + mHeadsetStateMachine.checkAndProcessAndroidAt( + "+ANDROID: PROBE,1,\"`AB\"", mTestDevice)); + Assert.assertFalse( + mHeadsetStateMachine.checkAndProcessAndroidAt( + "+ANDROID= PROBE,1,\"`AB\"", mTestDevice)); + Assert.assertFalse( + mHeadsetStateMachine.checkAndProcessAndroidAt( + "AT+ANDROID=PROBE,1,1,\"PQGHRSBCTU__\"", mTestDevice)); // Incorrect format AT command - Assert.assertFalse(mHeadsetStateMachine.checkAndProcessAndroidAt( - "RANDOM FORMAT" , mTestDevice)); + Assert.assertFalse( + mHeadsetStateMachine.checkAndProcessAndroidAt("RANDOM FORMAT", mTestDevice)); // Check no any AT result was sent for the failed ones verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(counter_ok)) @@ -1600,17 +1878,14 @@ public class HeadsetStateMachineTest { @Test public void testCheckAndProcessAndroidAt_replyAndroidAtFeatureRequest() { // Commands that will be handled - Assert.assertTrue(mHeadsetStateMachine.checkAndProcessAndroidAt( - "+ANDROID=?" , mTestDevice)); - verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).atResponseString( - mTestDevice, "+ANDROID: (SINKAUDIOPOLICY)"); - verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).atResponseCode( - mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, 0); + Assert.assertTrue(mHeadsetStateMachine.checkAndProcessAndroidAt("+ANDROID=?", mTestDevice)); + verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .atResponseString(mTestDevice, "+ANDROID: (SINKAUDIOPOLICY)"); + verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .atResponseCode(mTestDevice, HeadsetHalConstants.AT_RESPONSE_OK, 0); } - /** - * A end to end test to validate received Android AT commands and processing - */ + /** A end to end test to validate received Android AT commands and processing */ @Test public void testCehckAndProcessAndroidAtFromStateMachine() { // setAudioPolicyMetadata is invoked in HeadsetStateMachine.init() so start from 1 @@ -1621,24 +1896,28 @@ public class HeadsetStateMachineTest { setUpAudioPolicy(); // receive and set android policy - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_UNKNOWN_AT, - "+ANDROID=SINKAUDIOPOLICY,1,1,1", mTestDevice)); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_UNKNOWN_AT, + "+ANDROID=SINKAUDIOPOLICY,1,1,1", + mTestDevice)); expectCallTimes++; verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(expectCallTimes)) .setAudioPolicyMetadata(anyObject(), anyObject()); // receive and not set android policy - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_UNKNOWN_AT, - "AT+ANDROID=PROBE,1,1,\"PQGHRSBCTU__\"", mTestDevice)); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_UNKNOWN_AT, + "AT+ANDROID=PROBE,1,1,\"PQGHRSBCTU__\"", + mTestDevice)); verify(mDatabaseManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(expectCallTimes)) .setAudioPolicyMetadata(anyObject(), anyObject()); } - /** - * A test to verify whether the sink audio policy command is valid - */ + /** A test to verify whether the sink audio policy command is valid */ @Test public void testProcessAndroidAtSinkAudioPolicy() { // expected format @@ -1772,6 +2051,7 @@ public class HeadsetStateMachineTest { /** * set sink audio policy + * * @param arg body of the AT command * @return the result from processAndroidAtSinkAudioPolicy */ @@ -1782,49 +2062,75 @@ public class HeadsetStateMachineTest { /** * Setup Connecting State + * * @return number of times mHeadsetService.sendBroadcastAsUser() has been invoked */ private int setUpConnectingState() { // Put test state machine in connecting state mHeadsetStateMachine.sendMessage(HeadsetStateMachine.CONNECT, mTestDevice); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED, + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connecting.class)); return 1; } /** * Setup Connected State + * * @return number of times mHeadsetService.sendBroadcastAsUser() has been invoked */ private int setUpConnectedState() { // Put test state machine into connected state - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_CONNECTED, mTestDevice)); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_CONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connecting.class)); - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, - HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED, mTestDevice)); - verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED, + HeadsetHalConstants.CONNECTION_STATE_SLC_CONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_CONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Connected.class)); return 2; } @@ -1834,14 +2140,19 @@ public class HeadsetStateMachineTest { // Send CONNECT_AUDIO numBroadcastsSent++; mHeadsetStateMachine.sendMessage(HeadsetStateMachine.CONNECT_AUDIO, mTestDevice); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_CONNECTING, BluetoothHeadset.STATE_AUDIO_DISCONNECTED, + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_CONNECTING, + BluetoothHeadset.STATE_AUDIO_DISCONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioConnecting.class)); return numBroadcastsSent; } @@ -1850,17 +2161,25 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpAudioConnectingState(); // Send StackEvent.AUDIO_DISCONNECTED message numBroadcastsSent++; - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, - HeadsetHalConstants.AUDIO_STATE_CONNECTED, mTestDevice)); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyAudioStateBroadcast(mTestDevice, - BluetoothHeadset.STATE_AUDIO_CONNECTED, BluetoothHeadset.STATE_AUDIO_CONNECTING, + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED, + HeadsetHalConstants.AUDIO_STATE_CONNECTED, + mTestDevice)); + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyAudioStateBroadcast( + mTestDevice, + BluetoothHeadset.STATE_AUDIO_CONNECTED, + BluetoothHeadset.STATE_AUDIO_CONNECTING, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioOn.class)); return numBroadcastsSent; } @@ -1869,11 +2188,14 @@ public class HeadsetStateMachineTest { int numBroadcastsSent = setUpAudioOnState(); mHeadsetStateMachine.sendMessage(HeadsetStateMachine.DISCONNECT_AUDIO, mTestDevice); // No new broadcast due to lack of AUDIO_DISCONNECTING intent variable - verify(mHeadsetService, - after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - any(Intent.class), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + verify(mHeadsetService, after(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + any(Intent.class), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.AudioDisconnecting.class)); return numBroadcastsSent; } @@ -1883,24 +2205,30 @@ public class HeadsetStateMachineTest { // Send DISCONNECT message numBroadcastsSent++; mHeadsetStateMachine.sendMessage(HeadsetStateMachine.DISCONNECT, mTestDevice); - verify(mHeadsetService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)).sendBroadcastAsUser( - mIntentArgument.capture(), eq(UserHandle.ALL), eq(BLUETOOTH_CONNECT), - any(Bundle.class)); - HeadsetTestUtils.verifyConnectionStateBroadcast(mTestDevice, - BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED, + verify(mHeadsetService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(numBroadcastsSent)) + .sendBroadcastAsUser( + mIntentArgument.capture(), + eq(UserHandle.ALL), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + HeadsetTestUtils.verifyConnectionStateBroadcast( + mTestDevice, + BluetoothProfile.STATE_DISCONNECTING, + BluetoothProfile.STATE_CONNECTED, mIntentArgument.getValue()); - Assert.assertThat(mHeadsetStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetStateMachine.Disconnecting.class)); return numBroadcastsSent; } private void setUpAudioPolicy() { - mHeadsetStateMachine.sendMessage(HeadsetStateMachine.STACK_EVENT, - new HeadsetStackEvent(HeadsetStackEvent.EVENT_TYPE_UNKNOWN_AT, - "+ANDROID=?", mTestDevice)); - verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)).atResponseString( - anyObject(), anyString()); + mHeadsetStateMachine.sendMessage( + HeadsetStateMachine.STACK_EVENT, + new HeadsetStackEvent( + HeadsetStackEvent.EVENT_TYPE_UNKNOWN_AT, "+ANDROID=?", mTestDevice)); + verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS)) + .atResponseString(anyObject(), anyString()); } private void configureHeadsetServiceForAptxVoice(boolean enable) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetTestUtils.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetTestUtils.java index 4279afb0d3e..b8439fa8557 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetTestUtils.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetTestUtils.java @@ -25,9 +25,7 @@ import android.content.Intent; import org.junit.Assert; -/** - * Helper functions for HFP related tests - */ +/** Helper functions for HFP related tests */ public class HeadsetTestUtils { /** @@ -38,14 +36,14 @@ public class HeadsetTestUtils { * @param fromState value of {@link BluetoothProfile#EXTRA_PREVIOUS_STATE} * @param intent a {@link BluetoothHeadset#ACTION_AUDIO_STATE_CHANGED} intent */ - public static void verifyAudioStateBroadcast(BluetoothDevice device, int toState, int fromState, - Intent intent) { + public static void verifyAudioStateBroadcast( + BluetoothDevice device, int toState, int fromState, Intent intent) { Assert.assertNotNull(intent); Assert.assertEquals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED, intent.getAction()); Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); Assert.assertEquals(toState, intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertEquals(fromState, - intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)); + Assert.assertEquals( + fromState, intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)); } /** @@ -56,10 +54,10 @@ public class HeadsetTestUtils { * @param fromState value of {@link BluetoothProfile#EXTRA_PREVIOUS_STATE} * @param intent a {@link BluetoothHeadset#ACTION_CONNECTION_STATE_CHANGED} intent * @param checkFlag whether intent flag should be verified, normally this can only be done at - * the sender end + * the sender end */ - public static void verifyConnectionStateBroadcast(BluetoothDevice device, int toState, - int fromState, Intent intent, boolean checkFlag) { + public static void verifyConnectionStateBroadcast( + BluetoothDevice device, int toState, int fromState, Intent intent, boolean checkFlag) { Assert.assertNotNull(intent); Assert.assertEquals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED, intent.getAction()); if (checkFlag) { @@ -67,41 +65,43 @@ public class HeadsetTestUtils { } Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); Assert.assertEquals(toState, intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertEquals(fromState, - intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)); + Assert.assertEquals( + fromState, intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)); } /** - * Verify the content of a {@link BluetoothHeadset#ACTION_CONNECTION_STATE_CHANGED} intent - * and its flag, normally used at sender end + * Verify the content of a {@link BluetoothHeadset#ACTION_CONNECTION_STATE_CHANGED} intent and + * its flag, normally used at sender end * * @param device Bluetooth device * @param toState value of {@link BluetoothProfile#EXTRA_STATE} * @param fromState value of {@link BluetoothProfile#EXTRA_PREVIOUS_STATE} * @param intent a {@link BluetoothHeadset#ACTION_CONNECTION_STATE_CHANGED} intent */ - public static void verifyConnectionStateBroadcast(BluetoothDevice device, int toState, - int fromState, Intent intent) { + public static void verifyConnectionStateBroadcast( + BluetoothDevice device, int toState, int fromState, Intent intent) { verifyConnectionStateBroadcast(device, toState, fromState, intent, true); } /** - * Verify the content of a {@link BluetoothHeadset#ACTION_ACTIVE_DEVICE_CHANGED} intent - * and its flag, normally used at sender end + * Verify the content of a {@link BluetoothHeadset#ACTION_ACTIVE_DEVICE_CHANGED} intent and its + * flag, normally used at sender end * * @param device intended active Bluetooth device * @param intent a {@link BluetoothHeadset#ACTION_ACTIVE_DEVICE_CHANGED} intent * @param checkFlag whether intent flag should be verified, normally this can only be done at - * the sender end + * the sender end */ - public static void verifyActiveDeviceChangedBroadcast(BluetoothDevice device, Intent intent, - boolean checkFlag) { + public static void verifyActiveDeviceChangedBroadcast( + BluetoothDevice device, Intent intent, boolean checkFlag) { Assert.assertNotNull(intent); Assert.assertEquals(BluetoothHeadset.ACTION_ACTIVE_DEVICE_CHANGED, intent.getAction()); Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); if (checkFlag) { - Assert.assertEquals(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT - | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, intent.getFlags()); + Assert.assertEquals( + Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT + | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, + intent.getFlags()); } } @@ -113,13 +113,13 @@ public class HeadsetTestUtils { * @param headsetCallState intended headset call state * @param timeoutMs timeout for this check in asynchronous test conditions */ - public static void verifyPhoneStateChangeSetters(HeadsetPhoneState headsetPhoneState, - HeadsetCallState headsetCallState, int timeoutMs) { - verify(headsetPhoneState, timeout(timeoutMs).times(1)).setNumActiveCall( - headsetCallState.mNumActive); - verify(headsetPhoneState, timeout(timeoutMs).times(1)).setNumHeldCall( - headsetCallState.mNumHeld); - verify(headsetPhoneState, timeout(timeoutMs).times(1)).setCallState( - headsetCallState.mCallState); + public static void verifyPhoneStateChangeSetters( + HeadsetPhoneState headsetPhoneState, HeadsetCallState headsetCallState, int timeoutMs) { + verify(headsetPhoneState, timeout(timeoutMs).times(1)) + .setNumActiveCall(headsetCallState.mNumActive); + verify(headsetPhoneState, timeout(timeoutMs).times(1)) + .setNumHeldCall(headsetCallState.mNumHeld); + verify(headsetPhoneState, timeout(timeoutMs).times(1)) + .setCallState(headsetCallState.mCallState); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetVendorSpecificResultCodeTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetVendorSpecificResultCodeTest.java index 8d669e15456..3e5dc1d3ea1 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetVendorSpecificResultCodeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetVendorSpecificResultCodeTest.java @@ -45,8 +45,8 @@ public class HeadsetVendorSpecificResultCodeTest { @Test public void constructor() { - HeadsetVendorSpecificResultCode code = new HeadsetVendorSpecificResultCode(mTestDevice, - TEST_COMMAND, TEST_ARG); + HeadsetVendorSpecificResultCode code = + new HeadsetVendorSpecificResultCode(mTestDevice, TEST_COMMAND, TEST_ARG); assertThat(code.mDevice).isEqualTo(mTestDevice); assertThat(code.mCommand).isEqualTo(TEST_COMMAND); @@ -55,15 +55,21 @@ public class HeadsetVendorSpecificResultCodeTest { @Test public void buildString() { - HeadsetVendorSpecificResultCode code = new HeadsetVendorSpecificResultCode(mTestDevice, - TEST_COMMAND, TEST_ARG); + HeadsetVendorSpecificResultCode code = + new HeadsetVendorSpecificResultCode(mTestDevice, TEST_COMMAND, TEST_ARG); StringBuilder builder = new StringBuilder(); code.buildString(builder); String expectedString = - code.getClass().getSimpleName() + "[device=" + mTestDevice + ", command=" - + TEST_COMMAND + ", arg=" + TEST_ARG + "]"; + code.getClass().getSimpleName() + + "[device=" + + mTestDevice + + ", command=" + + TEST_COMMAND + + ", arg=" + + TEST_ARG + + "]"; assertThat(builder.toString()).isEqualTo(expectedString); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java index 57b7f9087c3..cb0121653b5 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java @@ -40,8 +40,7 @@ public class HeadsetClientServiceBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private HeadsetClientService mService; + @Mock private HeadsetClientService mService; BluetoothDevice mRemoteDevice; diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java index 65ef6b3985d..d059770d9e8 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java @@ -120,10 +120,7 @@ public class HeadsetClientServiceTest { // Expect send BIEV to state machine verify(mStateMachine, timeout(STANDARD_WAIT_MILLIS).times(1)) - .sendMessage( - eq(HeadsetClientStateMachine.SEND_BIEV), - eq(2), - anyInt()); + .sendMessage(eq(HeadsetClientStateMachine.SEND_BIEV), eq(2), anyInt()); } @Test @@ -141,10 +138,7 @@ public class HeadsetClientServiceTest { // Expect send BIEV to state machine verify(mStateMachine, timeout(STANDARD_WAIT_MILLIS).times(1)) - .sendMessage( - eq(HeadsetClientStateMachine.SEND_BIEV), - eq(2), - anyInt()); + .sendMessage(eq(HeadsetClientStateMachine.SEND_BIEV), eq(2), anyInt()); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java index ea38d2ea859..339a5bc6871 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java @@ -88,9 +88,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -/** - * Test cases for {@link HeadsetClientStateMachine}. - */ +/** Test cases for {@link HeadsetClientStateMachine}. */ @LargeTest @RunWith(AndroidJUnit4.class) public class HeadsetClientStateMachineTest { @@ -115,8 +113,8 @@ public class HeadsetClientStateMachineTest { private static final int STANDARD_WAIT_MILLIS = 1000; private static final int QUERY_CURRENT_CALLS_WAIT_MILLIS = 2000; - private static final int QUERY_CURRENT_CALLS_TEST_WAIT_MILLIS = QUERY_CURRENT_CALLS_WAIT_MILLIS - * 3 / 2; + private static final int QUERY_CURRENT_CALLS_TEST_WAIT_MILLIS = + QUERY_CURRENT_CALLS_WAIT_MILLIS * 3 / 2; private static final int TIMEOUT_MS = 1000; @Before @@ -127,8 +125,7 @@ public class HeadsetClientStateMachineTest { when(mAudioManager.getStreamVolume(anyInt())).thenReturn(2); when(mAudioManager.getStreamMaxVolume(anyInt())).thenReturn(10); when(mAudioManager.getStreamMinVolume(anyInt())).thenReturn(1); - when(mHeadsetClientService.getAudioManager()).thenReturn( - mAudioManager); + when(mHeadsetClientService.getAudioManager()).thenReturn(mAudioManager); when(mHeadsetClientService.getResources()).thenReturn(mMockHfpResources); when(mHeadsetClientService.getPackageManager()).thenReturn(mPackageManager); when(mPackageManager.hasSystemFeature(FEATURE_WATCH)).thenReturn(false); @@ -149,8 +146,12 @@ public class HeadsetClientStateMachineTest { mHandlerThread = new HandlerThread("HeadsetClientStateMachineTestHandlerThread"); mHandlerThread.start(); // Manage looper execution in main test thread explicitly to guarantee timing consistency - mHeadsetClientStateMachine = new TestHeadsetClientStateMachine(mHeadsetClientService, - mHeadsetService, mHandlerThread.getLooper(), mNativeInterface); + mHeadsetClientStateMachine = + new TestHeadsetClientStateMachine( + mHeadsetClientService, + mHeadsetService, + mHandlerThread.getLooper(), + mNativeInterface); mHeadsetClientStateMachine.start(); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); } @@ -255,25 +256,22 @@ public class HeadsetClientStateMachineTest { } } - /** - * Test that default state is disconnected - */ + /** Test that default state is disconnected */ @SmallTest @Test public void testDefaultDisconnectedState() { - Assert.assertEquals(mHeadsetClientStateMachine.getConnectionState(null), + Assert.assertEquals( + mHeadsetClientStateMachine.getConnectionState(null), BluetoothProfile.STATE_DISCONNECTED); } - /** - * Test that an incoming connection with low priority is rejected - */ + /** Test that an incoming connection with low priority is rejected */ @MediumTest @Test public void testIncomingPriorityReject() { // Return false for priority. - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Inject an event for when incoming connection is requested StackEvent connStCh = new StackEvent(StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); @@ -283,29 +281,33 @@ public class HeadsetClientStateMachineTest { // Verify that only DISCONNECTED -> DISCONNECTED broadcast is fired verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS)) - .sendBroadcastMultiplePermissions(MockitoHamcrest.argThat( - AllOf.allOf(IntentMatchers.hasAction( - BluetoothHeadsetClient.ACTION_CONNECTION_STATE_CHANGED), - IntentMatchers.hasExtra(BluetoothProfile.EXTRA_STATE, - BluetoothProfile.STATE_DISCONNECTED), - IntentMatchers.hasExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, - BluetoothProfile.STATE_DISCONNECTED))), - any(String[].class), - any(BroadcastOptions.class)); + .sendBroadcastMultiplePermissions( + MockitoHamcrest.argThat( + AllOf.allOf( + IntentMatchers.hasAction( + BluetoothHeadsetClient + .ACTION_CONNECTION_STATE_CHANGED), + IntentMatchers.hasExtra( + BluetoothProfile.EXTRA_STATE, + BluetoothProfile.STATE_DISCONNECTED), + IntentMatchers.hasExtra( + BluetoothProfile.EXTRA_PREVIOUS_STATE, + BluetoothProfile.STATE_DISCONNECTED))), + any(String[].class), + any(BroadcastOptions.class)); // Check we are in disconnected state still. - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Disconnected.class)); } - /** - * Test that an incoming connection with high priority is accepted - */ + /** Test that an incoming connection with high priority is accepted */ @MediumTest @Test public void testIncomingPriorityAccept() { // Return true for priority. - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); // Inject an event for when incoming connection is requested StackEvent connStCh = new StackEvent(StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); @@ -316,13 +318,17 @@ public class HeadsetClientStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS)) - .sendBroadcastMultiplePermissions(intentArgument1.capture(), - any(String[].class), any(BroadcastOptions.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + .sendBroadcastMultiplePermissions( + intentArgument1.capture(), + any(String[].class), + any(BroadcastOptions.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check we are in connecting state now. - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connecting.class)); // Send a message to trigger SLC connection @@ -338,25 +344,27 @@ public class HeadsetClientStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(2)) - .sendBroadcastMultiplePermissions(intentArgument2.capture(), - any(String[].class), any(BroadcastOptions.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, + .sendBroadcastMultiplePermissions( + intentArgument2.capture(), + any(String[].class), + any(BroadcastOptions.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check we are in connecting state now. - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connected.class)); verify(mHeadsetService).updateInbandRinging(eq(mTestDevice), eq(true)); } - /** - * Test that an incoming connection that times out - */ + /** Test that an incoming connection that times out */ @MediumTest @Test public void testIncomingTimeout() { // Return true for priority. - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); // Inject an event for when incoming connection is requested StackEvent connStCh = new StackEvent(StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); @@ -367,26 +375,35 @@ public class HeadsetClientStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS)) - .sendBroadcastMultiplePermissions(intentArgument1.capture(), - any(String[].class), any(BroadcastOptions.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + .sendBroadcastMultiplePermissions( + intentArgument1.capture(), + any(String[].class), + any(BroadcastOptions.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check we are in connecting state now. - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connecting.class)); // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class); - verify(mHeadsetClientService, - timeout(HeadsetClientStateMachine.CONNECTING_TIMEOUT_MS * 2).times(2)) - .sendBroadcastMultiplePermissions(intentArgument2.capture(), - any(String[].class), any(BroadcastOptions.class)); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + verify( + mHeadsetClientService, + timeout(HeadsetClientStateMachine.CONNECTING_TIMEOUT_MS * 2).times(2)) + .sendBroadcastMultiplePermissions( + intentArgument2.capture(), + any(String[].class), + any(BroadcastOptions.class)); + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Check we are in connecting state now. - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Disconnected.class)); verify(mHeadsetService).updateInbandRinging(eq(mTestDevice), eq(false)); } @@ -396,31 +413,39 @@ public class HeadsetClientStateMachineTest { initToConnectedState(); // True on correct AT command and BluetothDevice - Assert.assertTrue(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: (SINKAUDIOPOLICY)", mTestDevice)); - Assert.assertTrue(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: ()", mTestDevice)); - Assert.assertTrue(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: (,,,)", mTestDevice)); - Assert.assertTrue(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: (SINKAUDIOPOLICY),(OTHERFEATURE)", mTestDevice)); - Assert.assertTrue(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: (SINKAUDIOPOLICY),(OTHERFEATURE,1,2,3),(1,2,3)", mTestDevice)); - Assert.assertTrue(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: 123", mTestDevice)); - Assert.assertTrue(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: ", mTestDevice)); + Assert.assertTrue( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "+ANDROID: (SINKAUDIOPOLICY)", mTestDevice)); + Assert.assertTrue( + mHeadsetClientStateMachine.processAndroidSlcCommand("+ANDROID: ()", mTestDevice)); + Assert.assertTrue( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "+ANDROID: (,,,)", mTestDevice)); + Assert.assertTrue( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "+ANDROID: (SINKAUDIOPOLICY),(OTHERFEATURE)", mTestDevice)); + Assert.assertTrue( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "+ANDROID: (SINKAUDIOPOLICY),(OTHERFEATURE,1,2,3),(1,2,3)", mTestDevice)); + Assert.assertTrue( + mHeadsetClientStateMachine.processAndroidSlcCommand("+ANDROID: 123", mTestDevice)); + Assert.assertTrue( + mHeadsetClientStateMachine.processAndroidSlcCommand("+ANDROID: ", mTestDevice)); // False on incorrect AT command format - Assert.assertFalse(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID= (SINKAUDIOPOLICY)", mTestDevice)); - Assert.assertFalse(mHeadsetClientStateMachine.processAndroidSlcCommand( - "RANDOM ^%$# STRING", mTestDevice)); + Assert.assertFalse( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "+ANDROID= (SINKAUDIOPOLICY)", mTestDevice)); + Assert.assertFalse( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "RANDOM ^%$# STRING", mTestDevice)); Assert.assertFalse(mHeadsetClientStateMachine.processAndroidSlcCommand("", mTestDevice)); // False on incorrect BluetoothDevice - Assert.assertFalse(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: (SINKAUDIOPOLICY)", mAdapter.getRemoteDevice("05:04:01:02:03:00"))); + Assert.assertFalse( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "+ANDROID: (SINKAUDIOPOLICY)", + mAdapter.getRemoteDevice("05:04:01:02:03:00"))); } @Test @@ -428,34 +453,38 @@ public class HeadsetClientStateMachineTest { initToConnectedState(); mHeadsetClientStateMachine.setAudioPolicyRemoteSupported(false); - Assert.assertFalse(mHeadsetClientStateMachine.processAndroidSlcCommand( - "RANDOM ^%$# STRING", mTestDevice)); - Assert.assertEquals(BluetoothStatusCodes.FEATURE_NOT_SUPPORTED, + Assert.assertFalse( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "RANDOM ^%$# STRING", mTestDevice)); + Assert.assertEquals( + BluetoothStatusCodes.FEATURE_NOT_SUPPORTED, mHeadsetClientStateMachine.getAudioPolicyRemoteSupported()); mHeadsetClientStateMachine.setAudioPolicyRemoteSupported(false); - Assert.assertFalse(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID= (SINKAUDIOPOLICY)", mTestDevice)); - Assert.assertEquals(BluetoothStatusCodes.FEATURE_NOT_SUPPORTED, + Assert.assertFalse( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "+ANDROID= (SINKAUDIOPOLICY)", mTestDevice)); + Assert.assertEquals( + BluetoothStatusCodes.FEATURE_NOT_SUPPORTED, mHeadsetClientStateMachine.getAudioPolicyRemoteSupported()); mHeadsetClientStateMachine.setAudioPolicyRemoteSupported(false); - Assert.assertTrue(mHeadsetClientStateMachine.processAndroidSlcCommand( - "+ANDROID: (SINKAUDIOPOLICY)", mTestDevice)); - Assert.assertEquals(BluetoothStatusCodes.FEATURE_SUPPORTED, + Assert.assertTrue( + mHeadsetClientStateMachine.processAndroidSlcCommand( + "+ANDROID: (SINKAUDIOPOLICY)", mTestDevice)); + Assert.assertEquals( + BluetoothStatusCodes.FEATURE_SUPPORTED, mHeadsetClientStateMachine.getAudioPolicyRemoteSupported()); } - /** - * Test that In Band Ringtone information is relayed from phone. - */ + /** Test that In Band Ringtone information is relayed from phone. */ @LargeTest @Test @FlakyTest public void testInBandRingtone() { // Return true for priority. - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); Assert.assertEquals(false, mHeadsetClientStateMachine.getInBandRing()); @@ -470,11 +499,14 @@ public class HeadsetClientStateMachineTest { // Verify that one connection state broadcast is executed ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); - verify(mHeadsetClientService, - timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastMultiplePermissionsIndex++)) - .sendBroadcastMultiplePermissions(intentArgument.capture(), - any(String[].class), any(BroadcastOptions.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + verify( + mHeadsetClientService, + timeout(STANDARD_WAIT_MILLIS) + .times(expectedBroadcastMultiplePermissionsIndex++)) + .sendBroadcastMultiplePermissions( + intentArgument.capture(), any(String[].class), any(BroadcastOptions.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); // Send a message to trigger SLC connection @@ -487,12 +519,15 @@ public class HeadsetClientStateMachineTest { setUpAndroidAt(false); - verify(mHeadsetClientService, - timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastMultiplePermissionsIndex++)) - .sendBroadcastMultiplePermissions(intentArgument.capture(), - any(String[].class), any(BroadcastOptions.class)); + verify( + mHeadsetClientService, + timeout(STANDARD_WAIT_MILLIS) + .times(expectedBroadcastMultiplePermissionsIndex++)) + .sendBroadcastMultiplePermissions( + intentArgument.capture(), any(String[].class), any(BroadcastOptions.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTED, intentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); verify(mHeadsetService).updateInbandRinging(eq(mTestDevice), eq(true)); @@ -507,12 +542,12 @@ public class HeadsetClientStateMachineTest { eventInBandRing.device = mTestDevice; mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, eventInBandRing); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastIndex++)) - .sendBroadcast( - intentArgument.capture(), - anyString(), any(Bundle.class)); - Assert.assertEquals(1, - intentArgument.getValue().getIntExtra(BluetoothHeadsetClient.EXTRA_IN_BAND_RING, - -1)); + .sendBroadcast(intentArgument.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + 1, + intentArgument + .getValue() + .getIntExtra(BluetoothHeadsetClient.EXTRA_IN_BAND_RING, -1)); Assert.assertEquals(true, mHeadsetClientStateMachine.getInBandRing()); // Simulate a new incoming phone call @@ -520,54 +555,55 @@ public class HeadsetClientStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, eventCallStatusUpdated); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - verify(mHeadsetClientService, - timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastIndex - 1)) - .sendBroadcast( - intentArgument.capture(), - anyString(),any(Bundle.class)); + verify( + mHeadsetClientService, + timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastIndex - 1)) + .sendBroadcast(intentArgument.capture(), anyString(), any(Bundle.class)); // Provide information about the new call StackEvent eventIncomingCall = new StackEvent(StackEvent.EVENT_TYPE_CURRENT_CALLS); - eventIncomingCall.valueInt = 1; //index - eventIncomingCall.valueInt2 = 1; //direction - eventIncomingCall.valueInt3 = 4; //state - eventIncomingCall.valueInt4 = 0; //multi party - eventIncomingCall.valueString = "5551212"; //phone number + eventIncomingCall.valueInt = 1; // index + eventIncomingCall.valueInt2 = 1; // direction + eventIncomingCall.valueInt3 = 4; // state + eventIncomingCall.valueInt4 = 0; // multi party + eventIncomingCall.valueString = "5551212"; // phone number eventIncomingCall.device = mTestDevice; mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, eventIncomingCall); - verify(mHeadsetClientService, - timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastIndex - 1)) - .sendBroadcast( - intentArgument.capture(), - anyString(), any(Bundle.class)); - + verify( + mHeadsetClientService, + timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastIndex - 1)) + .sendBroadcast(intentArgument.capture(), anyString(), any(Bundle.class)); // Signal that the complete list of calls was received. StackEvent eventCommandStatus = new StackEvent(StackEvent.EVENT_TYPE_CMD_RESULT); eventCommandStatus.valueInt = AT_OK; mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, eventCommandStatus); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - verify(mHeadsetClientService, - timeout(QUERY_CURRENT_CALLS_TEST_WAIT_MILLIS).times(expectedBroadcastIndex++)) - .sendBroadcast( - intentArgument.capture(), - anyString(), any(Bundle.class)); + verify( + mHeadsetClientService, + timeout(QUERY_CURRENT_CALLS_TEST_WAIT_MILLIS) + .times(expectedBroadcastIndex++)) + .sendBroadcast(intentArgument.capture(), anyString(), any(Bundle.class)); // Verify that the new call is being registered with the inBandRing flag set. - Assert.assertEquals(true, - ((HfpClientCall) intentArgument.getValue().getParcelableExtra( - BluetoothHeadsetClient.EXTRA_CALL)).isInBandRing()); + Assert.assertEquals( + true, + ((HfpClientCall) + intentArgument + .getValue() + .getParcelableExtra(BluetoothHeadsetClient.EXTRA_CALL)) + .isInBandRing()); // Disable In Band Ring and verify state gets propagated. eventInBandRing.valueInt = 0; mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, eventInBandRing); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastIndex++)) - .sendBroadcast( - intentArgument.capture(), - anyString(), any(Bundle.class)); - Assert.assertEquals(0, - intentArgument.getValue().getIntExtra(BluetoothHeadsetClient.EXTRA_IN_BAND_RING, - -1)); + .sendBroadcast(intentArgument.capture(), anyString(), any(Bundle.class)); + Assert.assertEquals( + 0, + intentArgument + .getValue() + .getIntExtra(BluetoothHeadsetClient.EXTRA_IN_BAND_RING, -1)); Assert.assertEquals(false, mHeadsetClientStateMachine.getInBandRing()); } @@ -637,9 +673,10 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, connStCh); ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(startBroadcastIndex)) - .sendBroadcastMultiplePermissions(intentArgument.capture(), - any(String[].class), any(BroadcastOptions.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + .sendBroadcastMultiplePermissions( + intentArgument.capture(), any(String[].class), any(BroadcastOptions.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, intentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); startBroadcastIndex++; return startBroadcastIndex; @@ -664,11 +701,13 @@ public class HeadsetClientStateMachineTest { ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(startBroadcastIndex)) - .sendBroadcastMultiplePermissions(intentArgument.capture(), - any(String[].class), any(BroadcastOptions.class)); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, + .sendBroadcastMultiplePermissions( + intentArgument.capture(), any(String[].class), any(BroadcastOptions.class)); + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTED, intentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connected.class)); verify(mHeadsetService).updateInbandRinging(eq(mTestDevice), eq(true)); @@ -677,8 +716,8 @@ public class HeadsetClientStateMachineTest { } /** - * Set up and verify AT Android related commands and events. - * Make sure this method is invoked after SLC is setup. + * Set up and verify AT Android related commands and events. Make sure this method is invoked + * after SLC is setup. */ private void setUpAndroidAt(boolean androidAtSupported) { verify(mNativeInterface).sendAndroidAt(mTestDevice, "+ANDROID=?"); @@ -697,7 +736,8 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, cmdResEvt); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertEquals(BluetoothStatusCodes.FEATURE_SUPPORTED, + Assert.assertEquals( + BluetoothStatusCodes.FEATURE_SUPPORTED, mHeadsetClientStateMachine.getAudioPolicyRemoteSupported()); } else { // receive CMD_RESULT CME_ERROR due to remote not supporting Android AT @@ -707,7 +747,8 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, cmdResEvt); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertEquals(BluetoothStatusCodes.FEATURE_NOT_SUPPORTED, + Assert.assertEquals( + BluetoothStatusCodes.FEATURE_NOT_SUPPORTED, mHeadsetClientStateMachine.getAudioPolicyRemoteSupported()); } } @@ -715,27 +756,29 @@ public class HeadsetClientStateMachineTest { /* Utility function: supported AT command should lead to native call */ private void runSupportedVendorAtCommand(String atCommand, int vendorId) { // Return true for priority. - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); int expectedBroadcastIndex = 1; expectedBroadcastIndex = setUpHfpClientConnection(expectedBroadcastIndex); expectedBroadcastIndex = setUpServiceLevelConnection(expectedBroadcastIndex); - Message msg = mHeadsetClientStateMachine.obtainMessage( - HeadsetClientStateMachine.SEND_VENDOR_AT_COMMAND, vendorId, 0, atCommand); + Message msg = + mHeadsetClientStateMachine.obtainMessage( + HeadsetClientStateMachine.SEND_VENDOR_AT_COMMAND, vendorId, 0, atCommand); mHeadsetClientStateMachine.sendMessage(msg); - verify(mNativeInterface, timeout(STANDARD_WAIT_MILLIS).times(1)).sendATCmd( - mTestDevice, - HeadsetClientHalConstants.HANDSFREECLIENT_AT_CMD_VENDOR_SPECIFIC_CMD, - 0, 0, atCommand); + verify(mNativeInterface, timeout(STANDARD_WAIT_MILLIS).times(1)) + .sendATCmd( + mTestDevice, + HeadsetClientHalConstants.HANDSFREECLIENT_AT_CMD_VENDOR_SPECIFIC_CMD, + 0, + 0, + atCommand); } - /** - * Test: supported vendor specific command: set operation - */ + /** Test: supported vendor specific command: set operation */ @LargeTest @Test public void testSupportedVendorAtCommandSet() { @@ -744,9 +787,7 @@ public class HeadsetClientStateMachineTest { runSupportedVendorAtCommand(atCommand, vendorId); } - /** - * Test: supported vendor specific command: read operation - */ + /** Test: supported vendor specific command: read operation */ @LargeTest @Test public void testSupportedVendorAtCommandRead() { @@ -758,25 +799,24 @@ public class HeadsetClientStateMachineTest { /* utility function: unsupported vendor specific command shall be filtered. */ public void runUnsupportedVendorAtCommand(String atCommand, int vendorId) { // Return true for priority. - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); int expectedBroadcastIndex = 1; expectedBroadcastIndex = setUpHfpClientConnection(expectedBroadcastIndex); expectedBroadcastIndex = setUpServiceLevelConnection(expectedBroadcastIndex); - Message msg = mHeadsetClientStateMachine.obtainMessage( - HeadsetClientStateMachine.SEND_VENDOR_AT_COMMAND, vendorId, 0, atCommand); + Message msg = + mHeadsetClientStateMachine.obtainMessage( + HeadsetClientStateMachine.SEND_VENDOR_AT_COMMAND, vendorId, 0, atCommand); mHeadsetClientStateMachine.sendMessage(msg); verify(mNativeInterface, timeout(STANDARD_WAIT_MILLIS).times(0)) .sendATCmd(any(), anyInt(), anyInt(), anyInt(), any()); } - /** - * Test: unsupported vendor specific command shall be filtered: bad command code - */ + /** Test: unsupported vendor specific command shall be filtered: bad command code */ @LargeTest @Test public void testUnsupportedVendorAtCommandBadCode() { @@ -785,10 +825,7 @@ public class HeadsetClientStateMachineTest { runUnsupportedVendorAtCommand(atCommand, vendorId); } - /** - * Test: unsupported vendor specific command shall be filtered: - * no back to back command - */ + /** Test: unsupported vendor specific command shall be filtered: no back to back command */ @LargeTest @Test public void testUnsupportedVendorAtCommandBackToBack() { @@ -800,17 +837,17 @@ public class HeadsetClientStateMachineTest { /* Utility test function: supported vendor specific event * shall lead to broadcast intent */ - private void runSupportedVendorEvent(int vendorId, String vendorEventCode, - String vendorEventArgument) { + private void runSupportedVendorEvent( + int vendorId, String vendorEventCode, String vendorEventArgument) { // Setup connection state machine to be in connected state - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); int expectedBroadcastIndex = 1; int expectedBroadcastMultiplePermissionsIndex = 1; expectedBroadcastMultiplePermissionsIndex = - setUpHfpClientConnection(expectedBroadcastMultiplePermissionsIndex); + setUpHfpClientConnection(expectedBroadcastMultiplePermissionsIndex); expectedBroadcastMultiplePermissionsIndex = - setUpServiceLevelConnection(expectedBroadcastMultiplePermissionsIndex); + setUpServiceLevelConnection(expectedBroadcastMultiplePermissionsIndex); // Simulate a known event arrive String vendorEvent = vendorEventCode + vendorEventArgument; @@ -823,21 +860,25 @@ public class HeadsetClientStateMachineTest { ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastIndex)) .sendBroadcast(intentArgument.capture(), anyString(), any(Bundle.class)); - Assert.assertEquals(BluetoothHeadsetClient.ACTION_VENDOR_SPECIFIC_HEADSETCLIENT_EVENT, + Assert.assertEquals( + BluetoothHeadsetClient.ACTION_VENDOR_SPECIFIC_HEADSETCLIENT_EVENT, intentArgument.getValue().getAction()); - Assert.assertEquals(vendorId, + Assert.assertEquals( + vendorId, intentArgument.getValue().getIntExtra(BluetoothHeadsetClient.EXTRA_VENDOR_ID, -1)); - Assert.assertEquals(vendorEventCode, - intentArgument.getValue().getStringExtra( - BluetoothHeadsetClient.EXTRA_VENDOR_EVENT_CODE)); - Assert.assertEquals(vendorEvent, - intentArgument.getValue().getStringExtra( - BluetoothHeadsetClient.EXTRA_VENDOR_EVENT_FULL_ARGS)); + Assert.assertEquals( + vendorEventCode, + intentArgument + .getValue() + .getStringExtra(BluetoothHeadsetClient.EXTRA_VENDOR_EVENT_CODE)); + Assert.assertEquals( + vendorEvent, + intentArgument + .getValue() + .getStringExtra(BluetoothHeadsetClient.EXTRA_VENDOR_EVENT_FULL_ARGS)); } - /** - * Test: supported vendor specific response: response to read command - */ + /** Test: supported vendor specific response: response to read command */ @LargeTest @Test public void testSupportedVendorEventReadResponse() { @@ -847,9 +888,7 @@ public class HeadsetClientStateMachineTest { runSupportedVendorEvent(vendorId, vendorResponseCode, vendorResponseArgument); } - /** - * Test: supported vendor specific response: response to test command - */ + /** Test: supported vendor specific response: response to test command */ @LargeTest @Test public void testSupportedVendorEventTestResponse() { @@ -860,11 +899,11 @@ public class HeadsetClientStateMachineTest { } /* Utility test function: unsupported vendor specific response shall be filtered out*/ - public void runUnsupportedVendorEvent(int vendorId, String vendorEventCode, - String vendorEventArgument) { + public void runUnsupportedVendorEvent( + int vendorId, String vendorEventCode, String vendorEventArgument) { // Setup connection state machine to be in connected state - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); int expectedBroadcastIndex = 1; expectedBroadcastIndex = setUpHfpClientConnection(expectedBroadcastIndex); expectedBroadcastIndex = setUpServiceLevelConnection(expectedBroadcastIndex); @@ -881,9 +920,7 @@ public class HeadsetClientStateMachineTest { .sendBroadcast(any(), anyString(), any(Bundle.class)); } - /** - * Test unsupported vendor response: bad read response - */ + /** Test unsupported vendor response: bad read response */ @LargeTest @Test public void testUnsupportedVendorEventBadReadResponse() { @@ -893,9 +930,7 @@ public class HeadsetClientStateMachineTest { runUnsupportedVendorEvent(vendorId, vendorResponseCode, vendorResponseArgument); } - /** - * Test unsupported vendor response: bad test response - */ + /** Test unsupported vendor response: bad test response */ @LargeTest @Test public void testUnsupportedVendorEventBadTestResponse() { @@ -905,24 +940,22 @@ public class HeadsetClientStateMachineTest { runUnsupportedVendorEvent(vendorId, vendorResponseCode, vendorResponseArgument); } - /** - * Test voice recognition state change broadcast. - */ + /** Test voice recognition state change broadcast. */ @MediumTest @Test public void testVoiceRecognitionStateChange() { // Setup connection state machine to be in connected state - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mNativeInterface).startVoiceRecognition(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).stopVoiceRecognition(any(BluetoothDevice.class)); int expectedBroadcastIndex = 1; int expectedBroadcastMultiplePermissionsIndex = 1; expectedBroadcastMultiplePermissionsIndex = - setUpHfpClientConnection(expectedBroadcastMultiplePermissionsIndex); + setUpHfpClientConnection(expectedBroadcastMultiplePermissionsIndex); expectedBroadcastMultiplePermissionsIndex = - setUpServiceLevelConnection(expectedBroadcastMultiplePermissionsIndex); + setUpServiceLevelConnection(expectedBroadcastMultiplePermissionsIndex); // Simulate a voice recognition start mHeadsetClientStateMachine.sendMessage(VOICE_RECOGNITION_START); @@ -933,8 +966,9 @@ public class HeadsetClientStateMachineTest { event.valueInt = AT_OK; mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, event); - expectedBroadcastIndex = verifyVoiceRecognitionBroadcast(expectedBroadcastIndex, - HeadsetClientHalConstants.VR_STATE_STARTED); + expectedBroadcastIndex = + verifyVoiceRecognitionBroadcast( + expectedBroadcastIndex, HeadsetClientHalConstants.VR_STATE_STARTED); // Simulate a voice recognition stop mHeadsetClientStateMachine.sendMessage(VOICE_RECOGNITION_STOP); @@ -945,8 +979,8 @@ public class HeadsetClientStateMachineTest { event.valueInt = AT_OK; mHeadsetClientStateMachine.sendMessage(StackEvent.STACK_EVENT, event); - verifyVoiceRecognitionBroadcast(expectedBroadcastIndex, - HeadsetClientHalConstants.VR_STATE_STOPPED); + verifyVoiceRecognitionBroadcast( + expectedBroadcastIndex, HeadsetClientHalConstants.VR_STATE_STOPPED); } private int verifyVoiceRecognitionBroadcast(int expectedBroadcastIndex, int expectedState) { @@ -954,23 +988,23 @@ public class HeadsetClientStateMachineTest { ArgumentCaptor intentArgument = ArgumentCaptor.forClass(Intent.class); verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(expectedBroadcastIndex)) .sendBroadcast(intentArgument.capture(), anyString(), any(Bundle.class)); - Assert.assertEquals(BluetoothHeadsetClient.ACTION_AG_EVENT, - intentArgument.getValue().getAction()); - int state = intentArgument.getValue().getIntExtra( - BluetoothHeadsetClient.EXTRA_VOICE_RECOGNITION, -1); + Assert.assertEquals( + BluetoothHeadsetClient.ACTION_AG_EVENT, intentArgument.getValue().getAction()); + int state = + intentArgument + .getValue() + .getIntExtra(BluetoothHeadsetClient.EXTRA_VOICE_RECOGNITION, -1); Assert.assertEquals(expectedState, state); return expectedBroadcastIndex + 1; } - /** - * Test send BIEV command - */ + /** Test send BIEV command */ @MediumTest @Test public void testSendBIEVCommand() { // Setup connection state machine to be in connected state - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); int expectedBroadcastIndex = 1; expectedBroadcastIndex = setUpHfpClientConnection(expectedBroadcastIndex); expectedBroadcastIndex = setUpServiceLevelConnection(expectedBroadcastIndex); @@ -994,27 +1028,26 @@ public class HeadsetClientStateMachineTest { } /** - * Test state machine shall try to send AT+BIEV command to AG - * to update an init battery level. + * Test state machine shall try to send AT+BIEV command to AG to update an init battery level. */ @MediumTest @Test public void testSendBatteryUpdateIndicatorWhenConnect() { // Setup connection state machine to be in connected state - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); int expectedBroadcastIndex = 1; expectedBroadcastIndex = setUpHfpClientConnection(expectedBroadcastIndex); expectedBroadcastIndex = setUpServiceLevelConnection(expectedBroadcastIndex); - verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(1)) - .updateBatteryLevel(); + verify(mHeadsetClientService, timeout(STANDARD_WAIT_MILLIS).times(1)).updateBatteryLevel(); } @Test public void testBroadcastAudioState() { - mHeadsetClientStateMachine.broadcastAudioState(mTestDevice, + mHeadsetClientStateMachine.broadcastAudioState( + mTestDevice, BluetoothHeadsetClient.STATE_AUDIO_CONNECTED, BluetoothHeadsetClient.STATE_AUDIO_CONNECTING); @@ -1023,8 +1056,9 @@ public class HeadsetClientStateMachineTest { @Test public void testCallsInState() { - HfpClientCall call = new HfpClientCall(mTestDevice, 0, HfpClientCall.CALL_STATE_WAITING, - "1", false, false, false); + HfpClientCall call = + new HfpClientCall( + mTestDevice, 0, HfpClientCall.CALL_STATE_WAITING, "1", false, false, false); mHeadsetClientStateMachine.mCalls.put(0, call); Assert.assertEquals( @@ -1033,11 +1067,13 @@ public class HeadsetClientStateMachineTest { @Test public void testEnterPrivateMode() { - HfpClientCall call = new HfpClientCall(mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, - "1", true, false, false); + HfpClientCall call = + new HfpClientCall( + mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, "1", true, false, false); mHeadsetClientStateMachine.mCalls.put(0, call); - doReturn(true).when(mNativeInterface).handleCallAction(null, - HeadsetClientHalConstants.CALL_ACTION_CHLD_2X, 0); + doReturn(true) + .when(mNativeInterface) + .handleCallAction(null, HeadsetClientHalConstants.CALL_ACTION_CHLD_2X, 0); mHeadsetClientStateMachine.enterPrivateMode(0); @@ -1047,14 +1083,17 @@ public class HeadsetClientStateMachineTest { @Test public void testExplicitCallTransfer() { - HfpClientCall callOne = new HfpClientCall(mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, - "1", true, false, false); - HfpClientCall callTwo = new HfpClientCall(mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, - "1", true, false, false); + HfpClientCall callOne = + new HfpClientCall( + mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, "1", true, false, false); + HfpClientCall callTwo = + new HfpClientCall( + mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, "1", true, false, false); mHeadsetClientStateMachine.mCalls.put(0, callOne); mHeadsetClientStateMachine.mCalls.put(1, callTwo); - doReturn(true).when(mNativeInterface).handleCallAction(null, - HeadsetClientHalConstants.CALL_ACTION_CHLD_4, -1); + doReturn(true) + .when(mNativeInterface) + .handleCallAction(null, HeadsetClientHalConstants.CALL_ACTION_CHLD_4, -1); mHeadsetClientStateMachine.explicitCallTransfer(); @@ -1072,8 +1111,8 @@ public class HeadsetClientStateMachineTest { // Expect: Should not send +ANDROID to remote mHeadsetClientStateMachine.mCurrentDevice = mTestDevice; mHeadsetClientStateMachine.setAudioPolicyRemoteSupported(false); - verify(mNativeInterface, never()).sendAndroidAt(mTestDevice, - "+ANDROID=SINKAUDIOPOLICY,1,0,0"); + verify(mNativeInterface, never()) + .sendAndroidAt(mTestDevice, "+ANDROID=SINKAUDIOPOLICY,1,0,0"); // Case 2: if remote is supported and mForceSetAudioPolicyProperty is false // Expect: Should send +ANDROID=SINKAUDIOPOLICY,1,0,0 to remote @@ -1096,7 +1135,8 @@ public class HeadsetClientStateMachineTest { public void testGetAudioState_withCurrentDeviceNull() { Assert.assertNull(mHeadsetClientStateMachine.mCurrentDevice); - Assert.assertEquals(mHeadsetClientStateMachine.getAudioState(mTestDevice), + Assert.assertEquals( + mHeadsetClientStateMachine.getAudioState(mTestDevice), BluetoothHeadsetClient.STATE_AUDIO_DISCONNECTED); } @@ -1111,8 +1151,9 @@ public class HeadsetClientStateMachineTest { @Test public void testGetCall_withMatchingState() { - HfpClientCall call = new HfpClientCall(mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, - "1", true, false, false); + HfpClientCall call = + new HfpClientCall( + mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, "1", true, false, false); mHeadsetClientStateMachine.mCalls.put(0, call); int[] states = new int[1]; states[0] = HfpClientCall.CALL_STATE_ACTIVE; @@ -1122,8 +1163,9 @@ public class HeadsetClientStateMachineTest { @Test public void testGetCall_withNoMatchingState() { - HfpClientCall call = new HfpClientCall(mTestDevice, 0, HfpClientCall.CALL_STATE_WAITING, - "1", true, false, false); + HfpClientCall call = + new HfpClientCall( + mTestDevice, 0, HfpClientCall.CALL_STATE_WAITING, "1", true, false, false); mHeadsetClientStateMachine.mCalls.put(0, call); int[] states = new int[1]; states[0] = HfpClientCall.CALL_STATE_ACTIVE; @@ -1133,7 +1175,8 @@ public class HeadsetClientStateMachineTest { @Test public void testGetConnectionState_withNullDevice() { - Assert.assertEquals(mHeadsetClientStateMachine.getConnectionState(null), + Assert.assertEquals( + mHeadsetClientStateMachine.getConnectionState(null), BluetoothProfile.STATE_DISCONNECTED); } @@ -1141,17 +1184,23 @@ public class HeadsetClientStateMachineTest { public void testGetConnectionState_withNonNullDevice() { mHeadsetClientStateMachine.mCurrentDevice = mTestDevice; - Assert.assertEquals(mHeadsetClientStateMachine.getConnectionState(mTestDevice), + Assert.assertEquals( + mHeadsetClientStateMachine.getConnectionState(mTestDevice), BluetoothProfile.STATE_DISCONNECTED); } @Test public void testGetConnectionStateFromAudioState() { - Assert.assertEquals(HeadsetClientStateMachine.getConnectionStateFromAudioState( - BluetoothHeadsetClient.STATE_AUDIO_CONNECTED), BluetoothAdapter.STATE_CONNECTED); - Assert.assertEquals(HeadsetClientStateMachine.getConnectionStateFromAudioState( - BluetoothHeadsetClient.STATE_AUDIO_CONNECTING), BluetoothAdapter.STATE_CONNECTING); - Assert.assertEquals(HeadsetClientStateMachine.getConnectionStateFromAudioState( + Assert.assertEquals( + HeadsetClientStateMachine.getConnectionStateFromAudioState( + BluetoothHeadsetClient.STATE_AUDIO_CONNECTED), + BluetoothAdapter.STATE_CONNECTED); + Assert.assertEquals( + HeadsetClientStateMachine.getConnectionStateFromAudioState( + BluetoothHeadsetClient.STATE_AUDIO_CONNECTING), + BluetoothAdapter.STATE_CONNECTING); + Assert.assertEquals( + HeadsetClientStateMachine.getConnectionStateFromAudioState( BluetoothHeadsetClient.STATE_AUDIO_DISCONNECTED), BluetoothAdapter.STATE_DISCONNECTED); int invalidAudioState = 3; @@ -1164,7 +1213,8 @@ public class HeadsetClientStateMachineTest { public void testGetCurrentAgEvents() { Bundle bundle = mHeadsetClientStateMachine.getCurrentAgEvents(); - Assert.assertEquals(bundle.getString(BluetoothHeadsetClient.EXTRA_SUBSCRIBER_INFO), + Assert.assertEquals( + bundle.getString(BluetoothHeadsetClient.EXTRA_SUBSCRIBER_INFO), mHeadsetClientStateMachine.mSubscriberInfo); } @@ -1205,16 +1255,18 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.mChldFeatures = HeadsetClientHalConstants.CHLD_FEAT_HOLD_ACC; Bundle bundle = mHeadsetClientStateMachine.getCurrentAgFeaturesBundle(); Assert.assertTrue(bundle.getBoolean(BluetoothHeadsetClient.EXTRA_AG_FEATURE_3WAY_CALLING)); - Assert.assertTrue(bundle.getBoolean( - BluetoothHeadsetClient.EXTRA_AG_FEATURE_ACCEPT_HELD_OR_WAITING_CALL)); + Assert.assertTrue( + bundle.getBoolean( + BluetoothHeadsetClient.EXTRA_AG_FEATURE_ACCEPT_HELD_OR_WAITING_CALL)); mHeadsetClientStateMachine.mPeerFeatures = HeadsetClientHalConstants.PEER_FEAT_VREC; mHeadsetClientStateMachine.mChldFeatures = HeadsetClientHalConstants.CHLD_FEAT_REL; bundle = mHeadsetClientStateMachine.getCurrentAgFeaturesBundle(); Assert.assertTrue( bundle.getBoolean(BluetoothHeadsetClient.EXTRA_AG_FEATURE_VOICE_RECOGNITION)); - Assert.assertTrue(bundle.getBoolean( - BluetoothHeadsetClient.EXTRA_AG_FEATURE_RELEASE_HELD_OR_WAITING_CALL)); + Assert.assertTrue( + bundle.getBoolean( + BluetoothHeadsetClient.EXTRA_AG_FEATURE_RELEASE_HELD_OR_WAITING_CALL)); mHeadsetClientStateMachine.mPeerFeatures = HeadsetClientHalConstants.PEER_FEAT_REJECT; mHeadsetClientStateMachine.mChldFeatures = HeadsetClientHalConstants.CHLD_FEAT_REL_ACC; @@ -1237,8 +1289,9 @@ public class HeadsetClientStateMachineTest { @Test public void testGetCurrentCalls() { - HfpClientCall call = new HfpClientCall(mTestDevice, 0, HfpClientCall.CALL_STATE_WAITING, - "1", true, false, false); + HfpClientCall call = + new HfpClientCall( + mTestDevice, 0, HfpClientCall.CALL_STATE_WAITING, "1", true, false, false); mHeadsetClientStateMachine.mCalls.put(0, call); List currentCalls = mHeadsetClientStateMachine.getCurrentCalls(); @@ -1248,8 +1301,8 @@ public class HeadsetClientStateMachineTest { @Test public void testGetMessageName() { - Assert.assertEquals(HeadsetClientStateMachine.getMessageName(StackEvent.STACK_EVENT), - "STACK_EVENT"); + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName(StackEvent.STACK_EVENT), "STACK_EVENT"); Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.CONNECT), "CONNECT"); @@ -1259,17 +1312,23 @@ public class HeadsetClientStateMachineTest { Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.CONNECT_AUDIO), "CONNECT_AUDIO"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName( - HeadsetClientStateMachine.DISCONNECT_AUDIO), "DISCONNECT_AUDIO"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName(VOICE_RECOGNITION_START), + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName( + HeadsetClientStateMachine.DISCONNECT_AUDIO), + "DISCONNECT_AUDIO"); + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName(VOICE_RECOGNITION_START), "VOICE_RECOGNITION_START"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName(VOICE_RECOGNITION_STOP), + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName(VOICE_RECOGNITION_STOP), "VOICE_RECOGNITION_STOP"); Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.SET_MIC_VOLUME), "SET_MIC_VOLUME"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName( - HeadsetClientStateMachine.SET_SPEAKER_VOLUME), "SET_SPEAKER_VOLUME"); + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName( + HeadsetClientStateMachine.SET_SPEAKER_VOLUME), + "SET_SPEAKER_VOLUME"); Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.DIAL_NUMBER), "DIAL_NUMBER"); @@ -1285,43 +1344,54 @@ public class HeadsetClientStateMachineTest { Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.TERMINATE_CALL), "TERMINATE_CALL"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName(ENTER_PRIVATE_MODE), - "ENTER_PRIVATE_MODE"); + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName(ENTER_PRIVATE_MODE), "ENTER_PRIVATE_MODE"); Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.SEND_DTMF), "SEND_DTMF"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName(EXPLICIT_CALL_TRANSFER), + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName(EXPLICIT_CALL_TRANSFER), "EXPLICIT_CALL_TRANSFER"); Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.DISABLE_NREC), "DISABLE_NREC"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName( - HeadsetClientStateMachine.SEND_VENDOR_AT_COMMAND), "SEND_VENDOR_AT_COMMAND"); + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName( + HeadsetClientStateMachine.SEND_VENDOR_AT_COMMAND), + "SEND_VENDOR_AT_COMMAND"); Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.SEND_BIEV), "SEND_BIEV"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName( - HeadsetClientStateMachine.QUERY_CURRENT_CALLS), "QUERY_CURRENT_CALLS"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName( - HeadsetClientStateMachine.QUERY_OPERATOR_NAME), "QUERY_OPERATOR_NAME"); + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName( + HeadsetClientStateMachine.QUERY_CURRENT_CALLS), + "QUERY_CURRENT_CALLS"); + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName( + HeadsetClientStateMachine.QUERY_OPERATOR_NAME), + "QUERY_OPERATOR_NAME"); Assert.assertEquals( HeadsetClientStateMachine.getMessageName(HeadsetClientStateMachine.SUBSCRIBER_INFO), "SUBSCRIBER_INFO"); - Assert.assertEquals(HeadsetClientStateMachine.getMessageName( - HeadsetClientStateMachine.CONNECTING_TIMEOUT), "CONNECTING_TIMEOUT"); + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName( + HeadsetClientStateMachine.CONNECTING_TIMEOUT), + "CONNECTING_TIMEOUT"); int unknownMessageInt = 54; - Assert.assertEquals(HeadsetClientStateMachine.getMessageName(unknownMessageInt), + Assert.assertEquals( + HeadsetClientStateMachine.getMessageName(unknownMessageInt), "UNKNOWN(" + unknownMessageInt + ")"); } + /** - * Tests and verify behavior of the case where remote device doesn't support - * At Android but tries to send audio policy. + * Tests and verify behavior of the case where remote device doesn't support At Android but + * tries to send audio policy. */ @Test public void testAndroidAtRemoteNotSupported_StateTransition_setAudioPolicy() { // Setup connection state machine to be in connected state - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); int expectedBroadcastIndex = 1; expectedBroadcastIndex = setUpHfpClientConnection(expectedBroadcastIndex); @@ -1329,33 +1399,35 @@ public class HeadsetClientStateMachineTest { BluetoothSinkAudioPolicy dummyAudioPolicy = new BluetoothSinkAudioPolicy.Builder().build(); mHeadsetClientStateMachine.setAudioPolicy(dummyAudioPolicy); - verify(mNativeInterface, never()).sendAndroidAt(mTestDevice, - "+ANDROID=SINKAUDIOPOLICY,0,0,0"); + verify(mNativeInterface, never()) + .sendAndroidAt(mTestDevice, "+ANDROID=SINKAUDIOPOLICY,0,0,0"); } @SmallTest @Test public void testSetGetCallAudioPolicy() { // Return true for priority. - when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))).thenReturn( - BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mHeadsetClientService.getConnectionPolicy(any(BluetoothDevice.class))) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); int expectedBroadcastIndex = 1; expectedBroadcastIndex = setUpHfpClientConnection(expectedBroadcastIndex); expectedBroadcastIndex = setUpServiceLevelConnection(expectedBroadcastIndex, true); - BluetoothSinkAudioPolicy dummyAudioPolicy = new BluetoothSinkAudioPolicy.Builder() - .setCallEstablishPolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .setActiveDevicePolicyAfterConnection(BluetoothSinkAudioPolicy.POLICY_NOT_ALLOWED) - .setInBandRingtonePolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) - .build(); + BluetoothSinkAudioPolicy dummyAudioPolicy = + new BluetoothSinkAudioPolicy.Builder() + .setCallEstablishPolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .setActiveDevicePolicyAfterConnection( + BluetoothSinkAudioPolicy.POLICY_NOT_ALLOWED) + .setInBandRingtonePolicy(BluetoothSinkAudioPolicy.POLICY_ALLOWED) + .build(); // Test if not support audio policy feature mHeadsetClientStateMachine.setAudioPolicyRemoteSupported(false); mHeadsetClientStateMachine.setAudioPolicy(dummyAudioPolicy); - verify(mNativeInterface, never()).sendAndroidAt(mTestDevice, - "+ANDROID=SINKAUDIOPOLICY,1,2,1"); + verify(mNativeInterface, never()) + .sendAndroidAt(mTestDevice, "+ANDROID=SINKAUDIOPOLICY,1,2,1"); Assert.assertEquals(0, mHeadsetClientStateMachine.mQueuedActions.size()); // Test setAudioPolicy @@ -1419,16 +1491,16 @@ public class HeadsetClientStateMachineTest { public void testProcessDisconnectMessage_onDisconnectedState() { mHeadsetClientStateMachine.sendMessage(HeadsetClientStateMachine.DISCONNECT); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertEquals(STATE_DISCONNECTED, - mHeadsetClientStateMachine.getConnectionState(mTestDevice)); + Assert.assertEquals( + STATE_DISCONNECTED, mHeadsetClientStateMachine.getConnectionState(mTestDevice)); } @Test public void testProcessConnectMessage_onDisconnectedState() { doReturn(true).when(mNativeInterface).connect(any(BluetoothDevice.class)); sendMessageAndVerifyTransition( - mHeadsetClientStateMachine - .obtainMessage(HeadsetClientStateMachine.CONNECT, mTestDevice), + mHeadsetClientStateMachine.obtainMessage( + HeadsetClientStateMachine.CONNECT, mTestDevice), HeadsetClientStateMachine.Connecting.class); } @@ -1457,12 +1529,15 @@ public class HeadsetClientStateMachineTest { @Test public void testProcessConnectMessage_onConnectingState() { initToConnectingState(); - assertThat(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( - HeadsetClientStateMachine.CONNECT)).isFalse(); + assertThat( + mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( + HeadsetClientStateMachine.CONNECT)) + .isFalse(); mHeadsetClientStateMachine.sendMessage(HeadsetClientStateMachine.CONNECT); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertTrue(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( - HeadsetClientStateMachine.CONNECT)); + Assert.assertTrue( + mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( + HeadsetClientStateMachine.CONNECT)); } @Test @@ -1485,7 +1560,8 @@ public class HeadsetClientStateMachineTest { event.device = mTestDevice; mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connecting.class)); } @@ -1497,7 +1573,8 @@ public class HeadsetClientStateMachineTest { event.device = mTestDevice; mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connecting.class)); } @@ -1507,13 +1584,13 @@ public class HeadsetClientStateMachineTest { StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_CALL); event.valueInt = StackEvent.EVENT_TYPE_CALL; event.device = mTestDevice; - assertThat(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( - StackEvent.STACK_EVENT)).isFalse(); + assertThat(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages(StackEvent.STACK_EVENT)) + .isFalse(); mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertTrue(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( - StackEvent.STACK_EVENT)); + Assert.assertTrue( + mHeadsetClientStateMachine.doesSuperHaveDeferredMessages(StackEvent.STACK_EVENT)); } @Test @@ -1524,7 +1601,8 @@ public class HeadsetClientStateMachineTest { event.device = mTestDevice; mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connecting.class)); } @@ -1539,7 +1617,8 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connected.class)); verify(mHeadsetService).updateInbandRinging(eq(mTestDevice), eq(true)); } @@ -1547,8 +1626,9 @@ public class HeadsetClientStateMachineTest { @Test public void testProcessConnectTimeoutMessage_onConnectingState() { initToConnectingState(); - Message msg = mHeadsetClientStateMachine - .obtainMessage(HeadsetClientStateMachine.CONNECTING_TIMEOUT); + Message msg = + mHeadsetClientStateMachine.obtainMessage( + HeadsetClientStateMachine.CONNECTING_TIMEOUT); sendMessageAndVerifyTransition(msg, HeadsetClientStateMachine.Disconnected.class); verify(mHeadsetService).updateInbandRinging(eq(mTestDevice), eq(false)); } @@ -1559,13 +1639,13 @@ public class HeadsetClientStateMachineTest { StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_IN_BAND_RINGTONE); event.valueInt = StackEvent.EVENT_TYPE_IN_BAND_RINGTONE; event.device = mTestDevice; - assertThat(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( - StackEvent.STACK_EVENT)).isFalse(); + assertThat(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages(StackEvent.STACK_EVENT)) + .isFalse(); mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( - StackEvent.STACK_EVENT)).isTrue(); + assertThat(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages(StackEvent.STACK_EVENT)) + .isTrue(); } @Test @@ -1573,7 +1653,8 @@ public class HeadsetClientStateMachineTest { initToConnectedState(); mHeadsetClientStateMachine.sendMessage(HeadsetClientStateMachine.CONNECT); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connected.class)); } @@ -1612,19 +1693,22 @@ public class HeadsetClientStateMachineTest { @Test public void testProcessDisconnectMessage_onAudioOnState() { initToAudioOnState(); - assertThat(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( - HeadsetClientStateMachine.DISCONNECT)).isFalse(); + assertThat( + mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( + HeadsetClientStateMachine.DISCONNECT)) + .isFalse(); mHeadsetClientStateMachine.sendMessage(HeadsetClientStateMachine.DISCONNECT, mTestDevice); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertTrue(mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( - HeadsetClientStateMachine.DISCONNECT)); + Assert.assertTrue( + mHeadsetClientStateMachine.doesSuperHaveDeferredMessages( + HeadsetClientStateMachine.DISCONNECT)); } @Test public void testProcessDisconnectAudioMessage_onAudioOnState() { initToAudioOnState(); - mHeadsetClientStateMachine.sendMessage(HeadsetClientStateMachine.DISCONNECT_AUDIO, - mTestDevice); + mHeadsetClientStateMachine.sendMessage( + HeadsetClientStateMachine.DISCONNECT_AUDIO, mTestDevice); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mNativeInterface).disconnectAudio(any(BluetoothDevice.class)); } @@ -1632,13 +1716,13 @@ public class HeadsetClientStateMachineTest { @Test public void testProcessHoldCall_onAudioOnState() { initToAudioOnState(); - HfpClientCall call = new HfpClientCall(mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, - "1", true, false, false); + HfpClientCall call = + new HfpClientCall( + mTestDevice, 0, HfpClientCall.CALL_STATE_ACTIVE, "1", true, false, false); mHeadsetClientStateMachine.mCalls.put(0, call); int[] states = new int[1]; states[0] = HfpClientCall.CALL_STATE_ACTIVE; - mHeadsetClientStateMachine.sendMessage(HeadsetClientStateMachine.HOLD_CALL, - mTestDevice); + mHeadsetClientStateMachine.sendMessage(HeadsetClientStateMachine.HOLD_CALL, mTestDevice); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mNativeInterface).handleCallAction(any(BluetoothDevice.class), anyInt(), eq(0)); } @@ -1646,7 +1730,8 @@ public class HeadsetClientStateMachineTest { @Test public void testProcessStackEvent_ConnectionStateChanged_onAudioOnState() { initToAudioOnState(); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.AudioOn.class)); StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); event.valueInt = HeadsetClientHalConstants.CONNECTION_STATE_DISCONNECTED; @@ -1654,7 +1739,8 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Disconnected.class)); verify(mHeadsetService).updateInbandRinging(eq(mTestDevice), eq(false)); } @@ -1662,7 +1748,8 @@ public class HeadsetClientStateMachineTest { @Test public void testProcessStackEvent_AudioStateChanged_onAudioOnState() { initToAudioOnState(); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.AudioOn.class)); StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED); event.valueInt = HeadsetClientHalConstants.AUDIO_STATE_DISCONNECTED; @@ -1670,7 +1757,8 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connected.class)); } @@ -1718,8 +1806,8 @@ public class HeadsetClientStateMachineTest { private void initToConnectingState() { doReturn(true).when(mNativeInterface).connect(any(BluetoothDevice.class)); sendMessageAndVerifyTransition( - mHeadsetClientStateMachine - .obtainMessage(HeadsetClientStateMachine.CONNECT, mTestDevice), + mHeadsetClientStateMachine.obtainMessage( + HeadsetClientStateMachine.CONNECT, mTestDevice), HeadsetClientStateMachine.Connecting.class); } @@ -1732,7 +1820,8 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.Connected.class)); verify(mHeadsetService).updateInbandRinging(eq(mTestDevice), eq(true)); } @@ -1746,7 +1835,8 @@ public class HeadsetClientStateMachineTest { mHeadsetClientStateMachine.sendMessage( mHeadsetClientStateMachine.obtainMessage(StackEvent.STACK_EVENT, event)); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(HeadsetClientStateMachine.AudioOn.class)); } @@ -1754,11 +1844,11 @@ public class HeadsetClientStateMachineTest { Mockito.clearInvocations(mHeadsetClientService); mHeadsetClientStateMachine.sendMessage(msg); // Verify that one connection state broadcast is executed - verify(mHeadsetClientService, timeout(TIMEOUT_MS)).sendBroadcastMultiplePermissions( - any(Intent.class), any(String[].class), any(BroadcastOptions.class) - ); - Assert.assertThat(mHeadsetClientStateMachine.getCurrentState(), - IsInstanceOf.instanceOf(type)); + verify(mHeadsetClientService, timeout(TIMEOUT_MS)) + .sendBroadcastMultiplePermissions( + any(Intent.class), any(String[].class), any(BroadcastOptions.class)); + Assert.assertThat( + mHeadsetClientStateMachine.getCurrentState(), IsInstanceOf.instanceOf(type)); } public static class TestHeadsetClientStateMachine extends HeadsetClientStateMachine { @@ -1766,8 +1856,11 @@ public class HeadsetClientStateMachineTest { Boolean allowConnect = null; boolean mForceSetAudioPolicyProperty = false; - TestHeadsetClientStateMachine(HeadsetClientService context, HeadsetService headsetService, - Looper looper, NativeInterface nativeInterface) { + TestHeadsetClientStateMachine( + HeadsetClientService context, + HeadsetService headsetService, + Looper looper, + NativeInterface nativeInterface) { super(context, headsetService, looper, nativeInterface); } @@ -1790,7 +1883,7 @@ public class HeadsetClientStateMachineTest { return 1; } - void setForceSetAudioPolicyProperty(boolean flag){ + void setForceSetAudioPolicyProperty(boolean flag) { mForceSetAudioPolicyProperty = flag; } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HfpNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HfpNativeInterfaceTest.java index 5dc40be3144..f2e887db88f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HfpNativeInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HfpNativeInterfaceTest.java @@ -36,13 +36,11 @@ import org.mockito.junit.MockitoRule; public class HfpNativeInterfaceTest { private static final byte[] TEST_DEVICE_ADDRESS = - new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - HeadsetClientService mService; - @Mock - AdapterService mAdapterService; + @Mock HeadsetClientService mService; + @Mock AdapterService mAdapterService; private NativeInterface mNativeInterface; diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/StackEventTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/StackEventTest.java index 8c82602f344..7aaba84f594 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/StackEventTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/StackEventTest.java @@ -35,10 +35,23 @@ public class StackEventTest { int type = StackEvent.EVENT_TYPE_RING_INDICATION; StackEvent event = new StackEvent(type); - String expectedString = "StackEvent {type:" + StackEvent.eventTypeToString(type) - + ", value1:" + event.valueInt + ", value2:" + event.valueInt2 + ", value3:" - + event.valueInt3 + ", value4:" + event.valueInt4 + ", string: \"" - + event.valueString + "\"" + ", device:" + event.device + "}"; + String expectedString = + "StackEvent {type:" + + StackEvent.eventTypeToString(type) + + ", value1:" + + event.valueInt + + ", value2:" + + event.valueInt2 + + ", value3:" + + event.valueInt3 + + ", value4:" + + event.valueInt4 + + ", string: \"" + + event.valueString + + "\"" + + ", device:" + + event.device + + "}"; assertThat(event.toString()).isEqualTo(expectedString); } @@ -54,8 +67,8 @@ public class StackEventTest { if (t == int.class) { int stackEventType = field.getInt(null); if (fieldName.equals("EVENT_TYPE_UNKNOWN_EVENT")) { - assertThat(StackEvent.eventTypeToString(stackEventType)).isEqualTo( - "EVENT_TYPE_UNKNOWN:" + stackEventType); + assertThat(StackEvent.eventTypeToString(stackEventType)) + .isEqualTo("EVENT_TYPE_UNKNOWN:" + stackEventType); } else { String eventTypeToString = StackEvent.eventTypeToString(stackEventType); assertThat(eventTypeToString).isEqualTo(fieldName); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessorTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessorTest.java index 48428b70447..aa39028d3dc 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessorTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessorTest.java @@ -51,10 +51,8 @@ public class VendorCommandResponseProcessorTest { @Mock private NativeInterface mNativeInterface; private VendorCommandResponseProcessor mProcessor; - @Mock - private AdapterService mAdapterService; - @Mock - private HeadsetClientService mHeadsetClientService; + @Mock private AdapterService mAdapterService; + @Mock private HeadsetClientService mHeadsetClientService; @Before public void setUp() throws Exception { @@ -94,9 +92,14 @@ public class VendorCommandResponseProcessorTest { @Test public void sendCommand_withEqualSign() { String atCommand = "+XAPL="; - doReturn(true).when(mNativeInterface).sendATCmd(mTestDevice, - HeadsetClientHalConstants.HANDSFREECLIENT_AT_CMD_VENDOR_SPECIFIC_CMD, 0, 0, - atCommand); + doReturn(true) + .when(mNativeInterface) + .sendATCmd( + mTestDevice, + HeadsetClientHalConstants.HANDSFREECLIENT_AT_CMD_VENDOR_SPECIFIC_CMD, + 0, + 0, + atCommand); assertThat(mProcessor.sendCommand(TEST_VENDOR_ID, atCommand, mTestDevice)).isTrue(); } @@ -104,9 +107,14 @@ public class VendorCommandResponseProcessorTest { @Test public void sendCommand_withQuestionMarkSign() { String atCommand = "+APLSIRI?"; - doReturn(true).when(mNativeInterface).sendATCmd(mTestDevice, - HeadsetClientHalConstants.HANDSFREECLIENT_AT_CMD_VENDOR_SPECIFIC_CMD, 0, 0, - atCommand); + doReturn(true) + .when(mNativeInterface) + .sendATCmd( + mTestDevice, + HeadsetClientHalConstants.HANDSFREECLIENT_AT_CMD_VENDOR_SPECIFIC_CMD, + 0, + 0, + atCommand); assertThat(mProcessor.sendCommand(TEST_VENDOR_ID, atCommand, mTestDevice)).isTrue(); } @@ -114,9 +122,14 @@ public class VendorCommandResponseProcessorTest { @Test public void sendCommand_failingToSendATCommand() { String atCommand = "+APLSIRI?"; - doReturn(false).when(mNativeInterface).sendATCmd(mTestDevice, - HeadsetClientHalConstants.HANDSFREECLIENT_AT_CMD_VENDOR_SPECIFIC_CMD, 0, 0, - atCommand); + doReturn(false) + .when(mNativeInterface) + .sendATCmd( + mTestDevice, + HeadsetClientHalConstants.HANDSFREECLIENT_AT_CMD_VENDOR_SPECIFIC_CMD, + 0, + 0, + atCommand); assertThat(mProcessor.sendCommand(TEST_VENDOR_ID, atCommand, mTestDevice)).isFalse(); } @@ -148,4 +161,4 @@ public class VendorCommandResponseProcessorTest { assertThat(mProcessor.processEvent(atString, mTestDevice)).isTrue(); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HeadsetClientServiceInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HeadsetClientServiceInterfaceTest.java index 68918e5965e..d7af650d943 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HeadsetClientServiceInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HeadsetClientServiceInterfaceTest.java @@ -45,17 +45,26 @@ import java.util.Set; public class HeadsetClientServiceInterfaceTest { private static final String TEST_DEVICE_ADDRESS = "00:11:22:33:44:55"; private static final BluetoothDevice TEST_DEVICE = - ((BluetoothManager) InstrumentationRegistry.getTargetContext() - .getSystemService(Context.BLUETOOTH_SERVICE)) - .getAdapter().getRemoteDevice(TEST_DEVICE_ADDRESS); + ((BluetoothManager) + InstrumentationRegistry.getTargetContext() + .getSystemService(Context.BLUETOOTH_SERVICE)) + .getAdapter() + .getRemoteDevice(TEST_DEVICE_ADDRESS); private static final String TEST_NUMBER = "000-111-2222"; private static final byte TEST_CODE = 0; private static final int TEST_CALL_INDEX = 0; - private static final HfpClientCall TEST_CALL = new HfpClientCall(TEST_DEVICE, /* id= */ 0, - HfpClientCall.CALL_STATE_ACTIVE, /* number= */ TEST_NUMBER, - /* multiParty= */ false, /* outgoing= */false, /* inBandRing= */true); + private static final HfpClientCall TEST_CALL = + new HfpClientCall( + TEST_DEVICE, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true); private static final int TEST_FLAGS = 0; private static final Bundle TEST_BUNDLE = new Bundle(); + static { TEST_BUNDLE.putInt("test_int", 0); } @@ -80,7 +89,7 @@ public class HeadsetClientServiceInterfaceTest { private void makeHeadsetClientServiceAvailable() { when(mMockHeadsetClientService.isAvailable()).thenReturn(true); assertThat(HeadsetClientService.getHeadsetClientService()) - .isEqualTo(mMockHeadsetClientService); + .isEqualTo(mMockHeadsetClientService); } @Test @@ -97,11 +106,13 @@ public class HeadsetClientServiceInterfaceTest { assertThat(mServiceInterface.enterPrivateMode(TEST_DEVICE, TEST_CALL_INDEX)).isFalse(); makeHeadsetClientServiceAvailable(); - doReturn(false).when(mMockHeadsetClientService) - .enterPrivateMode(TEST_DEVICE, TEST_CALL_INDEX); + doReturn(false) + .when(mMockHeadsetClientService) + .enterPrivateMode(TEST_DEVICE, TEST_CALL_INDEX); assertThat(mServiceInterface.enterPrivateMode(TEST_DEVICE, TEST_CALL_INDEX)).isFalse(); - doReturn(true).when(mMockHeadsetClientService) - .enterPrivateMode(TEST_DEVICE, TEST_CALL_INDEX); + doReturn(true) + .when(mMockHeadsetClientService) + .enterPrivateMode(TEST_DEVICE, TEST_CALL_INDEX); assertThat(mServiceInterface.enterPrivateMode(TEST_DEVICE, TEST_CALL_INDEX)).isTrue(); } @@ -121,10 +132,12 @@ public class HeadsetClientServiceInterfaceTest { assertThat(mServiceInterface.terminateCall(TEST_DEVICE, TEST_CALL)).isFalse(); makeHeadsetClientServiceAvailable(); - doReturn(true).when(mMockHeadsetClientService) + doReturn(true) + .when(mMockHeadsetClientService) .terminateCall(TEST_DEVICE, TEST_CALL.getUUID()); assertThat(mServiceInterface.terminateCall(TEST_DEVICE, TEST_CALL)).isTrue(); - doReturn(false).when(mMockHeadsetClientService) + doReturn(false) + .when(mMockHeadsetClientService) .terminateCall(TEST_DEVICE, TEST_CALL.getUUID()); assertThat(mServiceInterface.terminateCall(TEST_DEVICE, TEST_CALL)).isFalse(); } @@ -237,4 +250,3 @@ public class HeadsetClientServiceInterfaceTest { assertThat(mServiceInterface.hasHfpClientEcc(TEST_DEVICE)).isTrue(); } } - diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java index 8278a40e8f4..4e73a36b7fb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java @@ -33,15 +33,24 @@ import org.junit.runner.RunWith; public class HfpClientCallTest { private static final String TEST_DEVICE_ADDRESS = "00:11:22:33:44:55"; private static final BluetoothDevice TEST_DEVICE = - ((BluetoothManager) InstrumentationRegistry.getTargetContext() - .getSystemService(Context.BLUETOOTH_SERVICE)) - .getAdapter().getRemoteDevice(TEST_DEVICE_ADDRESS); + ((BluetoothManager) + InstrumentationRegistry.getTargetContext() + .getSystemService(Context.BLUETOOTH_SERVICE)) + .getAdapter() + .getRemoteDevice(TEST_DEVICE_ADDRESS); private static final int TEST_ID = 0; private static final String TEST_NUMBER = "000-111-2222"; private static final String TEST_NUMBER_2 = "111-222-3333"; - private void assertCall(BluetoothDevice device, int id, int state, String number, - boolean isMultiParty, boolean isOutgoing, boolean isInBandRing, HfpClientCall call) { + private void assertCall( + BluetoothDevice device, + int id, + int state, + String number, + boolean isMultiParty, + boolean isOutgoing, + boolean isInBandRing, + HfpClientCall call) { assertThat(call).isNotNull(); assertThat(call.getDevice()).isEqualTo(device); assertThat(call.getId()).isEqualTo(id); @@ -58,189 +67,306 @@ public class HfpClientCallTest { @Test public void testCreateActiveCall() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ true, - /* inBandRing= */ false); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, false, true, - false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ false); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + false, + true, + false, + call); } @Test public void testCreateHeldCall() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_HELD, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ true, - /* inBandRing= */ false); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_HELD, TEST_NUMBER, false, true, - false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_HELD, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ false); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_HELD, + TEST_NUMBER, + false, + true, + false, + call); } @Test public void testCreateDialingCall() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_DIALING, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ true, - /* inBandRing= */ false); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_DIALING, TEST_NUMBER, false, true, - false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_DIALING, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ false); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_DIALING, + TEST_NUMBER, + false, + true, + false, + call); } @Test public void testCreateAlertingCall() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_ALERTING, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ true, - /* inBandRing= */ false); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ALERTING, TEST_NUMBER, false, - true, false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_ALERTING, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ false); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ALERTING, + TEST_NUMBER, + false, + true, + false, + call); } @Test public void testCreateIncomingCall() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_INCOMING, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ false, - /* inBandRing= */ false); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_INCOMING, TEST_NUMBER, false, - false, false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_INCOMING, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ false); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_INCOMING, + TEST_NUMBER, + false, + false, + false, + call); } @Test public void testCreateWaitingCall() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_WAITING, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ false, - /* inBandRing= */ false); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_WAITING, TEST_NUMBER, false, - false, false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_WAITING, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ false); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_WAITING, + TEST_NUMBER, + false, + false, + false, + call); } @Test public void testCreateHeldByResponseAndHoldCall() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ false, - /* inBandRing= */ false); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD, - TEST_NUMBER, false, false, false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ false); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD, + TEST_NUMBER, + false, + false, + false, + call); } @Test public void testCreateTerminatedCall() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_TERMINATED, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ false, - /* inBandRing= */ false); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_TERMINATED, TEST_NUMBER, false, - false, false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_TERMINATED, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ false); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_TERMINATED, + TEST_NUMBER, + false, + false, + false, + call); } @Test public void testSetState() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ true, - /* inBandRing= */ false); - - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, false, true, - false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ false); + + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + false, + true, + false, + call); call.setState(HfpClientCall.CALL_STATE_HELD); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_HELD, TEST_NUMBER, false, true, - false, call); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_HELD, + TEST_NUMBER, + false, + true, + false, + call); } @Test public void testSetNumber() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ true, - /* inBandRing= */ false); - - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, false, true, - false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ false); + + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + false, + true, + false, + call); call.setNumber(TEST_NUMBER_2); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER_2, false, - true, false, call); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER_2, + false, + true, + false, + call); } @Test public void testSetMultiParty() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ true, - /* inBandRing= */ false); - - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, false, true, - false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ false); + + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + false, + true, + false, + call); call.setMultiParty(true); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, true, true, - false, call); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + true, + true, + false, + call); } @Test public void testParcelable() { - HfpClientCall call = new HfpClientCall( - /* device= */ TEST_DEVICE, - /* call id= */ TEST_ID, - /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, - /* phone number= */ TEST_NUMBER, - /* multiParty= */ false, - /* outgoing= */ true, - /* inBandRing= */ false); - - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, false, true, - false, call); + HfpClientCall call = + new HfpClientCall( + /* device= */ TEST_DEVICE, + /* call id= */ TEST_ID, + /* call state= */ HfpClientCall.CALL_STATE_ACTIVE, + /* phone number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ false); + + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + false, + true, + false, + call); Parcel parcel = Parcel.obtain(); call.writeToParcel(parcel, 0 /* flags */); @@ -248,8 +374,15 @@ public class HfpClientCallTest { HfpClientCall callOut = HfpClientCall.CREATOR.createFromParcel(parcel); parcel.recycle(); - assertCall(TEST_DEVICE, TEST_ID, HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, false, true, - false, callOut); + assertCall( + TEST_DEVICE, + TEST_ID, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + false, + true, + false, + callOut); assertThat(HfpClientCall.CREATOR.newArray(5).length).isEqualTo(5); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java index a4258951d67..c3ebab4c974 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java @@ -64,9 +64,11 @@ import java.util.List; public class HfpClientConnectionServiceTest { private static final String TEST_DEVICE_ADDRESS = "00:11:22:33:44:55"; private static final BluetoothDevice TEST_DEVICE = - ((BluetoothManager) InstrumentationRegistry.getTargetContext() - .getSystemService(Context.BLUETOOTH_SERVICE)) - .getAdapter().getRemoteDevice(TEST_DEVICE_ADDRESS); + ((BluetoothManager) + InstrumentationRegistry.getTargetContext() + .getSystemService(Context.BLUETOOTH_SERVICE)) + .getAdapter() + .getRemoteDevice(TEST_DEVICE_ADDRESS); private static final String TEST_NUMBER = "000-111-2222"; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @@ -100,24 +102,31 @@ public class HfpClientConnectionServiceTest { // attachBaseContext, but until we need a full context this is simpler. mHfpClientConnectionService = spy(new HfpClientConnectionService()); - doReturn("com.android.bluetooth.hfpclient").when(mHfpClientConnectionService) + doReturn("com.android.bluetooth.hfpclient") + .when(mHfpClientConnectionService) .getPackageName(); - doReturn(mHfpClientConnectionService).when(mHfpClientConnectionService) + doReturn(mHfpClientConnectionService) + .when(mHfpClientConnectionService) .getApplicationContext(); doReturn(mMockResources).when(mHfpClientConnectionService).getResources(); - doReturn(true).when(mMockResources) + doReturn(true) + .when(mMockResources) .getBoolean(R.bool.hfp_client_connection_service_support_emergency_call); - doReturn(Context.TELECOM_SERVICE).when(mHfpClientConnectionService) + doReturn(Context.TELECOM_SERVICE) + .when(mHfpClientConnectionService) .getSystemServiceName(TelecomManager.class); - doReturn(mMockTelecomManager).when(mHfpClientConnectionService) + doReturn(mMockTelecomManager) + .when(mHfpClientConnectionService) .getSystemService(Context.TELECOM_SERVICE); doReturn(getPhoneAccount(TEST_DEVICE)).when(mMockTelecomManager).getPhoneAccount(any()); - doReturn(Context.BLUETOOTH_SERVICE).when(mHfpClientConnectionService) + doReturn(Context.BLUETOOTH_SERVICE) + .when(mHfpClientConnectionService) .getSystemServiceName(BluetoothManager.class); doReturn(targetContext.getSystemService(BluetoothManager.class)) - .when(mHfpClientConnectionService).getSystemService(Context.BLUETOOTH_SERVICE); + .when(mHfpClientConnectionService) + .getSystemService(Context.BLUETOOTH_SERVICE); } @After @@ -130,8 +139,9 @@ public class HfpClientConnectionServiceTest { } private PhoneAccountHandle getPhoneAccountHandle(BluetoothDevice device) { - return new PhoneAccountHandle(new ComponentName(mHfpClientConnectionService, - HfpClientConnectionService.class), device.getAddress()); + return new PhoneAccountHandle( + new ComponentName(mHfpClientConnectionService, HfpClientConnectionService.class), + device.getAddress()); } private PhoneAccount getPhoneAccount(BluetoothDevice device) { @@ -145,8 +155,8 @@ public class HfpClientConnectionServiceTest { } private void setupDeviceConnection(BluetoothDevice device) throws Exception { - mHfpClientConnectionService.onConnectionStateChanged(device, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); + mHfpClientConnectionService.onConnectionStateChanged( + device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); HfpClientDeviceBlock block = mHfpClientConnectionService.findBlockForDevice(TEST_DEVICE); assertThat(block).isNotNull(); assertThat(block.getDevice()).isEqualTo(TEST_DEVICE); @@ -171,8 +181,8 @@ public class HfpClientConnectionServiceTest { public void disconnectDevice_blockIsRemoved() throws Exception { createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientConnectionService.onConnectionStateChanged(TEST_DEVICE, - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); + HfpClientConnectionService.onConnectionStateChanged( + TEST_DEVICE, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); assertThat(mHfpClientConnectionService.findBlockForDevice(TEST_DEVICE)).isNull(); } @@ -180,9 +190,15 @@ public class HfpClientConnectionServiceTest { public void callChanged_callAdded() throws Exception { createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientCall call = new HfpClientCall(TEST_DEVICE, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, /* number= */ TEST_NUMBER, - /* multiParty= */ false, /* outgoing= */false, /* inBandRing= */true); + HfpClientCall call = + new HfpClientCall( + TEST_DEVICE, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true); HfpClientConnectionService.onCallChanged(TEST_DEVICE, call); HfpClientDeviceBlock block = mHfpClientConnectionService.findBlockForDevice(TEST_DEVICE); assertThat(block).isNotNull(); @@ -194,7 +210,8 @@ public class HfpClientConnectionServiceTest { public void audioStateChanged_scoStateChanged() throws Exception { createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientConnectionService.onAudioStateChanged(TEST_DEVICE, + HfpClientConnectionService.onAudioStateChanged( + TEST_DEVICE, HeadsetClientHalConstants.AUDIO_STATE_CONNECTED, HeadsetClientHalConstants.AUDIO_STATE_CONNECTING); HfpClientDeviceBlock block = mHfpClientConnectionService.findBlockForDevice(TEST_DEVICE); @@ -209,21 +226,27 @@ public class HfpClientConnectionServiceTest { createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientCall call = new HfpClientCall(TEST_DEVICE, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, /* number= */ TEST_NUMBER, - /* multiParty= */ false, /* outgoing= */false, /* inBandRing= */true); + HfpClientCall call = + new HfpClientCall( + TEST_DEVICE, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true); Bundle extras = new Bundle(); - extras.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, - new ParcelUuid(call.getUUID())); - ConnectionRequest connectionRequest = new ConnectionRequest.Builder().setExtras( - extras).build(); + extras.putParcelable( + TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = + new ConnectionRequest.Builder().setExtras(extras).build(); HfpClientConnectionService.onCallChanged(TEST_DEVICE, call); - Connection connection = mHfpClientConnectionService.onCreateIncomingConnection( - getPhoneAccountHandle(TEST_DEVICE), - connectionRequest); + Connection connection = + mHfpClientConnectionService.onCreateIncomingConnection( + getPhoneAccountHandle(TEST_DEVICE), connectionRequest); assertThat(connection).isNotNull(); assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(TEST_DEVICE); @@ -235,22 +258,30 @@ public class HfpClientConnectionServiceTest { createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientCall call = new HfpClientCall(TEST_DEVICE, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, /* number= */ TEST_NUMBER, - /* multiParty= */ false, /* outgoing= */true, /* inBandRing= */true); + HfpClientCall call = + new HfpClientCall( + TEST_DEVICE, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ true); doReturn(call).when(mMockHeadsetClientService).dial(TEST_DEVICE, TEST_NUMBER); Bundle extras = new Bundle(); - extras.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, - new ParcelUuid(call.getUUID())); - ConnectionRequest connectionRequest = new ConnectionRequest.Builder().setExtras( - extras).setAddress(Uri.fromParts( - PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)).build(); - - Connection connection = mHfpClientConnectionService.onCreateOutgoingConnection( - getPhoneAccountHandle(TEST_DEVICE), - connectionRequest); + extras.putParcelable( + TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = + new ConnectionRequest.Builder() + .setExtras(extras) + .setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) + .build(); + + Connection connection = + mHfpClientConnectionService.onCreateOutgoingConnection( + getPhoneAccountHandle(TEST_DEVICE), connectionRequest); assertThat(connection).isNotNull(); assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(TEST_DEVICE); @@ -262,22 +293,30 @@ public class HfpClientConnectionServiceTest { createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientCall call = new HfpClientCall(TEST_DEVICE, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, /* number= */ TEST_NUMBER, - /* multiParty= */ false, /* outgoing= */true, /* inBandRing= */true); + HfpClientCall call = + new HfpClientCall( + TEST_DEVICE, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ true); Bundle extras = new Bundle(); - extras.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, - new ParcelUuid(call.getUUID())); - ConnectionRequest connectionRequest = new ConnectionRequest.Builder().setExtras( - extras).setAddress(Uri.fromParts( - PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)).build(); + extras.putParcelable( + TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = + new ConnectionRequest.Builder() + .setExtras(extras) + .setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) + .build(); HfpClientConnectionService.onCallChanged(TEST_DEVICE, call); - Connection connection = mHfpClientConnectionService.onCreateUnknownConnection( - getPhoneAccountHandle(TEST_DEVICE), - connectionRequest); + Connection connection = + mHfpClientConnectionService.onCreateUnknownConnection( + getPhoneAccountHandle(TEST_DEVICE), connectionRequest); assertThat(connection).isNotNull(); assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(TEST_DEVICE); @@ -285,82 +324,101 @@ public class HfpClientConnectionServiceTest { } @Test - public void onCreateIncomingConnection_phoneAccountIsNull_returnsNull() throws Exception{ + public void onCreateIncomingConnection_phoneAccountIsNull_returnsNull() throws Exception { doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientCall call = new HfpClientCall(TEST_DEVICE, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, /* number= */ TEST_NUMBER, - /* multiParty= */ false, /* outgoing= */false, /* inBandRing= */true); + HfpClientCall call = + new HfpClientCall( + TEST_DEVICE, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true); Bundle extras = new Bundle(); - extras.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, - new ParcelUuid(call.getUUID())); - ConnectionRequest connectionRequest = new ConnectionRequest.Builder().setExtras( - extras).build(); + extras.putParcelable( + TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = + new ConnectionRequest.Builder().setExtras(extras).build(); HfpClientConnectionService.onCallChanged(TEST_DEVICE, call); - Connection connection = mHfpClientConnectionService.onCreateIncomingConnection( - getPhoneAccountHandle(TEST_DEVICE), - connectionRequest); + Connection connection = + mHfpClientConnectionService.onCreateIncomingConnection( + getPhoneAccountHandle(TEST_DEVICE), connectionRequest); assertThat(connection).isNull(); } - @Test - public void onCreateOutgoingConnection_phoneAccountIsNull_returnsNull() throws Exception{ + public void onCreateOutgoingConnection_phoneAccountIsNull_returnsNull() throws Exception { doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientCall call = new HfpClientCall(TEST_DEVICE, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, /* number= */ TEST_NUMBER, - /* multiParty= */ false, /* outgoing= */true, /* inBandRing= */true); + HfpClientCall call = + new HfpClientCall( + TEST_DEVICE, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ true); doReturn(call).when(mMockHeadsetClientService).dial(TEST_DEVICE, TEST_NUMBER); Bundle extras = new Bundle(); - extras.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, - new ParcelUuid(call.getUUID())); - ConnectionRequest connectionRequest = new ConnectionRequest.Builder().setExtras( - extras).setAddress(Uri.fromParts( - PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)).build(); - - Connection connection = mHfpClientConnectionService.onCreateOutgoingConnection( - getPhoneAccountHandle(TEST_DEVICE), - connectionRequest); + extras.putParcelable( + TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = + new ConnectionRequest.Builder() + .setExtras(extras) + .setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) + .build(); + + Connection connection = + mHfpClientConnectionService.onCreateOutgoingConnection( + getPhoneAccountHandle(TEST_DEVICE), connectionRequest); assertThat(connection).isNull(); } - @Test - public void onCreateUnknownConnection_phoneAccountIsNull_returnsNull() throws Exception{ + public void onCreateUnknownConnection_phoneAccountIsNull_returnsNull() throws Exception { doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); createService(); setupDeviceConnection(TEST_DEVICE); - HfpClientCall call = new HfpClientCall(TEST_DEVICE, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, /* number= */ TEST_NUMBER, - /* multiParty= */ false, /* outgoing= */true, /* inBandRing= */true); + HfpClientCall call = + new HfpClientCall( + TEST_DEVICE, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ true); Bundle extras = new Bundle(); - extras.putParcelable(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, - new ParcelUuid(call.getUUID())); - ConnectionRequest connectionRequest = new ConnectionRequest.Builder().setExtras( - extras).setAddress(Uri.fromParts( - PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)).build(); + extras.putParcelable( + TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = + new ConnectionRequest.Builder() + .setExtras(extras) + .setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) + .build(); HfpClientConnectionService.onCallChanged(TEST_DEVICE, call); - Connection connection = mHfpClientConnectionService.onCreateUnknownConnection( - getPhoneAccountHandle(TEST_DEVICE), - connectionRequest); + Connection connection = + mHfpClientConnectionService.onCreateUnknownConnection( + getPhoneAccountHandle(TEST_DEVICE), connectionRequest); assertThat(connection).isNull(); } - } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java index 76d3552ca6e..e7e0f415e30 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java @@ -49,8 +49,7 @@ import java.util.Set; @MediumTest @RunWith(MockitoJUnitRunner.class) public class HfpClientConnectionTest { - @Rule - public MockitoRule rule = MockitoJUnit.rule(); + @Rule public MockitoRule rule = MockitoJUnit.rule(); private static final String EVENT_SCO_CONNECT = "com.android.bluetooth.hfpclient.SCO_CONNECT"; private static final String EVENT_SCO_DISCONNECT = @@ -63,20 +62,23 @@ public class HfpClientConnectionTest { private BluetoothDevice mBluetoothDevice; private HfpClientCall mCall; - @Mock - private HeadsetClientServiceInterface mMockServiceInterface; - @Mock - private Context mContext; - @Mock - private HfpClientConnectionService mHfpClientConnectionService; + @Mock private HeadsetClientServiceInterface mMockServiceInterface; + @Mock private Context mContext; + @Mock private HfpClientConnectionService mHfpClientConnectionService; @Before public void setUp() { - mBluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice( - TEST_DEVICE_ADDRESS); - mCall = new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, /* multiParty= */ - false, /* outgoing= */false, /* inBandRing= */true); + mBluetoothDevice = + BluetoothAdapter.getDefaultAdapter().getRemoteDevice(TEST_DEVICE_ADDRESS); + mCall = + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true); } @Test @@ -88,15 +90,18 @@ public class HfpClientConnectionTest { assertThat(mHfpClientConnection.getUUID()).isEqualTo(mCall.getUUID()); assertThat(mHfpClientConnection.getState()).isEqualTo(Connection.STATE_ACTIVE); assertThat(mHfpClientConnection.getAudioModeIsVoip()).isFalse(); - assertThat(mHfpClientConnection.getAddress()).isEqualTo( - Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, /* fragment= */ null)); - assertThat(mHfpClientConnection.getAddressPresentation()).isEqualTo( - TelecomManager.PRESENTATION_ALLOWED); - assertThat(mHfpClientConnection.getConnectionCapabilities()).isEqualTo( - Connection.CAPABILITY_SUPPORT_HOLD | Connection.CAPABILITY_MUTE - | Connection.CAPABILITY_SEPARATE_FROM_CONFERENCE - | Connection.CAPABILITY_DISCONNECT_FROM_CONFERENCE - | Connection.CAPABILITY_HOLD); + assertThat(mHfpClientConnection.getAddress()) + .isEqualTo( + Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, /* fragment= */ null)); + assertThat(mHfpClientConnection.getAddressPresentation()) + .isEqualTo(TelecomManager.PRESENTATION_ALLOWED); + assertThat(mHfpClientConnection.getConnectionCapabilities()) + .isEqualTo( + Connection.CAPABILITY_SUPPORT_HOLD + | Connection.CAPABILITY_MUTE + | Connection.CAPABILITY_SEPARATE_FROM_CONFERENCE + | Connection.CAPABILITY_DISCONNECT_FROM_CONFERENCE + | Connection.CAPABILITY_HOLD); } @Test @@ -111,15 +116,17 @@ public class HfpClientConnectionTest { assertThat(mHfpClientConnection.getExtras()).isNull(); assertThat(mHfpClientConnection.getState()).isEqualTo(Connection.STATE_DIALING); assertThat(mHfpClientConnection.getAudioModeIsVoip()).isFalse(); - assertThat(mHfpClientConnection.getAddress()).isEqualTo( - Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, /* fragment= */ null)); - assertThat(mHfpClientConnection.getAddressPresentation()).isEqualTo( - TelecomManager.PRESENTATION_ALLOWED); - assertThat(mHfpClientConnection.getConnectionCapabilities()).isEqualTo( - Connection.CAPABILITY_SUPPORT_HOLD | Connection.CAPABILITY_MUTE - | Connection.CAPABILITY_SEPARATE_FROM_CONFERENCE - | Connection.CAPABILITY_DISCONNECT_FROM_CONFERENCE); - + assertThat(mHfpClientConnection.getAddress()) + .isEqualTo( + Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, /* fragment= */ null)); + assertThat(mHfpClientConnection.getAddressPresentation()) + .isEqualTo(TelecomManager.PRESENTATION_ALLOWED); + assertThat(mHfpClientConnection.getConnectionCapabilities()) + .isEqualTo( + Connection.CAPABILITY_SUPPORT_HOLD + | Connection.CAPABILITY_MUTE + | Connection.CAPABILITY_SEPARATE_FROM_CONFERENCE + | Connection.CAPABILITY_DISCONNECT_FROM_CONFERENCE); } @Test @@ -136,11 +143,18 @@ public class HfpClientConnectionTest { @Test public void multiPartyCallOnAddedNotDisconnected_isInConference() { - mHfpClientConnection = createHfpClientConnectionWithExistingCall() - .setCall(new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, - "444-555-6666", /* multiParty= */true, /* outgoing= */ - false, /* inBandRing= */true)).build(); + mHfpClientConnection = + createHfpClientConnectionWithExistingCall() + .setCall( + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + "444-555-6666", + /* multiParty= */ true, + /* outgoing= */ false, + /* inBandRing= */ true)) + .build(); mHfpClientConnection.onAdded(); assertThat(mHfpClientConnection.inConference()).isTrue(); @@ -156,22 +170,36 @@ public class HfpClientConnectionTest { @Test public void multiPartyCallNotAddedNotDisconnected_notInConference() { - mHfpClientConnection = createHfpClientConnectionWithExistingCall() - .setCall(new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, - "444-555-6666", /* multiParty= */true, /* outgoing= */ - false, /* inBandRing= */true)).build(); + mHfpClientConnection = + createHfpClientConnectionWithExistingCall() + .setCall( + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + "444-555-6666", + /* multiParty= */ true, + /* outgoing= */ false, + /* inBandRing= */ true)) + .build(); assertThat(mHfpClientConnection.inConference()).isFalse(); } @Test public void multiPartyCallOnAddedDisconnected_notInConference() { - mHfpClientConnection = createHfpClientConnectionWithExistingCall() - .setCall(new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, - "444-555-6666", /* multiParty= */true, /* outgoing= */ - false, /* inBandRing= */true)).build(); + mHfpClientConnection = + createHfpClientConnectionWithExistingCall() + .setCall( + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + "444-555-6666", + /* multiParty= */ true, + /* outgoing= */ false, + /* inBandRing= */ true)) + .build(); mHfpClientConnection.onAdded(); mHfpClientConnection.setDisconnected(new DisconnectCause(DisconnectCause.LOCAL)); @@ -193,10 +221,14 @@ public class HfpClientConnectionTest { assertThat(mHfpClientConnection.getCall()).isEqualTo(mCall); HfpClientCall newCall = - new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, - TEST_NUMBER_2, /* multiParty= */false, /* outgoing= */ - false, /* inBandRing= */true); + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER_2, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true); mHfpClientConnection.updateCall(newCall); assertThat(mHfpClientConnection.getCall()).isEqualTo(newCall); @@ -226,8 +258,7 @@ public class HfpClientConnectionTest { @Test public void handleCallChanged_heldByResponseAndHold() { mHfpClientConnection = createHfpClientConnectionWithExistingCall().build(); - mHfpClientConnection.getCall() - .setState(HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD); + mHfpClientConnection.getCall().setState(HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD); mHfpClientConnection.handleCallChanged(); assertThat(mHfpClientConnection.getState()).isEqualTo(Connection.STATE_HOLDING); @@ -239,8 +270,7 @@ public class HfpClientConnectionTest { mHfpClientConnection = createHfpClientConnectionWithExistingCall().build(); HfpClientConference mockConference = mock(HfpClientConference.class); mHfpClientConnection.setConference(mockConference); - mHfpClientConnection.getCall() - .setState(HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD); + mHfpClientConnection.getCall().setState(HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD); mHfpClientConnection.handleCallChanged(); verify(mockConference).setOnHold(); @@ -397,31 +427,38 @@ public class HfpClientConnectionTest { @Ignore("b/191783947") public void onUnhold_connectionServiceHasOneConnection_acceptsHeldCall() { mHfpClientConnection = createHfpClientConnectionWithExistingCall().build(); - when(mHfpClientConnectionService.getAllConnections()).thenReturn( - Set.of(mHfpClientConnection)); + when(mHfpClientConnectionService.getAllConnections()) + .thenReturn(Set.of(mHfpClientConnection)); mHfpClientConnection.onUnhold(); - verify(mMockServiceInterface).acceptCall(mBluetoothDevice, - HeadsetClientServiceInterface.CALL_ACCEPT_HOLD); + verify(mMockServiceInterface) + .acceptCall(mBluetoothDevice, HeadsetClientServiceInterface.CALL_ACCEPT_HOLD); } @Test @Ignore("b/191783947") public void onUnhold_connectionServiceHasMultipleConnections_doesNotAcceptHeldCall() { mHfpClientConnection = createHfpClientConnectionWithExistingCall().build(); - HfpClientConnection secondConnection = createHfpClientConnectionWithExistingCall() - .setCall(new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, - "444-555-6666", /* multiParty= */false, /* outgoing= */ - false, /* inBandRing= */true)).build(); - when(mHfpClientConnectionService.getAllConnections()).thenReturn( - Set.of(mHfpClientConnection, secondConnection)); + HfpClientConnection secondConnection = + createHfpClientConnectionWithExistingCall() + .setCall( + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + "444-555-6666", + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true)) + .build(); + when(mHfpClientConnectionService.getAllConnections()) + .thenReturn(Set.of(mHfpClientConnection, secondConnection)); mHfpClientConnection.onUnhold(); - verify(mMockServiceInterface, never()).acceptCall(mBluetoothDevice, - HeadsetClientServiceInterface.CALL_ACCEPT_HOLD); + verify(mMockServiceInterface, never()) + .acceptCall(mBluetoothDevice, HeadsetClientServiceInterface.CALL_ACCEPT_HOLD); } @Test @@ -430,8 +467,8 @@ public class HfpClientConnectionTest { mHfpClientConnection.onAnswer(); - verify(mMockServiceInterface).acceptCall(mBluetoothDevice, - HeadsetClientServiceInterface.CALL_ACCEPT_NONE); + verify(mMockServiceInterface) + .acceptCall(mBluetoothDevice, HeadsetClientServiceInterface.CALL_ACCEPT_NONE); } @Test @@ -501,8 +538,8 @@ public class HfpClientConnectionTest { @Override public HfpClientConnection build() { - return new HfpClientConnection(mBluetoothDevice, mCall, mHfpClientConnectionService, - mMockServiceInterface); + return new HfpClientConnection( + mBluetoothDevice, mCall, mHfpClientConnectionService, mMockServiceInterface); } } @@ -516,8 +553,11 @@ public class HfpClientConnectionTest { @Override public HfpClientConnection build() { - return new HfpClientConnection(mBluetoothDevice, Uri.parse(mNumber), - mHfpClientConnectionService, mMockServiceInterface); + return new HfpClientConnection( + mBluetoothDevice, + Uri.parse(mNumber), + mHfpClientConnectionService, + mMockServiceInterface); } } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java index c30e2b86a34..e92dd5dc593 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java @@ -51,18 +51,12 @@ public class HfpClientDeviceBlockTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private HeadsetClientService mHeadsetClientService; - @Mock - private HfpClientConnectionService mConnServ; - @Mock - private HeadsetClientServiceInterface mMockServiceInterface; - @Mock - private Context mApplicationContext; - @Mock - private Resources mResources; - @Mock - private TelecomManager mTelecomManager; + @Mock private HeadsetClientService mHeadsetClientService; + @Mock private HfpClientConnectionService mConnServ; + @Mock private HeadsetClientServiceInterface mMockServiceInterface; + @Mock private Context mApplicationContext; + @Mock private Resources mResources; + @Mock private TelecomManager mTelecomManager; private HfpClientDeviceBlock mHfpClientDeviceBlock; private BluetoothDevice mBluetoothDevice; @@ -73,8 +67,10 @@ public class HfpClientDeviceBlockTest { // HfpClientConnectionService.createAccount is static and can't be mocked, so the // application context and resources must be mocked to avoid NPE when creating an // HfpClientDeviceBlock for testing. - when(mResources.getBoolean(com.android.bluetooth.R.bool - .hfp_client_connection_service_support_emergency_call)).thenReturn(true); + when(mResources.getBoolean( + com.android.bluetooth.R.bool + .hfp_client_connection_service_support_emergency_call)) + .thenReturn(true); when(mApplicationContext.getResources()).thenReturn(mResources); when(mConnServ.getApplicationContext()).thenReturn(mApplicationContext); when(mConnServ.getPackageName()).thenReturn(TEST_PACKAGE); @@ -83,8 +79,8 @@ public class HfpClientDeviceBlockTest { when(mConnServ.getSystemServiceName(TelecomManager.class)) .thenReturn(Context.TELECOM_SERVICE); - mBluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice( - TEST_DEVICE_ADDRESS); + mBluetoothDevice = + BluetoothAdapter.getDefaultAdapter().getRemoteDevice(TEST_DEVICE_ADDRESS); when(mHeadsetClientService.isAvailable()).thenReturn(true); HeadsetClientService.setHeadsetClientService(mHeadsetClientService); @@ -92,11 +88,18 @@ public class HfpClientDeviceBlockTest { @Test public void testCreateOutgoingConnection_scoStateIsSet() { - setUpCall(new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, - /* multiParty= */false, /* outgoing= */false, /* inBandRing= */true)); - HfpClientConnection connection = createOutgoingConnectionWithScoState( - HeadsetClientHalConstants.AUDIO_STATE_CONNECTED); + setUpCall( + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true)); + HfpClientConnection connection = + createOutgoingConnectionWithScoState( + HeadsetClientHalConstants.AUDIO_STATE_CONNECTED); assertThat(connection.getExtras().getInt(KEY_SCO_STATE)) .isEqualTo(HeadsetClientHalConstants.AUDIO_STATE_CONNECTED); @@ -104,15 +107,23 @@ public class HfpClientDeviceBlockTest { @Test public void testOnAudioStateChanged() { - setUpCall(new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, - /* multiParty= */false, /* outgoing= */false, /* inBandRing= */true)); - HfpClientConnection connection = createOutgoingConnectionWithScoState( - HeadsetClientHalConstants.AUDIO_STATE_CONNECTED); + setUpCall( + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true)); + HfpClientConnection connection = + createOutgoingConnectionWithScoState( + HeadsetClientHalConstants.AUDIO_STATE_CONNECTED); assertThat(connection.getExtras().getInt(KEY_SCO_STATE)) .isEqualTo(HeadsetClientHalConstants.AUDIO_STATE_CONNECTED); - mHfpClientDeviceBlock.onAudioStateChange(HeadsetClientHalConstants.AUDIO_STATE_DISCONNECTED, + mHfpClientDeviceBlock.onAudioStateChange( + HeadsetClientHalConstants.AUDIO_STATE_DISCONNECTED, HeadsetClientHalConstants.AUDIO_STATE_CONNECTED); assertThat(connection.getExtras().getInt(KEY_SCO_STATE)) @@ -123,9 +134,14 @@ public class HfpClientDeviceBlockTest { @Ignore("b/191783947") public void testHandleMultiPartyCall_scoStateIsSetOnConference() { HfpClientCall call = - new HfpClientCall(mBluetoothDevice, /* id= */0, - HfpClientCall.CALL_STATE_ACTIVE, TEST_NUMBER, /* multiParty= */ - true, /* outgoing= */false, /* inBandRing= */true); + new HfpClientCall( + mBluetoothDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + TEST_NUMBER, + /* multiParty= */ true, + /* outgoing= */ false, + /* inBandRing= */ true); setUpCall(call); createOutgoingConnectionWithScoState(HeadsetClientHalConstants.AUDIO_STATE_CONNECTING); @@ -147,9 +163,7 @@ public class HfpClientDeviceBlockTest { private HfpClientConnection createOutgoingConnectionWithScoState(int scoState) { when(mHeadsetClientService.getAudioState(mBluetoothDevice)).thenReturn(scoState); - doCallRealMethod() - .when(mConnServ) - .createAccount(any()); + doCallRealMethod().when(mConnServ).createAccount(any()); mHfpClientDeviceBlock = new HfpClientDeviceBlock(mBluetoothDevice, mConnServ, mMockServiceInterface); return mHfpClientDeviceBlock.onCreateOutgoingConnection( diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java index 86396c0f120..fac59958d8d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java @@ -44,8 +44,7 @@ public class BluetoothHidDeviceBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private HidDeviceService mService; + @Mock private HidDeviceService mService; private AttributionSource mAttributionSource; private BluetoothDevice mTestDevice; private HidDeviceService.BluetoothHidDeviceBinder mBinder; @@ -71,20 +70,31 @@ public class BluetoothHidDeviceBinderTest { String provider = "test-provider"; byte subclass = 1; byte[] descriptors = new byte[] {10}; - BluetoothHidDeviceAppSdpSettings sdp = new BluetoothHidDeviceAppSdpSettings( - name, description, provider, subclass, descriptors); + BluetoothHidDeviceAppSdpSettings sdp = + new BluetoothHidDeviceAppSdpSettings( + name, description, provider, subclass, descriptors); int tokenRate = 800; int tokenBucketSize = 9; int peakBandwidth = 10; int latency = 11250; int delayVariation = BluetoothHidDeviceAppQosSettings.MAX; - BluetoothHidDeviceAppQosSettings inQos = new BluetoothHidDeviceAppQosSettings( - BluetoothHidDeviceAppQosSettings.SERVICE_BEST_EFFORT, tokenRate, - tokenBucketSize, peakBandwidth, latency, delayVariation); - BluetoothHidDeviceAppQosSettings outQos = new BluetoothHidDeviceAppQosSettings( - BluetoothHidDeviceAppQosSettings.SERVICE_BEST_EFFORT, tokenRate, - tokenBucketSize, peakBandwidth, latency, delayVariation); + BluetoothHidDeviceAppQosSettings inQos = + new BluetoothHidDeviceAppQosSettings( + BluetoothHidDeviceAppQosSettings.SERVICE_BEST_EFFORT, + tokenRate, + tokenBucketSize, + peakBandwidth, + latency, + delayVariation); + BluetoothHidDeviceAppQosSettings outQos = + new BluetoothHidDeviceAppQosSettings( + BluetoothHidDeviceAppQosSettings.SERVICE_BEST_EFFORT, + tokenRate, + tokenBucketSize, + peakBandwidth, + latency, + delayVariation); IBluetoothHidDeviceCallback cb = mock(IBluetoothHidDeviceCallback.class); mBinder.registerApp(sdp, inQos, outQos, cb, mAttributionSource); @@ -100,7 +110,7 @@ public class BluetoothHidDeviceBinderTest { @Test public void sendReport() { int id = 100; - byte[] data = new byte[] { 0x00, 0x01 }; + byte[] data = new byte[] {0x00, 0x01}; mBinder.sendReport(mTestDevice, id, data, mAttributionSource); verify(mService).sendReport(mTestDevice, id, data); } @@ -109,7 +119,7 @@ public class BluetoothHidDeviceBinderTest { public void replyReport() { byte type = 0; byte id = 100; - byte[] data = new byte[] { 0x00, 0x01 }; + byte[] data = new byte[] {0x00, 0x01}; mBinder.replyReport(mTestDevice, type, id, data, mAttributionSource); verify(mService).replyReport(mTestDevice, type, id, data); } @@ -160,7 +170,7 @@ public class BluetoothHidDeviceBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] { BluetoothProfile.STATE_CONNECTED }; + int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); verify(mService).getDevicesMatchingConnectionStates(states); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceNativeInterfaceTest.java index 41b4006ee80..27bd6d6c1e9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceNativeInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceNativeInterfaceTest.java @@ -37,13 +37,11 @@ import org.mockito.junit.MockitoRule; public class HidDeviceNativeInterfaceTest { private static final byte[] TEST_DEVICE_ADDRESS = - new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - HidDeviceService mService; - @Mock - AdapterService mAdapterService; + @Mock HidDeviceService mService; + @Mock AdapterService mAdapterService; private HidDeviceNativeInterface mNativeInterface; @@ -69,8 +67,8 @@ public class HidDeviceNativeInterfaceTest { @Test public void onConnectStateChanged() { - mNativeInterface.onConnectStateChanged(TEST_DEVICE_ADDRESS, - BluetoothHidDevice.STATE_DISCONNECTED); + mNativeInterface.onConnectStateChanged( + TEST_DEVICE_ADDRESS, BluetoothHidDevice.STATE_DISCONNECTED); verify(mService).onConnectStateChangedFromNative(any(), anyInt()); } @@ -87,7 +85,7 @@ public class HidDeviceNativeInterfaceTest { public void onSetReport() { byte reportType = 1; byte reportId = 2; - byte[] data = new byte[] { 0x00, 0x00 }; + byte[] data = new byte[] {0x00, 0x00}; mNativeInterface.onSetReport(reportType, reportId, data); verify(mService).onSetReportFromNative(reportType, reportId, data); } @@ -102,7 +100,7 @@ public class HidDeviceNativeInterfaceTest { @Test public void onInterruptData() { byte reportId = 3; - byte[] data = new byte[] { 0x00, 0x00 }; + byte[] data = new byte[] {0x00, 0x00}; mNativeInterface.onInterruptData(reportId, data); verify(mService).onInterruptDataFromNative(reportId, data); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java index 4b6672ec6c2..a509da0730f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java @@ -57,8 +57,8 @@ import java.util.concurrent.TimeUnit; @MediumTest @RunWith(AndroidJUnit4.class) public class HidDeviceTest { - private static final int TIMEOUT_MS = 1000; // 1s - private static final byte[] SAMPLE_HID_REPORT = new byte[]{0x01, 0x00, 0x02}; + private static final int TIMEOUT_MS = 1000; // 1s + private static final byte[] SAMPLE_HID_REPORT = new byte[] {0x01, 0x00, 0x02}; private static final byte SAMPLE_REPORT_ID = 0x00; private static final byte SAMPLE_REPORT_TYPE = 0x00; private static final byte SAMPLE_REPORT_ERROR = 0x02; @@ -87,11 +87,11 @@ public class HidDeviceTest { private final BlockingQueue mConnectionStateChangedQueue = new LinkedBlockingQueue<>(); private final BlockingQueue mCallbackQueue = new LinkedBlockingQueue<>(); - private static void setHidDeviceNativeInterfaceInstance(HidDeviceNativeInterface instance) throws Exception { - Method method = HidDeviceNativeInterface.class.getDeclaredMethod("setInstance", - HidDeviceNativeInterface.class); + Method method = + HidDeviceNativeInterface.class.getDeclaredMethod( + "setInstance", HidDeviceNativeInterface.class); method.setAccessible(true); method.invoke(null, instance); } @@ -126,8 +126,13 @@ public class HidDeviceTest { Assert.assertEquals(nativeInterface, mHidDeviceNativeInterface); // Dummy SDP settings - mSettings = new BluetoothHidDeviceAppSdpSettings("Unit test", "test", "Android", - BluetoothHidDevice.SUBCLASS1_COMBO, new byte[]{}); + mSettings = + new BluetoothHidDeviceAppSdpSettings( + "Unit test", + "test", + "Android", + BluetoothHidDevice.SUBCLASS1_COMBO, + new byte[] {}); // Set up the Connection State Changed receiver IntentFilter filter = new IntentFilter(); @@ -174,15 +179,15 @@ public class HidDeviceTest { } } - private void verifyConnectionStateIntent(int timeoutMs, BluetoothDevice device, int newState, - int prevState) { + private void verifyConnectionStateIntent( + int timeoutMs, BluetoothDevice device, int newState, int prevState) { Intent intent = waitForIntent(timeoutMs, mConnectionStateChangedQueue); Assert.assertNotNull(intent); Assert.assertEquals(BluetoothHidDevice.ACTION_CONNECTION_STATE_CHANGED, intent.getAction()); Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); Assert.assertEquals(newState, intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertEquals(prevState, - intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)); + Assert.assertEquals( + prevState, intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)); } private void verifyCallback(int timeoutMs, int callbackType, BlockingQueue queue) { @@ -209,9 +214,7 @@ public class HidDeviceTest { } } - public void onConnectionStateChanged(BluetoothDevice device, int state) { - - } + public void onConnectionStateChanged(BluetoothDevice device, int state) {} public void onGetReport(BluetoothDevice device, byte type, byte id, int bufferSize) { try { @@ -242,7 +245,6 @@ public class HidDeviceTest { mCallbackQueue.put(CALLBACK_ON_INTR_DATA); } catch (InterruptedException e) { throw new AssertionError("Cannot add Intent to the queue", e); - } } @@ -255,9 +257,7 @@ public class HidDeviceTest { } } - /** - * Test getting HidDeviceService: getHidDeviceService(). - */ + /** Test getting HidDeviceService: getHidDeviceService(). */ @Test public void testGetHidDeviceService() { Assert.assertEquals(mHidDeviceService, HidDeviceService.getHidDeviceService()); @@ -269,19 +269,40 @@ public class HidDeviceTest { */ @Test public void testRegistration() throws Exception { - doReturn(true).when(mHidDeviceNativeInterface) - .registerApp(anyString(), anyString(), anyString(), anyByte(), any(byte[].class), - isNull(), isNull()); - - verify(mHidDeviceNativeInterface, never()).registerApp(anyString(), anyString(), - anyString(), anyByte(), any(byte[].class), isNull(), isNull()); + doReturn(true) + .when(mHidDeviceNativeInterface) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); + + verify(mHidDeviceNativeInterface, never()) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); // Register app BluetoothHidDeviceCallbackTestHelper helper = new BluetoothHidDeviceCallbackTestHelper(); Assert.assertTrue(mHidDeviceService.registerApp(mSettings, null, null, helper)); - verify(mHidDeviceNativeInterface).registerApp(anyString(), anyString(), anyString(), - anyByte(), any(byte[].class), isNull(), isNull()); + verify(mHidDeviceNativeInterface) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); // App registered mHidDeviceService.onApplicationStateChangedFromNative(mTestDevice, true); @@ -295,23 +316,28 @@ public class HidDeviceTest { mHidDeviceService.onApplicationStateChangedFromNative(mTestDevice, false); verifyCallback(TIMEOUT_MS, CALLBACK_APP_UNREGISTERED, mCallbackQueue); - } - /** - * Test the logic in sendReport(). This should fail when the app is not registered. - */ + /** Test the logic in sendReport(). This should fail when the app is not registered. */ @Test public void testSendReport() throws Exception { doReturn(true).when(mHidDeviceNativeInterface).sendReport(anyInt(), any(byte[].class)); // sendReport() should fail without app registered - Assert.assertEquals(false, + Assert.assertEquals( + false, mHidDeviceService.sendReport(mTestDevice, SAMPLE_REPORT_ID, SAMPLE_HID_REPORT)); // Register app - doReturn(true).when(mHidDeviceNativeInterface) - .registerApp(anyString(), anyString(), anyString(), anyByte(), any(byte[].class), - isNull(), isNull()); + doReturn(true) + .when(mHidDeviceNativeInterface) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); BluetoothHidDeviceCallbackTestHelper helper = new BluetoothHidDeviceCallbackTestHelper(); Assert.assertTrue(mHidDeviceService.registerApp(mSettings, null, null, helper)); @@ -322,33 +348,41 @@ public class HidDeviceTest { verifyCallback(TIMEOUT_MS, CALLBACK_APP_REGISTERED, mCallbackQueue); // sendReport() should work when app is registered - Assert.assertEquals(true, + Assert.assertEquals( + true, mHidDeviceService.sendReport(mTestDevice, SAMPLE_REPORT_ID, SAMPLE_HID_REPORT)); - verify(mHidDeviceNativeInterface).sendReport(eq((int) SAMPLE_REPORT_ID), - eq(SAMPLE_HID_REPORT)); + verify(mHidDeviceNativeInterface) + .sendReport(eq((int) SAMPLE_REPORT_ID), eq(SAMPLE_HID_REPORT)); // Unregister app doReturn(true).when(mHidDeviceNativeInterface).unregisterApp(); Assert.assertEquals(true, mHidDeviceService.unregisterApp()); } - /** - * Test the logic in replyReport(). This should fail when the app is not registered. - */ + /** Test the logic in replyReport(). This should fail when the app is not registered. */ @Test public void testReplyReport() throws Exception { - doReturn(true).when(mHidDeviceNativeInterface) + doReturn(true) + .when(mHidDeviceNativeInterface) .replyReport(anyByte(), anyByte(), any(byte[].class)); // replyReport() should fail without app registered - Assert.assertEquals(false, - mHidDeviceService.replyReport(mTestDevice, SAMPLE_REPORT_TYPE, SAMPLE_REPORT_ID, - SAMPLE_HID_REPORT)); + Assert.assertEquals( + false, + mHidDeviceService.replyReport( + mTestDevice, SAMPLE_REPORT_TYPE, SAMPLE_REPORT_ID, SAMPLE_HID_REPORT)); // Register app - doReturn(true).when(mHidDeviceNativeInterface) - .registerApp(anyString(), anyString(), anyString(), anyByte(), any(byte[].class), - isNull(), isNull()); + doReturn(true) + .when(mHidDeviceNativeInterface) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); BluetoothHidDeviceCallbackTestHelper helper = new BluetoothHidDeviceCallbackTestHelper(); Assert.assertTrue(mHidDeviceService.registerApp(mSettings, null, null, helper)); @@ -359,21 +393,20 @@ public class HidDeviceTest { verifyCallback(TIMEOUT_MS, CALLBACK_APP_REGISTERED, mCallbackQueue); // replyReport() should work when app is registered - Assert.assertEquals(true, - mHidDeviceService.replyReport(mTestDevice, SAMPLE_REPORT_TYPE, SAMPLE_REPORT_ID, - SAMPLE_HID_REPORT)); + Assert.assertEquals( + true, + mHidDeviceService.replyReport( + mTestDevice, SAMPLE_REPORT_TYPE, SAMPLE_REPORT_ID, SAMPLE_HID_REPORT)); - verify(mHidDeviceNativeInterface).replyReport(eq(SAMPLE_REPORT_TYPE), eq(SAMPLE_REPORT_ID), - eq(SAMPLE_HID_REPORT)); + verify(mHidDeviceNativeInterface) + .replyReport(eq(SAMPLE_REPORT_TYPE), eq(SAMPLE_REPORT_ID), eq(SAMPLE_HID_REPORT)); // Unregister app doReturn(true).when(mHidDeviceNativeInterface).unregisterApp(); Assert.assertEquals(true, mHidDeviceService.unregisterApp()); } - /** - * Test the logic in reportError(). This should fail when the app is not registered. - */ + /** Test the logic in reportError(). This should fail when the app is not registered. */ @Test public void testReportError() throws Exception { doReturn(true).when(mHidDeviceNativeInterface).reportError(anyByte()); @@ -381,9 +414,16 @@ public class HidDeviceTest { Assert.assertEquals(false, mHidDeviceService.reportError(mTestDevice, SAMPLE_REPORT_ERROR)); // Register app - doReturn(true).when(mHidDeviceNativeInterface) - .registerApp(anyString(), anyString(), anyString(), anyByte(), any(byte[].class), - isNull(), isNull()); + doReturn(true) + .when(mHidDeviceNativeInterface) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); BluetoothHidDeviceCallbackTestHelper helper = new BluetoothHidDeviceCallbackTestHelper(); Assert.assertTrue(mHidDeviceService.registerApp(mSettings, null, null, helper)); @@ -403,18 +443,23 @@ public class HidDeviceTest { Assert.assertEquals(true, mHidDeviceService.unregisterApp()); } - /** - * Test that an outgoing connection/disconnection succeeds - */ + /** Test that an outgoing connection/disconnection succeeds */ @Test public void testOutgoingConnectDisconnectSuccess() { doReturn(true).when(mHidDeviceNativeInterface).connect(any(BluetoothDevice.class)); doReturn(true).when(mHidDeviceNativeInterface).disconnect(); // Register app - doReturn(true).when(mHidDeviceNativeInterface) - .registerApp(anyString(), anyString(), anyString(), anyByte(), any(byte[].class), - isNull(), isNull()); + doReturn(true) + .when(mHidDeviceNativeInterface) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); mHidDeviceService.registerApp(mSettings, null, null, null); // App registered @@ -423,48 +468,70 @@ public class HidDeviceTest { // Send a connect request Assert.assertTrue("Connect failed", mHidDeviceService.connect(mTestDevice)); - mHidDeviceService.onConnectStateChangedFromNative(mTestDevice, - HidDeviceService.HAL_CONN_STATE_CONNECTING); + mHidDeviceService.onConnectStateChangedFromNative( + mTestDevice, HidDeviceService.HAL_CONN_STATE_CONNECTING); // Verify the connection state broadcast - verifyConnectionStateIntent(TIMEOUT_MS, mTestDevice, BluetoothProfile.STATE_CONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mTestDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTING, mHidDeviceService.getConnectionState(mTestDevice)); - mHidDeviceService.onConnectStateChangedFromNative(mTestDevice, - HidDeviceService.HAL_CONN_STATE_CONNECTED); + mHidDeviceService.onConnectStateChangedFromNative( + mTestDevice, HidDeviceService.HAL_CONN_STATE_CONNECTED); // Verify the connection state broadcast - verifyConnectionStateIntent(TIMEOUT_MS, mTestDevice, BluetoothProfile.STATE_CONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mTestDevice, + BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); - Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, + Assert.assertEquals( + BluetoothProfile.STATE_CONNECTED, mHidDeviceService.getConnectionState(mTestDevice)); // Verify the list of connected devices - Assert.assertTrue(mHidDeviceService.getDevicesMatchingConnectionStates( - new int[]{BluetoothProfile.STATE_CONNECTED}).contains(mTestDevice)); + Assert.assertTrue( + mHidDeviceService + .getDevicesMatchingConnectionStates( + new int[] {BluetoothProfile.STATE_CONNECTED}) + .contains(mTestDevice)); // Send a disconnect request Assert.assertTrue("Disconnect failed", mHidDeviceService.disconnect(mTestDevice)); - mHidDeviceService.onConnectStateChangedFromNative(mTestDevice, - HidDeviceService.HAL_CONN_STATE_DISCONNECTING); + mHidDeviceService.onConnectStateChangedFromNative( + mTestDevice, HidDeviceService.HAL_CONN_STATE_DISCONNECTING); // Verify the connection state broadcast - verifyConnectionStateIntent(TIMEOUT_MS, mTestDevice, BluetoothProfile.STATE_DISCONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mTestDevice, + BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTING, + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTING, mHidDeviceService.getConnectionState(mTestDevice)); - mHidDeviceService.onConnectStateChangedFromNative(mTestDevice, - HidDeviceService.HAL_CONN_STATE_DISCONNECTED); + mHidDeviceService.onConnectStateChangedFromNative( + mTestDevice, HidDeviceService.HAL_CONN_STATE_DISCONNECTED); // Verify the connection state broadcast - verifyConnectionStateIntent(TIMEOUT_MS, mTestDevice, BluetoothProfile.STATE_DISCONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mTestDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTING); - Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, + Assert.assertEquals( + BluetoothProfile.STATE_DISCONNECTED, mHidDeviceService.getConnectionState(mTestDevice)); // Verify the list of connected devices - Assert.assertFalse(mHidDeviceService.getDevicesMatchingConnectionStates( - new int[]{BluetoothProfile.STATE_CONNECTED}).contains(mTestDevice)); + Assert.assertFalse( + mHidDeviceService + .getDevicesMatchingConnectionStates( + new int[] {BluetoothProfile.STATE_CONNECTED}) + .contains(mTestDevice)); // Unregister app doReturn(true).when(mHidDeviceNativeInterface).unregisterApp(); @@ -478,32 +545,53 @@ public class HidDeviceTest { */ @Test public void testCallbacks() { - doReturn(true).when(mHidDeviceNativeInterface) - .registerApp(anyString(), anyString(), anyString(), anyByte(), any(byte[].class), - isNull(), isNull()); - - verify(mHidDeviceNativeInterface, never()).registerApp(anyString(), anyString(), - anyString(), anyByte(), any(byte[].class), isNull(), isNull()); + doReturn(true) + .when(mHidDeviceNativeInterface) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); + + verify(mHidDeviceNativeInterface, never()) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); // Register app BluetoothHidDeviceCallbackTestHelper helper = new BluetoothHidDeviceCallbackTestHelper(); Assert.assertTrue(mHidDeviceService.registerApp(mSettings, null, null, helper)); - verify(mHidDeviceNativeInterface).registerApp(anyString(), anyString(), anyString(), - anyByte(), any(byte[].class), isNull(), isNull()); + verify(mHidDeviceNativeInterface) + .registerApp( + anyString(), + anyString(), + anyString(), + anyByte(), + any(byte[].class), + isNull(), + isNull()); // App registered mHidDeviceService.onApplicationStateChangedFromNative(mTestDevice, true); verifyCallback(TIMEOUT_MS, CALLBACK_APP_REGISTERED, mCallbackQueue); // Received callback: onGetReport - mHidDeviceService.onGetReportFromNative(SAMPLE_REPORT_TYPE, SAMPLE_REPORT_ID, - SAMPLE_BUFFER_SIZE); + mHidDeviceService.onGetReportFromNative( + SAMPLE_REPORT_TYPE, SAMPLE_REPORT_ID, SAMPLE_BUFFER_SIZE); verifyCallback(TIMEOUT_MS, CALLBACK_ON_GET_REPORT, mCallbackQueue); // Received callback: onSetReport - mHidDeviceService.onSetReportFromNative(SAMPLE_REPORT_TYPE, SAMPLE_REPORT_ID, - SAMPLE_HID_REPORT); + mHidDeviceService.onSetReportFromNative( + SAMPLE_REPORT_TYPE, SAMPLE_REPORT_ID, SAMPLE_HID_REPORT); verifyCallback(TIMEOUT_MS, CALLBACK_ON_SET_REPORT, mCallbackQueue); // Received callback: onSetProtocol diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java index 8e1870c2ce5..39de9c8e0f2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java @@ -44,8 +44,7 @@ public class HidHostServiceBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private HidHostService mService; + @Mock private HidHostService mService; BluetoothDevice mRemoteDevice; @@ -75,8 +74,8 @@ public class HidHostServiceBinderTest { public void getConnectedDevices_callsServiceMethod() { mBinder.getConnectedDevices(null); - verify(mService).getDevicesMatchingConnectionStates( - new int[] { BluetoothProfile.STATE_CONNECTED }); + verify(mService) + .getDevicesMatchingConnectionStates(new int[] {BluetoothProfile.STATE_CONNECTED}); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java index ee746db3c50..6bac16e14ff 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java @@ -84,45 +84,66 @@ public class HidHostServiceTest { Assert.assertNotNull(HidHostService.getHidHostService()); } - /** - * Test okToConnect method using various test cases - */ + /** Test okToConnect method using various test cases */ @Test public void testOkToConnect() { int badPriorityValue = 1024; int badBondState = 42; - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_NONE, badPriorityValue, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_BONDING, badPriorityValue, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_ALLOWED, true); - testOkToConnectCase(mTestDevice, - BluetoothDevice.BOND_BONDED, badPriorityValue, false); - testOkToConnectCase(mTestDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mTestDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mTestDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mTestDevice, - badBondState, badPriorityValue, false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); + testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_NONE, badPriorityValue, false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); + testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDING, badPriorityValue, false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + true); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mTestDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + true); + testOkToConnectCase(mTestDevice, BluetoothDevice.BOND_BONDED, badPriorityValue, false); + testOkToConnectCase( + mTestDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); + testOkToConnectCase( + mTestDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); + testOkToConnectCase( + mTestDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); + testOkToConnectCase(mTestDevice, badBondState, badPriorityValue, false); } @Test @@ -138,8 +159,8 @@ public class HidHostServiceTest { * @param priority value, could be invalid, could be invalid * @param expected expected result from okToConnect() */ - private void testOkToConnectCase(BluetoothDevice device, int bondState, int priority, - boolean expected) { + private void testOkToConnectCase( + BluetoothDevice device, int bondState, int priority, boolean expected) { doReturn(bondState).when(mAdapterService).getBondState(device); when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.HID_HOST)) .thenReturn(priority); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/ContentControlIdKeeperTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/ContentControlIdKeeperTest.java index 6a3443387d9..572eb95e51a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/ContentControlIdKeeperTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/ContentControlIdKeeperTest.java @@ -45,10 +45,8 @@ import java.util.UUID; public class ContentControlIdKeeperTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - ServiceFactory mServiceFactoryMock; - @Mock - LeAudioService mLeAudioServiceMock; + @Mock ServiceFactory mServiceFactoryMock; + @Mock LeAudioService mLeAudioServiceMock; @Before public void setUp() throws Exception { @@ -64,33 +62,29 @@ public class ContentControlIdKeeperTest { public int testCcidAcquire(ParcelUuid uuid, int context, int expectedListSize) { int ccid = ContentControlIdKeeper.acquireCcid(uuid, context); - Assert.assertNotEquals( - ccid, - ContentControlIdKeeper.CCID_INVALID); + Assert.assertNotEquals(ccid, ContentControlIdKeeper.CCID_INVALID); - verify(mLeAudioServiceMock).setCcidInformation(eq(uuid), - eq(ccid), eq(context)); + verify(mLeAudioServiceMock).setCcidInformation(eq(uuid), eq(ccid), eq(context)); Map> uuidToCcidContextPair = ContentControlIdKeeper.getUuidToCcidContextPairMap(); Assert.assertEquals(expectedListSize, uuidToCcidContextPair.size()); Assert.assertTrue(uuidToCcidContextPair.containsKey(uuid)); - Assert.assertEquals(ccid, (long)uuidToCcidContextPair.get(uuid).first); - Assert.assertEquals(context, (long)uuidToCcidContextPair.get(uuid).second); + Assert.assertEquals(ccid, (long) uuidToCcidContextPair.get(uuid).first); + Assert.assertEquals(context, (long) uuidToCcidContextPair.get(uuid).second); return ccid; } public void testCcidRelease(ParcelUuid uuid, int ccid, int expectedListSize) { Map> uuidToCcidContextPair = - ContentControlIdKeeper.getUuidToCcidContextPairMap(); + ContentControlIdKeeper.getUuidToCcidContextPairMap(); Assert.assertTrue(uuidToCcidContextPair.containsKey(uuid)); ContentControlIdKeeper.releaseCcid(ccid); uuidToCcidContextPair = ContentControlIdKeeper.getUuidToCcidContextPairMap(); Assert.assertFalse(uuidToCcidContextPair.containsKey(uuid)); - verify(mLeAudioServiceMock).setCcidInformation(eq(uuid), - eq(ccid), eq(0)); + verify(mLeAudioServiceMock).setCcidInformation(eq(uuid), eq(ccid), eq(0)); Assert.assertEquals(expectedListSize, uuidToCcidContextPair.size()); } @@ -111,8 +105,12 @@ public class ContentControlIdKeeperTest { @Test public void testAcquireReleaseCcidForCompoundContext() { ParcelUuid uuid = new ParcelUuid(UUID.randomUUID()); - int ccid = testCcidAcquire(uuid, - BluetoothLeAudio.CONTEXT_TYPE_MEDIA | BluetoothLeAudio.CONTEXT_TYPE_RINGTONE, 1); + int ccid = + testCcidAcquire( + uuid, + BluetoothLeAudio.CONTEXT_TYPE_MEDIA + | BluetoothLeAudio.CONTEXT_TYPE_RINGTONE, + 1); testCcidRelease(uuid, ccid, 0); } @@ -123,8 +121,8 @@ public class ContentControlIdKeeperTest { int ccid = ContentControlIdKeeper.acquireCcid(uuid, 0); Assert.assertEquals(ccid, ContentControlIdKeeper.CCID_INVALID); - verify(mLeAudioServiceMock, - times(0)).setCcidInformation(any(ParcelUuid.class), any(int.class), any(int.class)); + verify(mLeAudioServiceMock, times(0)) + .setCcidInformation(any(ParcelUuid.class), any(int.class), any(int.class)); Map> uuidToCcidContextPair = ContentControlIdKeeper.getUuidToCcidContextPairMap(); Assert.assertEquals(0, uuidToCcidContextPair.size()); @@ -140,5 +138,4 @@ public class ContentControlIdKeeperTest { // This is implementation specific but verifies that the previous CCID was recycled Assert.assertEquals(ccid_one, ccid_two); } - } diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java index 9cf208aaa02..c8a85c0ec38 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java @@ -76,8 +76,7 @@ public class LeAudioBinderTest { private BluetoothAdapter mAdapter; private static final String TEST_BROADCAST_NAME = "TEST"; - private static final int TEST_QUALITY = - BluetoothLeBroadcastSubgroupSettings.QUALITY_STANDARD; + private static final int TEST_QUALITY = BluetoothLeBroadcastSubgroupSettings.QUALITY_STANDARD; @Before public void setUp() throws Exception { @@ -145,7 +144,7 @@ public class LeAudioBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_DISCONNECTED }; + int[] states = new int[] {BluetoothProfile.STATE_DISCONNECTED}; AttributionSource source = new AttributionSource.Builder(0).build(); mBinder.getDevicesMatchingConnectionStates(states, source); @@ -410,8 +409,7 @@ public class LeAudioBinderTest { @Test public void setCodecConfigPreference() { int groupId = 1; - BluetoothLeAudioCodecConfig inputConfig = - new BluetoothLeAudioCodecConfig.Builder().build(); + BluetoothLeAudioCodecConfig inputConfig = new BluetoothLeAudioCodecConfig.Builder().build(); BluetoothLeAudioCodecConfig outputConfig = new BluetoothLeAudioCodecConfig.Builder().build(); AttributionSource source = new AttributionSource.Builder(0).build(); @@ -429,10 +427,11 @@ public class LeAudioBinderTest { BluetoothLeBroadcastSubgroupSettings.Builder subgroupBuilder = new BluetoothLeBroadcastSubgroupSettings.Builder() - .setPreferredQuality(TEST_QUALITY) - .setContentMetadata(metadata); + .setPreferredQuality(TEST_QUALITY) + .setContentMetadata(metadata); - BluetoothLeBroadcastSettings.Builder builder = new BluetoothLeBroadcastSettings.Builder() + BluetoothLeBroadcastSettings.Builder builder = + new BluetoothLeBroadcastSettings.Builder() .setPublicBroadcast(false) .setBroadcastName(TEST_BROADCAST_NAME) .setBroadcastCode(null) diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java index 34936960f81..7510fe2ce62 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java @@ -81,12 +81,9 @@ public class LeAudioBroadcastServiceTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock private ActiveDeviceManager mActiveDeviceManager; - @Mock - private AdapterService mAdapterService; - @Mock - private DatabaseManager mDatabaseManager; - @Mock - private AudioManager mAudioManager; + @Mock private AdapterService mAdapterService; + @Mock private DatabaseManager mDatabaseManager; + @Mock private AudioManager mAudioManager; @Mock private LeAudioBroadcasterNativeInterface mLeAudioBroadcasterNativeInterface; @Mock private LeAudioNativeInterface mLeAudioNativeInterface; @Mock private LeAudioTmapGattServer mTmapGattServer; @@ -199,7 +196,6 @@ public class LeAudioBroadcastServiceTest { public void setUp() throws Exception { mTargetContext = InstrumentationRegistry.getTargetContext(); - // Use spied objects factory doNothing().when(mTmapGattServer).start(anyInt()); doNothing().when(mTmapGattServer).stop(); @@ -213,8 +209,11 @@ public class LeAudioBroadcastServiceTest { TestUtils.setAdapterService(mAdapterService); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); doReturn(true).when(mAdapterService).isLeAudioBroadcastSourceSupported(); - doReturn((long)(1 << BluetoothProfile.LE_AUDIO_BROADCAST) | (1 << BluetoothProfile.LE_AUDIO)) - .when(mAdapterService).getSupportedProfilesBitMask(); + doReturn( + (long) (1 << BluetoothProfile.LE_AUDIO_BROADCAST) + | (1 << BluetoothProfile.LE_AUDIO)) + .when(mAdapterService) + .getSupportedProfilesBitMask(); doReturn(mActiveDeviceManager).when(mAdapterService).getActiveDeviceManager(); mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -270,9 +269,7 @@ public class LeAudioBroadcastServiceTest { Assert.assertNull(mService); } - /** - * Test getting LeAudio Service - */ + /** Test getting LeAudio Service */ @Test public void testGetLeAudioService() { Assert.assertEquals(mService, LeAudioService.getLeAudioService()); @@ -289,12 +286,10 @@ public class LeAudioBroadcastServiceTest { void verifyBroadcastStarted(int broadcastId, BluetoothLeBroadcastSettings settings) { mService.createBroadcast(settings); - List settingsList = - settings.getSubgroupSettings(); + List settingsList = settings.getSubgroupSettings(); int[] expectedQualityArray = - settingsList.stream() - .mapToInt(setting -> setting.getPreferredQuality()).toArray(); + settingsList.stream().mapToInt(setting -> setting.getPreferredQuality()).toArray(); byte[][] expectedDataArray = settingsList.stream() .map(setting -> setting.getContentMetadata().getRawMetadata()) @@ -411,10 +406,10 @@ public class LeAudioBroadcastServiceTest { mService.createBroadcast(settings); // Test data with only one subgroup - int[] expectedQualityArray = - {settings.getSubgroupSettings().get(0).getPreferredQuality()}; - byte[][] expectedDataArray = - {settings.getSubgroupSettings().get(0).getContentMetadata().getRawMetadata()}; + int[] expectedQualityArray = {settings.getSubgroupSettings().get(0).getPreferredQuality()}; + byte[][] expectedDataArray = { + settings.getSubgroupSettings().get(0).getContentMetadata().getRawMetadata() + }; verify(mLeAudioBroadcasterNativeInterface, times(1)) .createBroadcast( @@ -565,11 +560,11 @@ public class LeAudioBroadcastServiceTest { // Update metadata for non-existing broadcast BluetoothLeAudioContentMetadata.Builder meta_builder = - new BluetoothLeAudioContentMetadata.Builder(); + new BluetoothLeAudioContentMetadata.Builder(); meta_builder.setLanguage("eng"); meta_builder.setProgramInfo("Public broadcast info"); - mService.updateBroadcast(broadcastId, - buildBroadcastSettingsFromMetadata(meta_builder.build(), null, 1)); + mService.updateBroadcast( + broadcastId, buildBroadcastSettingsFromMetadata(meta_builder.build(), null, 1)); TestUtils.waitForLooperToFinishScheduledTask(mService.getMainLooper()); @@ -580,35 +575,41 @@ public class LeAudioBroadcastServiceTest { private BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { BluetoothLeAudioCodecConfigMetadata codecMetadata = new BluetoothLeAudioCodecConfigMetadata.Builder() - .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_LEFT).build(); + .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_LEFT) + .build(); BluetoothLeAudioContentMetadata contentMetadata = new BluetoothLeAudioContentMetadata.Builder() - .setProgramInfo(TEST_PROGRAM_INFO).setLanguage(TEST_LANGUAGE).build(); - BluetoothLeBroadcastSubgroup.Builder builder = new BluetoothLeBroadcastSubgroup.Builder() - .setCodecId(TEST_CODEC_ID) - .setCodecSpecificConfig(codecMetadata) - .setContentMetadata(contentMetadata); + .setProgramInfo(TEST_PROGRAM_INFO) + .setLanguage(TEST_LANGUAGE) + .build(); + BluetoothLeBroadcastSubgroup.Builder builder = + new BluetoothLeBroadcastSubgroup.Builder() + .setCodecId(TEST_CODEC_ID) + .setCodecSpecificConfig(codecMetadata) + .setContentMetadata(contentMetadata); BluetoothLeAudioCodecConfigMetadata channelCodecMetadata = new BluetoothLeAudioCodecConfigMetadata.Builder() - .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_RIGHT).build(); + .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_RIGHT) + .build(); // builder expect at least one channel BluetoothLeBroadcastChannel channel = - new BluetoothLeBroadcastChannel.Builder() - .setSelected(true) - .setChannelIndex(TEST_CHANNEL_INDEX) - .setCodecMetadata(channelCodecMetadata) - .build(); + new BluetoothLeBroadcastChannel.Builder() + .setSelected(true) + .setChannelIndex(TEST_CHANNEL_INDEX) + .setCodecMetadata(channelCodecMetadata) + .build(); builder.addChannel(channel); return builder.build(); } private BluetoothLeBroadcastMetadata createBroadcastMetadata() { BluetoothDevice testDevice = - mAdapter.getRemoteLeDevice(TEST_MAC_ADDRESS, BluetoothDevice.ADDRESS_TYPE_RANDOM); + mAdapter.getRemoteLeDevice(TEST_MAC_ADDRESS, BluetoothDevice.ADDRESS_TYPE_RANDOM); - BluetoothLeBroadcastMetadata.Builder builder = new BluetoothLeBroadcastMetadata.Builder() + BluetoothLeBroadcastMetadata.Builder builder = + new BluetoothLeBroadcastMetadata.Builder() .setEncrypted(false) .setSourceDevice(testDevice, BluetoothDevice.ADDRESS_TYPE_RANDOM) .setSourceAdvertisingSid(TEST_ADVERTISER_SID) @@ -731,7 +732,7 @@ public class LeAudioBroadcastServiceTest { /* Initialize native */ LeAudioStackEvent stackEvent = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_NATIVE_INITIALIZED); + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_NATIVE_INITIALIZED); mService.messageFromNative(stackEvent); Assert.assertTrue(mService.mLeAudioNativeIsInitialized); @@ -1150,7 +1151,8 @@ public class LeAudioBroadcastServiceTest { Assert.assertEquals(activeGroup, groupId); /* Imitate group change request by Bluetooth Sink HAL suspend request */ - create_event = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_UNICAST_MONITOR_MODE_STATUS); + create_event = + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_UNICAST_MONITOR_MODE_STATUS); create_event.valueInt1 = LeAudioStackEvent.DIRECTION_SINK; create_event.valueInt2 = LeAudioStackEvent.STATUS_LOCAL_STREAM_SUSPENDED; mService.messageFromNative(create_event); @@ -1199,7 +1201,8 @@ public class LeAudioBroadcastServiceTest { .setContentMetadata(contentMetadata) .setPreferredQuality(BluetoothLeBroadcastSubgroupSettings.QUALITY_HIGH); - BluetoothLeBroadcastSettings.Builder builder = new BluetoothLeBroadcastSettings.Builder() + BluetoothLeBroadcastSettings.Builder builder = + new BluetoothLeBroadcastSettings.Builder() .setPublicBroadcast(true) .setBroadcastName(TEST_BROADCAST_NAME) .setBroadcastCode(broadcastCode) diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterfaceTest.java index 045b5a26673..889a8cdcbf2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterfaceTest.java @@ -39,8 +39,7 @@ import org.mockito.junit.MockitoRule; public class LeAudioBroadcasterNativeInterfaceTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private LeAudioService mMockService; + @Mock private LeAudioService mMockService; private LeAudioBroadcasterNativeInterface mNativeInterface; @@ -63,11 +62,9 @@ public class LeAudioBroadcasterNativeInterfaceTest { mNativeInterface.onBroadcastCreated(broadcastId, success); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_BROADCAST_CREATED); + assertThat(event.getValue().type).isEqualTo(LeAudioStackEvent.EVENT_TYPE_BROADCAST_CREATED); } @Test @@ -76,11 +73,10 @@ public class LeAudioBroadcasterNativeInterfaceTest { mNativeInterface.onBroadcastDestroyed(broadcastId); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_BROADCAST_DESTROYED); + assertThat(event.getValue().type) + .isEqualTo(LeAudioStackEvent.EVENT_TYPE_BROADCAST_DESTROYED); } @Test @@ -90,11 +86,9 @@ public class LeAudioBroadcasterNativeInterfaceTest { mNativeInterface.onBroadcastStateChanged(broadcastId, state); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_BROADCAST_STATE); + assertThat(event.getValue().type).isEqualTo(LeAudioStackEvent.EVENT_TYPE_BROADCAST_STATE); } @Test @@ -104,10 +98,9 @@ public class LeAudioBroadcasterNativeInterfaceTest { mNativeInterface.onBroadcastMetadataChanged(broadcastId, metadata); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_BROADCAST_METADATA_CHANGED); + assertThat(event.getValue().type) + .isEqualTo(LeAudioStackEvent.EVENT_TYPE_BROADCAST_METADATA_CHANGED); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioNativeInterfaceTest.java index cf88ce49259..c6e8cf33381 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioNativeInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioNativeInterfaceTest.java @@ -40,8 +40,7 @@ import org.mockito.junit.MockitoRule; public class LeAudioNativeInterfaceTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private LeAudioService mMockService; + @Mock private LeAudioService mMockService; private LeAudioNativeInterface mNativeInterface; @@ -60,30 +59,28 @@ public class LeAudioNativeInterfaceTest { @Test public void onConnectionStateChanged() { int state = LeAudioStackEvent.CONNECTION_STATE_CONNECTED; - byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; + byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}; mNativeInterface.onConnectionStateChanged(state, address); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + assertThat(event.getValue().type) + .isEqualTo(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); } @Test public void onGroupNodeStatus() { - byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; + byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}; int groupId = 1; int nodeStatus = LeAudioStackEvent.GROUP_NODE_ADDED; mNativeInterface.onGroupNodeStatus(address, groupId, nodeStatus); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_GROUP_NODE_STATUS_CHANGED); + assertThat(event.getValue().type) + .isEqualTo(LeAudioStackEvent.EVENT_TYPE_GROUP_NODE_STATUS_CHANGED); } @Test @@ -97,44 +94,40 @@ public class LeAudioNativeInterfaceTest { mNativeInterface.onAudioConf( direction, groupId, sinkAudioLocation, sourceAudioLocation, availableContexts); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_AUDIO_CONF_CHANGED); + assertThat(event.getValue().type) + .isEqualTo(LeAudioStackEvent.EVENT_TYPE_AUDIO_CONF_CHANGED); } @Test public void onSinkAudioLocationAvailable() { - byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; + byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05}; int sinkAudioLocation = BluetoothLeAudio.AUDIO_LOCATION_INVALID; mNativeInterface.onSinkAudioLocationAvailable(address, sinkAudioLocation); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_SINK_AUDIO_LOCATION_AVAILABLE); + assertThat(event.getValue().type) + .isEqualTo(LeAudioStackEvent.EVENT_TYPE_SINK_AUDIO_LOCATION_AVAILABLE); } @Test public void onAudioLocalCodecCapabilities() { - BluetoothLeAudioCodecConfig emptyConfig = - new BluetoothLeAudioCodecConfig.Builder().build(); + BluetoothLeAudioCodecConfig emptyConfig = new BluetoothLeAudioCodecConfig.Builder().build(); BluetoothLeAudioCodecConfig[] localInputCodecCapabilities = - new BluetoothLeAudioCodecConfig[] { emptyConfig }; + new BluetoothLeAudioCodecConfig[] {emptyConfig}; BluetoothLeAudioCodecConfig[] localOutputCodecCapabilities = - new BluetoothLeAudioCodecConfig[] { emptyConfig }; + new BluetoothLeAudioCodecConfig[] {emptyConfig}; mNativeInterface.onAudioLocalCodecCapabilities( localInputCodecCapabilities, localOutputCodecCapabilities); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); - assertThat(event.getValue().type).isEqualTo( - LeAudioStackEvent.EVENT_TYPE_AUDIO_LOCAL_CODEC_CONFIG_CAPA_CHANGED); + assertThat(event.getValue().type) + .isEqualTo(LeAudioStackEvent.EVENT_TYPE_AUDIO_LOCAL_CODEC_CONFIG_CAPA_CHANGED); } @Test @@ -155,20 +148,18 @@ public class LeAudioNativeInterfaceTest { @Test public void onAudioGroupSelectableCodecConf() { int groupId = 1; - BluetoothLeAudioCodecConfig inputConfig = - new BluetoothLeAudioCodecConfig.Builder().build(); + BluetoothLeAudioCodecConfig inputConfig = new BluetoothLeAudioCodecConfig.Builder().build(); BluetoothLeAudioCodecConfig outputConfig = new BluetoothLeAudioCodecConfig.Builder().build(); BluetoothLeAudioCodecConfig[] inputSelectableCodecConfig = - new BluetoothLeAudioCodecConfig[] { inputConfig }; + new BluetoothLeAudioCodecConfig[] {inputConfig}; BluetoothLeAudioCodecConfig[] outputSelectableCodecConfig = - new BluetoothLeAudioCodecConfig[] { outputConfig }; + new BluetoothLeAudioCodecConfig[] {outputConfig}; mNativeInterface.onAudioGroupSelectableCodecConf( groupId, inputSelectableCodecConfig, outputSelectableCodecConfig); - ArgumentCaptor event = - ArgumentCaptor.forClass(LeAudioStackEvent.class); + ArgumentCaptor event = ArgumentCaptor.forClass(LeAudioStackEvent.class); verify(mMockService).messageFromNative(event.capture()); assertThat(event.getValue().type) .isEqualTo( diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java index ee3c5cfd3c2..20651241105 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java @@ -145,42 +145,42 @@ public class LeAudioServiceTest { private static final BluetoothLeAudioCodecConfig LC3_16KHZ_CONFIG = new BluetoothLeAudioCodecConfig.Builder() - .setCodecType(BluetoothLeAudioCodecConfig.SOURCE_CODEC_TYPE_LC3) - .setSampleRate(BluetoothLeAudioCodecConfig.SAMPLE_RATE_16000) - .build(); + .setCodecType(BluetoothLeAudioCodecConfig.SOURCE_CODEC_TYPE_LC3) + .setSampleRate(BluetoothLeAudioCodecConfig.SAMPLE_RATE_16000) + .build(); private static final BluetoothLeAudioCodecConfig LC3_48KHZ_CONFIG = new BluetoothLeAudioCodecConfig.Builder() - .setCodecType(BluetoothLeAudioCodecConfig.SOURCE_CODEC_TYPE_LC3) - .setSampleRate(BluetoothLeAudioCodecConfig.SAMPLE_RATE_48000) - .build(); + .setCodecType(BluetoothLeAudioCodecConfig.SOURCE_CODEC_TYPE_LC3) + .setSampleRate(BluetoothLeAudioCodecConfig.SAMPLE_RATE_48000) + .build(); private static final BluetoothLeAudioCodecConfig LC3_48KHZ_16KHZ_CONFIG = - new BluetoothLeAudioCodecConfig.Builder() - .setCodecType(BluetoothLeAudioCodecConfig.SOURCE_CODEC_TYPE_LC3) - .setSampleRate(BluetoothLeAudioCodecConfig.SAMPLE_RATE_48000 - | BluetoothLeAudioCodecConfig.SAMPLE_RATE_16000) - .build(); + new BluetoothLeAudioCodecConfig.Builder() + .setCodecType(BluetoothLeAudioCodecConfig.SOURCE_CODEC_TYPE_LC3) + .setSampleRate( + BluetoothLeAudioCodecConfig.SAMPLE_RATE_48000 + | BluetoothLeAudioCodecConfig.SAMPLE_RATE_16000) + .build(); - private static final List INPUT_CAPABILITIES_CONFIG = List.of( - LC3_48KHZ_16KHZ_CONFIG); + private static final List INPUT_CAPABILITIES_CONFIG = + List.of(LC3_48KHZ_16KHZ_CONFIG); - private static final List OUTPUT_CAPABILITIES_CONFIG = List.of( - LC3_48KHZ_16KHZ_CONFIG); + private static final List OUTPUT_CAPABILITIES_CONFIG = + List.of(LC3_48KHZ_16KHZ_CONFIG); - private static final List INPUT_SELECTABLE_CONFIG = List.of( - LC3_16KHZ_CONFIG); + private static final List INPUT_SELECTABLE_CONFIG = + List.of(LC3_16KHZ_CONFIG); private static final List INPUT_EMPTY_CONFIG = List.of(EMPTY_CONFIG); - private static final List OUTPUT_SELECTABLE_CONFIG = List.of( - LC3_48KHZ_16KHZ_CONFIG); + private static final List OUTPUT_SELECTABLE_CONFIG = + List.of(LC3_48KHZ_16KHZ_CONFIG); @Before public void setUp() throws Exception { mTargetContext = InstrumentationRegistry.getTargetContext(); - // Use spied objects factory doNothing().when(mTmapGattServer).start(anyInt()); doNothing().when(mTmapGattServer).stop(); @@ -194,7 +194,8 @@ public class LeAudioServiceTest { TestUtils.setAdapterService(mAdapterService); doReturn(MAX_LE_AUDIO_CONNECTIONS).when(mAdapterService).getMaxConnectedAudioDevices(); - doReturn(new ParcelUuid[]{BluetoothUuid.LE_AUDIO}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.LE_AUDIO}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); doReturn(mActiveDeviceManager).when(mAdapterService).getActiveDeviceManager(); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); @@ -203,8 +204,9 @@ public class LeAudioServiceTest { assertThat(manager).isNotNull(); mAdapter = manager.getAdapter(); // Mock methods in AdapterService - doAnswer(invocation -> mBondedDevices.toArray(new BluetoothDevice[]{})).when( - mAdapterService).getBondedDevices(); + doAnswer(invocation -> mBondedDevices.toArray(new BluetoothDevice[] {})) + .when(mAdapterService) + .getBondedDevices(); LeAudioNativeInterface.setInstance(mNativeInterface); startService(); @@ -221,12 +223,12 @@ public class LeAudioServiceTest { when(mServiceFactory.getBassClientService()).thenReturn(mBassClientService); LeAudioStackEvent stackEvent = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_NATIVE_INITIALIZED); + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_NATIVE_INITIALIZED); mService.messageFromNative(stackEvent); assertThat(mService.mLeAudioNativeIsInitialized).isTrue(); // Override the timeout value to speed up the test - LeAudioStateMachine.sConnectTimeoutMs = TIMEOUT_MS; // 1s + LeAudioStateMachine.sConnectTimeoutMs = TIMEOUT_MS; // 1s mGroupIntentQueue = new LinkedBlockingQueue<>(); @@ -238,8 +240,9 @@ public class LeAudioServiceTest { mLeAudioIntentReceiver = new LeAudioIntentReceiver(); mTargetContext.registerReceiver(mLeAudioIntentReceiver, filter); - doAnswer(invocation -> mBondedDevices.toArray(new BluetoothDevice[]{})).when( - mAdapterService).getBondedDevices(); + doAnswer(invocation -> mBondedDevices.toArray(new BluetoothDevice[] {})) + .when(mAdapterService) + .getBondedDevices(); // Get a device for testing mLeftDevice = TestUtils.getTestDevice(mAdapter, 0); @@ -251,9 +254,11 @@ public class LeAudioServiceTest { mDeviceQueueMap.put(mRightDevice, new LinkedBlockingQueue<>()); mDeviceQueueMap.put(mSingleDevice, new LinkedBlockingQueue<>()); mDeviceQueueMap.put(mSingleDevice_2, new LinkedBlockingQueue<>()); - doReturn(BluetoothDevice.BOND_BONDED).when(mAdapterService) + doReturn(BluetoothDevice.BOND_BONDED) + .when(mAdapterService) .getBondState(any(BluetoothDevice.class)); - doReturn(new ParcelUuid[]{BluetoothUuid.LE_AUDIO}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.LE_AUDIO}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); verify(mNativeInterface, timeout(3000).times(1)).init(any()); @@ -305,46 +310,52 @@ public class LeAudioServiceTest { return; } - if (BluetoothLeAudio.ACTION_LE_AUDIO_CONNECTION_STATE_CHANGED - .equals(intent.getAction())) { + if (BluetoothLeAudio.ACTION_LE_AUDIO_CONNECTION_STATE_CHANGED.equals( + intent.getAction())) { try { - BluetoothDevice device = intent.getParcelableExtra( - BluetoothDevice.EXTRA_DEVICE); + BluetoothDevice device = + intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); assertThat(device).isNotNull(); LinkedBlockingQueue queue = mDeviceQueueMap.get(device); assertThat(queue).isNotNull(); queue.put(intent); } catch (InterruptedException e) { - assertWithMessage("Cannot add Intent to the Connection State queue: " - + e.getMessage()).fail(); + assertWithMessage( + "Cannot add Intent to the Connection State queue: " + + e.getMessage()) + .fail(); } } else if (BluetoothLeAudio.ACTION_LE_AUDIO_ACTIVE_DEVICE_CHANGED.equals( intent.getAction())) { try { - BluetoothDevice device = intent.getParcelableExtra( - BluetoothDevice.EXTRA_DEVICE); + BluetoothDevice device = + intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device != null) { LinkedBlockingQueue queue = mDeviceQueueMap.get(device); assertThat(queue).isNotNull(); queue.put(intent); } } catch (InterruptedException e) { - assertWithMessage("Cannot add Le Audio Intent to the Connection State queue: " - + e.getMessage()).fail(); + assertWithMessage( + "Cannot add Le Audio Intent to the Connection State queue: " + + e.getMessage()) + .fail(); } } } } - private void verifyConnectionStateIntent(int timeoutMs, BluetoothDevice device, - int newState, int prevState) { + private void verifyConnectionStateIntent( + int timeoutMs, BluetoothDevice device, int newState, int prevState) { Intent intent = TestUtils.waitForIntent(timeoutMs, mDeviceQueueMap.get(device)); assertThat(intent).isNotNull(); assertThat(intent.getAction()) .isEqualTo(BluetoothLeAudio.ACTION_LE_AUDIO_CONNECTION_STATE_CHANGED); - assertThat((BluetoothDevice)intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)).isEqualTo(device); + assertThat((BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)) + .isEqualTo(device); assertThat(intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1)).isEqualTo(newState); - assertThat(intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)).isEqualTo(prevState); + assertThat(intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1)) + .isEqualTo(prevState); if (newState == BluetoothProfile.STATE_CONNECTED) { // ActiveDeviceManager calls deviceConnected when connected. @@ -355,17 +366,13 @@ public class LeAudioServiceTest { } } - /** - * Test getting LeAudio Service: getLeAudioService() - */ + /** Test getting LeAudio Service: getLeAudioService() */ @Test public void testGetLeAudioService() { assertThat(mService).isEqualTo(LeAudioService.getLeAudioService()); } - /** - * Test stop LeAudio Service - */ + /** Test stop LeAudio Service */ @Test public void testStopLeAudioService() { // Prepare: connect @@ -374,9 +381,7 @@ public class LeAudioServiceTest { InstrumentationRegistry.getInstrumentation().runOnMainSync(mService::stop); } - /** - * Test if stop during init is ok. - */ + /** Test if stop during init is ok. */ @Test public void testStopStartStopService() throws Exception { InstrumentationRegistry.getInstrumentation() @@ -412,118 +417,128 @@ public class LeAudioServiceTest { } /** - * Helper function to test okToConnect() method + * Helper function to test okToConnect() method * - * @param device test device - * @param bondState bond state value, could be invalid - * @param priority value, could be invalid, could be invalid - * @param expected expected result from okToConnect() + * @param device test device + * @param bondState bond state value, could be invalid + * @param priority value, could be invalid, could be invalid + * @param expected expected result from okToConnect() */ - private void testOkToConnectCase(BluetoothDevice device, int bondState, int priority, - boolean expected) { + private void testOkToConnectCase( + BluetoothDevice device, int bondState, int priority, boolean expected) { doReturn(bondState).when(mAdapterService).getBondState(device); when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO)) .thenReturn(priority); assertThat(expected).isEqualTo(mService.okToConnect(device)); } - /** - * Test okToConnect method using various test cases - */ + /** Test okToConnect method using various test cases */ @Test public void testOkToConnect() { int badPriorityValue = 1024; int badBondState = 42; - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_NONE, badPriorityValue, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_BONDING, badPriorityValue, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_ALLOWED, true); - testOkToConnectCase(mSingleDevice, - BluetoothDevice.BOND_BONDED, badPriorityValue, false); - testOkToConnectCase(mSingleDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase(mSingleDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); - testOkToConnectCase(mSingleDevice, - badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); - testOkToConnectCase(mSingleDevice, - badBondState, badPriorityValue, false); - } - - /** - * Test that an outgoing connection to device that does not have Le Audio UUID is rejected - */ + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_NONE, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); + testOkToConnectCase(mSingleDevice, BluetoothDevice.BOND_NONE, badPriorityValue, false); + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + false); + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_BONDING, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + false); + testOkToConnectCase(mSingleDevice, BluetoothDevice.BOND_BONDING, badPriorityValue, false); + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + true); + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, + false); + testOkToConnectCase( + mSingleDevice, + BluetoothDevice.BOND_BONDED, + BluetoothProfile.CONNECTION_POLICY_ALLOWED, + true); + testOkToConnectCase(mSingleDevice, BluetoothDevice.BOND_BONDED, badPriorityValue, false); + testOkToConnectCase( + mSingleDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); + testOkToConnectCase( + mSingleDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); + testOkToConnectCase( + mSingleDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false); + testOkToConnectCase(mSingleDevice, badBondState, badPriorityValue, false); + } + + /** Test that an outgoing connection to device that does not have Le Audio UUID is rejected */ @Test public void testOutgoingConnectMissingLeAudioUuid() { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mDatabaseManager - .getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - when(mDatabaseManager - .getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); // Return No UUID - doReturn(new ParcelUuid[]{}).when(mAdapterService) + doReturn(new ParcelUuid[] {}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Send a connect request assertWithMessage("Connect expected to fail").that(mService.connect(mLeftDevice)).isFalse(); } - /** - * Test that an outgoing connection to device with PRIORITY_OFF is rejected - */ + /** Test that an outgoing connection to device with PRIORITY_OFF is rejected */ @Test public void testOutgoingConnectPriorityOff() { doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); // Set the device priority to PRIORITY_OFF so connect() should fail - when(mDatabaseManager - .getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Send a connect request assertWithMessage("Connect expected to fail").that(mService.connect(mLeftDevice)).isFalse(); } - /** - * Test that an outgoing connection times out - */ + /** Test that an outgoing connection times out */ @Test public void testOutgoingConnectTimeout() { // Update the device priority so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mDatabaseManager - .getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - when(mDatabaseManager - .getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); @@ -532,14 +547,19 @@ public class LeAudioServiceTest { assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, mLeftDevice, BluetoothProfile.STATE_CONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(mService.getConnectionState(mLeftDevice)) .isEqualTo(BluetoothProfile.STATE_CONNECTING); // Verify the connection state broadcast, and that we are in Disconnected state - verifyConnectionStateIntent(LeAudioStateMachine.sConnectTimeoutMs * 2, - mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, + verifyConnectionStateIntent( + LeAudioStateMachine.sConnectTimeoutMs * 2, + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); assertThat(mService.getConnectionState(mLeftDevice)) .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); @@ -576,36 +596,35 @@ public class LeAudioServiceTest { } private void injectNoVerifyDeviceConnected(BluetoothDevice device) { - generateUnexpectedConnectionMessageFromNative(device, + generateUnexpectedConnectionMessageFromNative( + device, LeAudioStackEvent.CONNECTION_STATE_CONNECTED, LeAudioStackEvent.CONNECTION_STATE_DISCONNECTED); } private void injectAndVerifyDeviceDisconnected(BluetoothDevice device) { - generateConnectionMessageFromNative(device, + generateConnectionMessageFromNative( + device, LeAudioStackEvent.CONNECTION_STATE_DISCONNECTED, LeAudioStackEvent.CONNECTION_STATE_CONNECTED); } private void injectNoVerifyDeviceDisconnected(BluetoothDevice device) { - generateUnexpectedConnectionMessageFromNative(device, + generateUnexpectedConnectionMessageFromNative( + device, LeAudioStackEvent.CONNECTION_STATE_DISCONNECTED, LeAudioStackEvent.CONNECTION_STATE_CONNECTED); } - /** - * Test that the outgoing connect/disconnect and audio switch is successful. - */ + + /** Test that the outgoing connect/disconnect and audio switch is successful. */ @Test public void testAudioManagerConnectDisconnect() { // Update the device priority so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mDatabaseManager - .getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mDatabaseManager - .getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); @@ -615,38 +634,50 @@ public class LeAudioServiceTest { assertWithMessage("Connect failed").that(mService.connect(mRightDevice)).isTrue(); // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, mLeftDevice, BluetoothProfile.STATE_CONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(mService.getConnectionState(mLeftDevice)) .isEqualTo(BluetoothProfile.STATE_CONNECTING); - verifyConnectionStateIntent(TIMEOUT_MS, mRightDevice, BluetoothProfile.STATE_CONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mRightDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(mService.getConnectionState(mRightDevice)) .isEqualTo(BluetoothProfile.STATE_CONNECTING); LeAudioStackEvent connCompletedEvent; // Send a message to trigger connection completed - connCompletedEvent = new LeAudioStackEvent( - LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connCompletedEvent = + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = mLeftDevice; connCompletedEvent.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_CONNECTED; mService.messageFromNative(connCompletedEvent); // Verify the connection state broadcast, and that we are in Connected state - verifyConnectionStateIntent(TIMEOUT_MS, mLeftDevice, BluetoothProfile.STATE_CONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); assertThat(mService.getConnectionState(mLeftDevice)) .isEqualTo(BluetoothProfile.STATE_CONNECTED); // Send a message to trigger connection completed for right side - connCompletedEvent = new LeAudioStackEvent( - LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connCompletedEvent = + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = mRightDevice; connCompletedEvent.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_CONNECTED; mService.messageFromNative(connCompletedEvent); // Verify the connection state broadcast, and that we are in Connected state for right side - verifyConnectionStateIntent(TIMEOUT_MS, mRightDevice, BluetoothProfile.STATE_CONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mRightDevice, + BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); assertThat(mService.getConnectionState(mRightDevice)) .isEqualTo(BluetoothProfile.STATE_CONNECTED); @@ -660,37 +691,49 @@ public class LeAudioServiceTest { assertWithMessage("Disconnect failed").that(mService.disconnect(mRightDevice)).isTrue(); // Verify the connection state broadcast, and that we are in Disconnecting state - verifyConnectionStateIntent(TIMEOUT_MS, mLeftDevice, BluetoothProfile.STATE_DISCONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED); assertThat(BluetoothProfile.STATE_DISCONNECTING) .isEqualTo(mService.getConnectionState(mLeftDevice)); - verifyConnectionStateIntent(TIMEOUT_MS, mRightDevice, BluetoothProfile.STATE_DISCONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mRightDevice, + BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED); assertThat(BluetoothProfile.STATE_DISCONNECTING) .isEqualTo(mService.getConnectionState(mRightDevice)); // Send a message to trigger disconnection completed - connCompletedEvent = new LeAudioStackEvent( - LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connCompletedEvent = + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = mLeftDevice; connCompletedEvent.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_DISCONNECTED; mService.messageFromNative(connCompletedEvent); // Verify the connection state broadcast, and that we are in Disconnected state - verifyConnectionStateIntent(TIMEOUT_MS, mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTING); assertThat(BluetoothProfile.STATE_DISCONNECTED) .isEqualTo(mService.getConnectionState(mLeftDevice)); // Send a message to trigger disconnection completed to the right device - connCompletedEvent = new LeAudioStackEvent( - LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connCompletedEvent = + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = mRightDevice; connCompletedEvent.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_DISCONNECTED; mService.messageFromNative(connCompletedEvent); // Verify the connection state broadcast, and that we are in Disconnected state - verifyConnectionStateIntent(TIMEOUT_MS, mRightDevice, BluetoothProfile.STATE_DISCONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mRightDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTING); assertThat(BluetoothProfile.STATE_DISCONNECTED) .isEqualTo(mService.getConnectionState(mRightDevice)); @@ -707,14 +750,11 @@ public class LeAudioServiceTest { @Test public void testCreateStateMachineStackEvents() { // Update the device priority so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mDatabaseManager - .getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - when(mDatabaseManager - .getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); @@ -723,14 +763,18 @@ public class LeAudioServiceTest { assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); // Le Audio stack event: CONNECTION_STATE_CONNECTING - state machine should be created - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_CONNECTING, + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(BluetoothProfile.STATE_CONNECTING) .isEqualTo(mService.getConnectionState(mLeftDevice)); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); // LeAudio stack event: CONNECTION_STATE_DISCONNECTED - state machine should be removed - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); assertThat(BluetoothProfile.STATE_DISCONNECTED) .isEqualTo(mService.getConnectionState(mLeftDevice)); @@ -740,20 +784,22 @@ public class LeAudioServiceTest { // Remove bond will remove also device descriptor. Device has to be connected again assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); - verifyConnectionStateIntent(LeAudioStateMachine.sConnectTimeoutMs * 2, - mLeftDevice, BluetoothProfile.STATE_CONNECTING, + verifyConnectionStateIntent( + LeAudioStateMachine.sConnectTimeoutMs * 2, + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); // stack event: CONNECTION_STATE_CONNECTED - state machine should be created - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_CONNECTING); + generateConnectionMessageFromNative( + mLeftDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); assertThat(BluetoothProfile.STATE_CONNECTED) .isEqualTo(mService.getConnectionState(mLeftDevice)); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); // stack event: CONNECTION_STATE_DISCONNECTED - state machine should be removed - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + generateConnectionMessageFromNative( + mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); assertThat(BluetoothProfile.STATE_DISCONNECTED) .isEqualTo(mService.getConnectionState(mLeftDevice)); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); @@ -761,7 +807,8 @@ public class LeAudioServiceTest { assertThat(mService.getDevices().contains(mLeftDevice)).isFalse(); // stack event: CONNECTION_STATE_DISCONNECTING - state machine should not be created - generateUnexpectedConnectionMessageFromNative(mLeftDevice, + generateUnexpectedConnectionMessageFromNative( + mLeftDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(BluetoothProfile.STATE_DISCONNECTED) @@ -769,7 +816,8 @@ public class LeAudioServiceTest { assertThat(mService.getDevices().contains(mLeftDevice)).isFalse(); // stack event: CONNECTION_STATE_DISCONNECTED - state machine should not be created - generateUnexpectedConnectionMessageFromNative(mLeftDevice, + generateUnexpectedConnectionMessageFromNative( + mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTED); assertThat(BluetoothProfile.STATE_DISCONNECTED) @@ -783,14 +831,11 @@ public class LeAudioServiceTest { @Test public void testDeleteStateMachineUnbondEvents() { // Update the device priority so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mDatabaseManager - .getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - when(mDatabaseManager - .getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); @@ -799,7 +844,9 @@ public class LeAudioServiceTest { assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); // LeAudio stack event: CONNECTION_STATE_CONNECTING - state machine should be created - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_CONNECTING, + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(mService.getConnectionState(mLeftDevice)) .isEqualTo(BluetoothProfile.STATE_CONNECTING); @@ -807,20 +854,26 @@ public class LeAudioServiceTest { // Device unbond - state machine is not removed mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_NONE); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); - verifyConnectionStateIntent(TIMEOUT_MS, mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); // LeAudio stack event: CONNECTION_STATE_CONNECTED - state machine is not removed mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_BONDED); - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + generateConnectionMessageFromNative( + mLeftDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); assertThat(mService.getConnectionState(mLeftDevice)) .isEqualTo(BluetoothProfile.STATE_CONNECTED); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); // Device unbond - state machine is not removed mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_NONE); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); - verifyConnectionStateIntent(TIMEOUT_MS, mLeftDevice, BluetoothProfile.STATE_DISCONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED); assertThat(mService.getConnectionState(mLeftDevice)) .isEqualTo(BluetoothProfile.STATE_DISCONNECTING); @@ -836,7 +889,9 @@ public class LeAudioServiceTest { // LeAudio stack event: CONNECTION_STATE_DISCONNECTED - state machine is not removed mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_BONDED); - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTING); assertThat(mService.getConnectionState(mLeftDevice)) .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); @@ -984,21 +1039,19 @@ public class LeAudioServiceTest { testAuthorizationInfoRemovedFromTbsMcsOnUnbondEvents(); } + /** - * Test that a CONNECTION_STATE_DISCONNECTED Le Audio stack event will remove the state - * machine only if the device is unbond. + * Test that a CONNECTION_STATE_DISCONNECTED Le Audio stack event will remove the state machine + * only if the device is unbond. */ @Test public void testDeleteStateMachineDisconnectEvents() { // Update the device priority so okToConnect() returns true - when(mDatabaseManager - .getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - when(mDatabaseManager - .getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - when(mDatabaseManager - .getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) + when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); @@ -1007,33 +1060,42 @@ public class LeAudioServiceTest { assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); // LeAudio stack event: CONNECTION_STATE_CONNECTING - state machine should be created - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_CONNECTING, + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(BluetoothProfile.STATE_CONNECTING) .isEqualTo(mService.getConnectionState(mLeftDevice)); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); // LeAudio stack event: CONNECTION_STATE_DISCONNECTED - state machine is not removed - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); assertThat(BluetoothProfile.STATE_DISCONNECTED) .isEqualTo(mService.getConnectionState(mLeftDevice)); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); // LeAudio stack event: CONNECTION_STATE_CONNECTING - state machine remains - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_CONNECTING, + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(BluetoothProfile.STATE_CONNECTING) .isEqualTo(mService.getConnectionState(mLeftDevice)); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); // Device bond state marked as unbond - state machine is not removed - doReturn(BluetoothDevice.BOND_NONE).when(mAdapterService) + doReturn(BluetoothDevice.BOND_NONE) + .when(mAdapterService) .getBondState(any(BluetoothDevice.class)); assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); // LeAudio stack event: CONNECTION_STATE_DISCONNECTED - state machine is removed - generateConnectionMessageFromNative(mLeftDevice, BluetoothProfile.STATE_DISCONNECTED, + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); assertThat(BluetoothProfile.STATE_DISCONNECTED) .isEqualTo(mService.getConnectionState(mLeftDevice)); @@ -1054,23 +1116,28 @@ public class LeAudioServiceTest { assertWithMessage("Connect failed").that(mService.connect(device)).isTrue(); // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, device, BluetoothProfile.STATE_CONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + device, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(BluetoothProfile.STATE_CONNECTING) .isEqualTo(mService.getConnectionState(device)); // Send a message to trigger connection completed - connCompletedEvent = new LeAudioStackEvent( - LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connCompletedEvent = + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = device; connCompletedEvent.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_CONNECTED; mService.messageFromNative(connCompletedEvent); // Verify the connection state broadcast, and that we are in Connected state - verifyConnectionStateIntent(TIMEOUT_MS, device, BluetoothProfile.STATE_CONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + device, + BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); - assertThat(BluetoothProfile.STATE_CONNECTED) - .isEqualTo(mService.getConnectionState(device)); + assertThat(BluetoothProfile.STATE_CONNECTED).isEqualTo(mService.getConnectionState(device)); // Verify that the device is in the list of connected devices assertThat(mService.getConnectedDevices().contains(device)).isTrue(); @@ -1080,8 +1147,8 @@ public class LeAudioServiceTest { } } - private void generateConnectionMessageFromNative(BluetoothDevice device, int newConnectionState, - int oldConnectionState) { + private void generateConnectionMessageFromNative( + BluetoothDevice device, int newConnectionState, int oldConnectionState) { LeAudioStackEvent stackEvent = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); stackEvent.device = device; @@ -1091,8 +1158,8 @@ public class LeAudioServiceTest { verifyConnectionStateIntent(TIMEOUT_MS, device, newConnectionState, oldConnectionState); } - private void generateUnexpectedConnectionMessageFromNative(BluetoothDevice device, - int newConnectionState, int oldConnectionState) { + private void generateUnexpectedConnectionMessageFromNative( + BluetoothDevice device, int newConnectionState, int oldConnectionState) { LeAudioStackEvent stackEvent = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); stackEvent.device = device; @@ -1104,7 +1171,7 @@ public class LeAudioServiceTest { private void generateGroupNodeAdded(BluetoothDevice device, int groupId) { LeAudioStackEvent nodeGroupAdded = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_NODE_STATUS_CHANGED); + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_NODE_STATUS_CHANGED); nodeGroupAdded.device = device; nodeGroupAdded.valueInt1 = groupId; nodeGroupAdded.valueInt2 = LeAudioStackEvent.GROUP_NODE_ADDED; @@ -1113,7 +1180,7 @@ public class LeAudioServiceTest { private void generateGroupNodeRemoved(BluetoothDevice device, int groupId) { LeAudioStackEvent nodeGroupRemoved = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_NODE_STATUS_CHANGED); + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_NODE_STATUS_CHANGED); nodeGroupRemoved.device = device; nodeGroupRemoved.valueInt1 = groupId; nodeGroupRemoved.valueInt2 = LeAudioStackEvent.GROUP_NODE_REMOVED; @@ -1125,88 +1192,103 @@ public class LeAudioServiceTest { assertThat(intent).isNull(); } - /** - * Test setting connection policy - */ + /** Test setting connection policy */ @Test public void testSetConnectionPolicy() { doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); - doReturn(true).when(mDatabaseManager).setProfileConnectionPolicy(any(BluetoothDevice.class), - anyInt(), anyInt()); + doReturn(true) + .when(mDatabaseManager) + .setProfileConnectionPolicy(any(BluetoothDevice.class), anyInt(), anyInt()); when(mVolumeControlService.setConnectionPolicy(any(), anyInt())).thenReturn(true); when(mCsipSetCoordinatorService.setConnectionPolicy(any(), anyInt())).thenReturn(true); when(mHapClientService.setConnectionPolicy(any(), anyInt())).thenReturn(true); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - assertThat(mService.setConnectionPolicy(mSingleDevice, - BluetoothProfile.CONNECTION_POLICY_ALLOWED)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED)) + .isTrue(); // Verify connection policy for CSIP and VCP are also set - verify(mVolumeControlService, times(1)).setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); - verify(mCsipSetCoordinatorService, times(1)).setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); - verify(mHapClientService, times(1)).setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + verify(mVolumeControlService, times(1)) + .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + verify(mCsipSetCoordinatorService, times(1)) + .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + verify(mHapClientService, times(1)) + .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, mSingleDevice, BluetoothProfile.STATE_CONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mSingleDevice, + BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); assertThat(BluetoothProfile.STATE_CONNECTING) .isEqualTo(mService.getConnectionState(mSingleDevice)); LeAudioStackEvent connCompletedEvent; // Send a message to trigger connection completed - connCompletedEvent = new LeAudioStackEvent( - LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connCompletedEvent = + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = mSingleDevice; connCompletedEvent.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_CONNECTED; mService.messageFromNative(connCompletedEvent); // Verify the connection state broadcast, and that we are in Connected state - verifyConnectionStateIntent(TIMEOUT_MS, mSingleDevice, BluetoothProfile.STATE_CONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mSingleDevice, + BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); assertThat(BluetoothProfile.STATE_CONNECTED) .isEqualTo(mService.getConnectionState(mSingleDevice)); // Set connection policy to forbidden - assertThat(mService.setConnectionPolicy(mSingleDevice, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + .isTrue(); // Verify connection policy for CSIP and VCP are also set - verify(mVolumeControlService, times(1)).setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - verify(mCsipSetCoordinatorService, times(1)).setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - verify(mHapClientService, times(1)).setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + verify(mVolumeControlService, times(1)) + .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + verify(mCsipSetCoordinatorService, times(1)) + .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + verify(mHapClientService, times(1)) + .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, mSingleDevice, BluetoothProfile.STATE_DISCONNECTING, + verifyConnectionStateIntent( + TIMEOUT_MS, + mSingleDevice, + BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_CONNECTED); assertThat(BluetoothProfile.STATE_DISCONNECTING) .isEqualTo(mService.getConnectionState(mSingleDevice)); // Send a message to trigger disconnection completed - connCompletedEvent = new LeAudioStackEvent( - LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + connCompletedEvent = + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connCompletedEvent.device = mSingleDevice; connCompletedEvent.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_DISCONNECTED; mService.messageFromNative(connCompletedEvent); // Verify the connection state broadcast, and that we are in Disconnected state - verifyConnectionStateIntent(TIMEOUT_MS, mSingleDevice, BluetoothProfile.STATE_DISCONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + mSingleDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTING); assertThat(BluetoothProfile.STATE_DISCONNECTED) .isEqualTo(mService.getConnectionState(mSingleDevice)); } /** - * Helper function to connect Test device + * Helper function to connect Test device * - * @param device test device + * @param device test device */ private void connectTestDevice(BluetoothDevice device, int GroupId) { List prevConnectedDevices = mService.getConnectedDevices(); @@ -1223,8 +1305,11 @@ public class LeAudioServiceTest { // 250ms for processing two messages should be way more than enough. Anything that breaks // this indicate some breakage in other part of Android OS - verifyConnectionStateIntent(ASYNC_CALL_TIMEOUT_MILLIS, device, - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + verifyConnectionStateIntent( + ASYNC_CALL_TIMEOUT_MILLIS, + device, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED); assertThat(BluetoothProfile.STATE_CONNECTING) .isEqualTo(mService.getConnectionState(device)); @@ -1235,11 +1320,13 @@ public class LeAudioServiceTest { connCompletedEvent.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_CONNECTED; mService.messageFromNative(connCompletedEvent); - verifyConnectionStateIntent(ASYNC_CALL_TIMEOUT_MILLIS, device, - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); + verifyConnectionStateIntent( + ASYNC_CALL_TIMEOUT_MILLIS, + device, + BluetoothProfile.STATE_CONNECTED, + BluetoothProfile.STATE_CONNECTING); - assertThat(BluetoothProfile.STATE_CONNECTED) - .isEqualTo(mService.getConnectionState(device)); + assertThat(BluetoothProfile.STATE_CONNECTED).isEqualTo(mService.getConnectionState(device)); LeAudioStackEvent nodeGroupAdded = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_NODE_STATUS_CHANGED); @@ -1252,13 +1339,11 @@ public class LeAudioServiceTest { assertThat(mService.getConnectedDevices().contains(device)).isTrue(); // Verify the list of previously connected devices for (BluetoothDevice prevDevice : prevConnectedDevices) { - assertThat(mService.getConnectedDevices().contains(prevDevice)).isTrue(); + assertThat(mService.getConnectedDevices().contains(prevDevice)).isTrue(); } } - /** - * Test adding node - */ + /** Test adding node */ @Test public void testGroupAddRemoveNode() { int groupId = 1; @@ -1270,9 +1355,7 @@ public class LeAudioServiceTest { assertThat(mService.groupRemoveNode(groupId, mSingleDevice)).isTrue(); } - /** - * Test setting active device group with Ringtone context - */ + /** Test setting active device group with Ringtone context */ @Test public void testSetActiveDeviceGroup() { int groupId = 1; @@ -1303,7 +1386,7 @@ public class LeAudioServiceTest { assertThat(mService.setActiveDevice(mSingleDevice)).isTrue(); verify(mNativeInterface).groupSetActive(groupId); - //Set group and device as active + // Set group and device as active LeAudioStackEvent groupStatusChangedEvent = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED); groupStatusChangedEvent.valueInt1 = groupId; @@ -1316,7 +1399,7 @@ public class LeAudioServiceTest { assertThat(mService.removeActiveDevice(false)).isTrue(); verify(mNativeInterface).groupSetActive(BluetoothLeAudio.GROUP_ID_INVALID); - //Set group and device as inactive active + // Set group and device as inactive active groupStatusChangedEvent.valueInt2 = LeAudioStackEvent.GROUP_STATUS_INACTIVE; mService.messageFromNative(groupStatusChangedEvent); @@ -1531,9 +1614,7 @@ public class LeAudioServiceTest { mSingleDevice_2, AudioDeviceInfo.TYPE_BLE_HEADSET, true, false, true); } - /** - * Test setting active device group without Ringtone context - */ + /** Test setting active device group without Ringtone context */ @Test public void testSetActiveDeviceGroupWithoutRingtoneContext() { int groupId = 1; @@ -1550,9 +1631,9 @@ public class LeAudioServiceTest { doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); connectTestDevice(mSingleDevice, testGroupId); - // Add location support + // Add location support LeAudioStackEvent audioConfChangedEvent = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_AUDIO_CONF_CHANGED); + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_AUDIO_CONF_CHANGED); audioConfChangedEvent.device = mSingleDevice; audioConfChangedEvent.valueInt1 = direction; audioConfChangedEvent.valueInt2 = groupId; @@ -1564,8 +1645,7 @@ public class LeAudioServiceTest { assertThat(mService.setActiveDevice(mSingleDevice)).isTrue(); verify(mNativeInterface).groupSetActive(groupId); - - //Set group and device as active + // Set group and device as active LeAudioStackEvent groupStatusChangedEvent = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED); groupStatusChangedEvent.valueInt1 = groupId; @@ -1576,7 +1656,7 @@ public class LeAudioServiceTest { assertThat(mService.removeActiveDevice(false)).isTrue(); verify(mNativeInterface).groupSetActive(BluetoothLeAudio.GROUP_ID_INVALID); - //Set group and device as inactive active + // Set group and device as inactive active groupStatusChangedEvent.valueInt2 = LeAudioStackEvent.GROUP_STATUS_INACTIVE; mService.messageFromNative(groupStatusChangedEvent); @@ -1626,9 +1706,7 @@ public class LeAudioServiceTest { verify(mNativeInterface, times(0)).groupSetActive(anyInt()); } - /** - * Test getting active device - */ + /** Test getting active device */ @Test public void testGetActiveDevices() { int groupId = 1; @@ -1799,45 +1877,44 @@ public class LeAudioServiceTest { assertThat(connInfos.get(4).isLeOutput()).isEqualTo(false); } - /** - * Test native interface audio configuration changed message handling - */ + /** Test native interface audio configuration changed message handling */ @Test public void testMessageFromNativeAudioConfChangedActiveGroup() { doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); connectTestDevice(mSingleDevice, testGroupId); - injectAudioConfChanged(testGroupId, BluetoothLeAudio.CONTEXT_TYPE_MEDIA | - BluetoothLeAudio.CONTEXT_TYPE_CONVERSATIONAL, 3); + injectAudioConfChanged( + testGroupId, + BluetoothLeAudio.CONTEXT_TYPE_MEDIA | BluetoothLeAudio.CONTEXT_TYPE_CONVERSATIONAL, + 3); injectGroupStatusChange(testGroupId, BluetoothLeAudio.GROUP_STATUS_ACTIVE); /* Expect 2 calles to Audio Manager - one for output and second for input as this is * Conversational use case */ - verify(mAudioManager, times(2)).handleBluetoothActiveDeviceChanged(any(), any(), - any(BluetoothProfileConnectionInfo.class)); + verify(mAudioManager, times(2)) + .handleBluetoothActiveDeviceChanged( + any(), any(), any(BluetoothProfileConnectionInfo.class)); /* Since LeAudioService called AudioManager - assume Audio manager calles properly callback * mAudioManager.onAudioDeviceAdded */ injectAudioDeviceAdded(mSingleDevice, AudioDeviceInfo.TYPE_BLE_HEADSET, true, false, true); } - /** - * Test native interface audio configuration changed message handling - */ + + /** Test native interface audio configuration changed message handling */ @Test public void testMessageFromNativeAudioConfChangedInactiveGroup() { doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); connectTestDevice(mSingleDevice, testGroupId); String action = BluetoothLeAudio.ACTION_LE_AUDIO_ACTIVE_DEVICE_CHANGED; - Integer contexts = BluetoothLeAudio.CONTEXT_TYPE_MEDIA | - BluetoothLeAudio.CONTEXT_TYPE_CONVERSATIONAL; + Integer contexts = + BluetoothLeAudio.CONTEXT_TYPE_MEDIA | BluetoothLeAudio.CONTEXT_TYPE_CONVERSATIONAL; injectAudioConfChanged(testGroupId, contexts, 3); Intent intent = TestUtils.waitForNoIntent(TIMEOUT_MS, mDeviceQueueMap.get(mSingleDevice)); assertThat(intent).isNull(); } - /** - * Test native interface audio configuration changed message handling - */ + + /** Test native interface audio configuration changed message handling */ @Test public void testMessageFromNativeAudioConfChangedNoGroupChanged() { doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); @@ -1999,19 +2076,21 @@ public class LeAudioServiceTest { mService.mLeAudioCallbacks.unregister(leAudioCallbacks); } - /** - * Test native interface group status message handling - */ + /** Test native interface group status message handling */ @Test public void testMessageFromNativeGroupStatusChanged() { doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); connectTestDevice(mSingleDevice, testGroupId); - injectAudioConfChanged(testGroupId, BluetoothLeAudio.CONTEXT_TYPE_MEDIA | - BluetoothLeAudio.CONTEXT_TYPE_CONVERSATIONAL, 3); + injectAudioConfChanged( + testGroupId, + BluetoothLeAudio.CONTEXT_TYPE_MEDIA | BluetoothLeAudio.CONTEXT_TYPE_CONVERSATIONAL, + 3); - sendEventAndVerifyIntentForGroupStatusChanged(testGroupId, LeAudioStackEvent.GROUP_STATUS_ACTIVE); - sendEventAndVerifyIntentForGroupStatusChanged(testGroupId, LeAudioStackEvent.GROUP_STATUS_INACTIVE); + sendEventAndVerifyIntentForGroupStatusChanged( + testGroupId, LeAudioStackEvent.GROUP_STATUS_ACTIVE); + sendEventAndVerifyIntentForGroupStatusChanged( + testGroupId, LeAudioStackEvent.GROUP_STATUS_INACTIVE); } private void sendEventAndVerifyGroupStreamStatusChanged(int groupId, int groupStreamStatus) { @@ -2068,14 +2147,15 @@ public class LeAudioServiceTest { testGroupId, LeAudioStackEvent.GROUP_STREAM_STATUS_STREAMING); } - private void injectLocalCodecConfigCapaChanged(List inputCodecCapa, - List outputCodecCapa) { + private void injectLocalCodecConfigCapaChanged( + List inputCodecCapa, + List outputCodecCapa) { int eventType = LeAudioStackEvent.EVENT_TYPE_AUDIO_LOCAL_CODEC_CONFIG_CAPA_CHANGED; // Add device to group LeAudioStackEvent localCodecCapaEvent = new LeAudioStackEvent(eventType); localCodecCapaEvent.valueCodecList1 = inputCodecCapa; - localCodecCapaEvent.valueCodecList2 = outputCodecCapa; + localCodecCapaEvent.valueCodecList2 = outputCodecCapa; mService.messageFromNative(localCodecCapaEvent); } @@ -2103,13 +2183,11 @@ public class LeAudioServiceTest { LeAudioStackEvent groupCodecConfigChangedEvent = new LeAudioStackEvent(eventType); groupCodecConfigChangedEvent.valueInt1 = groupId; groupCodecConfigChangedEvent.valueCodecList1 = inputSelectableCodecConfig; - groupCodecConfigChangedEvent.valueCodecList2 = outputSelectableCodecConfig; + groupCodecConfigChangedEvent.valueCodecList2 = outputSelectableCodecConfig; mService.messageFromNative(groupCodecConfigChangedEvent); } - /** - * Test native interface group status message handling - */ + /** Test native interface group status message handling */ @Test public void testMessageFromNativeGroupCodecConfigChanged() { onGroupCodecConfChangedCallbackCalled = false; @@ -2119,10 +2197,14 @@ public class LeAudioServiceTest { doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); connectTestDevice(mSingleDevice, testGroupId); - testCodecStatus = new BluetoothLeAudioCodecStatus(LC3_16KHZ_CONFIG, - LC3_48KHZ_CONFIG, INPUT_CAPABILITIES_CONFIG, - OUTPUT_CAPABILITIES_CONFIG, INPUT_SELECTABLE_CONFIG, - OUTPUT_SELECTABLE_CONFIG); + testCodecStatus = + new BluetoothLeAudioCodecStatus( + LC3_16KHZ_CONFIG, + LC3_48KHZ_CONFIG, + INPUT_CAPABILITIES_CONFIG, + OUTPUT_CAPABILITIES_CONFIG, + INPUT_SELECTABLE_CONFIG, + OUTPUT_SELECTABLE_CONFIG); IBluetoothLeAudioCallback leAudioCallbacks = new IBluetoothLeAudioCallback.Stub() { @@ -2223,9 +2305,7 @@ public class LeAudioServiceTest { assertThat(device).isEqualTo(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); } - /** - * Test native interface group status message handling - */ + /** Test native interface group status message handling */ @Test public void testLeadGroupDeviceDisconnects() { int groupId = 1; @@ -2233,7 +2313,8 @@ public class LeAudioServiceTest { int direction = 1; int snkAudioLocation = 3; int srcAudioLocation = 4; - int availableContexts = 5 + BluetoothLeAudio.CONTEXT_TYPE_RINGTONE;; + int availableContexts = 5 + BluetoothLeAudio.CONTEXT_TYPE_RINGTONE; + ; int groupStatus = LeAudioStackEvent.GROUP_STATUS_ACTIVE; BluetoothDevice leadDevice; BluetoothDevice memberDevice = mLeftDevice; @@ -2244,12 +2325,12 @@ public class LeAudioServiceTest { leadDevice = mService.getConnectedGroupLeadDevice(groupId); if (Objects.equals(leadDevice, mLeftDevice)) { - memberDevice = mRightDevice; + memberDevice = mRightDevice; } assertThat(mService.setActiveDevice(leadDevice)).isFalse(); - //Add location support + // Add location support LeAudioStackEvent audioConfChangedEvent = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_AUDIO_CONF_CHANGED); audioConfChangedEvent.valueInt1 = direction; @@ -2261,7 +2342,7 @@ public class LeAudioServiceTest { assertThat(mService.setActiveDevice(leadDevice)).isTrue(); - //Set group and device as active + // Set group and device as active LeAudioStackEvent groupStatusChangedEvent = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED); groupStatusChangedEvent.valueInt1 = groupId; @@ -2269,8 +2350,9 @@ public class LeAudioServiceTest { mService.messageFromNative(groupStatusChangedEvent); assertThat(mService.getActiveDevices().contains(leadDevice)).isTrue(); - verify(mAudioManager, times(1)).handleBluetoothActiveDeviceChanged(eq(leadDevice), any(), - any(BluetoothProfileConnectionInfo.class)); + verify(mAudioManager, times(1)) + .handleBluetoothActiveDeviceChanged( + eq(leadDevice), any(), any(BluetoothProfileConnectionInfo.class)); /* Since LeAudioService called AudioManager - assume Audio manager calles properly callback * mAudioManager.onAudioDeviceAdded */ @@ -2285,19 +2367,21 @@ public class LeAudioServiceTest { injectAndVerifyDeviceDisconnected(memberDevice); // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, leadDevice, BluetoothProfile.STATE_DISCONNECTED, + verifyConnectionStateIntent( + TIMEOUT_MS, + leadDevice, + BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); - verify(mAudioManager, times(1)).handleBluetoothActiveDeviceChanged(any(), eq(leadDevice), - any(BluetoothProfileConnectionInfo.class)); + verify(mAudioManager, times(1)) + .handleBluetoothActiveDeviceChanged( + any(), eq(leadDevice), any(BluetoothProfileConnectionInfo.class)); verify(mTbsService).setInbandRingtoneSupport(mLeftDevice); verify(mTbsService).setInbandRingtoneSupport(mRightDevice); } - /** - * Test native interface group status message handling - */ + /** Test native interface group status message handling */ @Test public void testLeadGroupDeviceReconnects() { int groupId = 1; @@ -2305,7 +2389,8 @@ public class LeAudioServiceTest { int direction = 1; int snkAudioLocation = 3; int srcAudioLocation = 4; - int availableContexts = 5 + BluetoothLeAudio.CONTEXT_TYPE_RINGTONE;; + int availableContexts = 5 + BluetoothLeAudio.CONTEXT_TYPE_RINGTONE; + ; int groupStatus = LeAudioStackEvent.GROUP_STATUS_ACTIVE; BluetoothDevice leadDevice; BluetoothDevice memberDevice = mLeftDevice; @@ -2316,12 +2401,12 @@ public class LeAudioServiceTest { leadDevice = mService.getConnectedGroupLeadDevice(groupId); if (Objects.equals(leadDevice, mLeftDevice)) { - memberDevice = mRightDevice; + memberDevice = mRightDevice; } assertThat(mService.setActiveDevice(leadDevice)).isFalse(); - //Add location support + // Add location support LeAudioStackEvent audioConfChangedEvent = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_AUDIO_CONF_CHANGED); audioConfChangedEvent.valueInt1 = direction; @@ -2333,7 +2418,7 @@ public class LeAudioServiceTest { assertThat(mService.setActiveDevice(leadDevice)).isTrue(); - //Set group and device as active + // Set group and device as active LeAudioStackEvent groupStatusChangedEvent = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED); groupStatusChangedEvent.valueInt1 = groupId; @@ -2341,8 +2426,9 @@ public class LeAudioServiceTest { mService.messageFromNative(groupStatusChangedEvent); assertThat(mService.getActiveDevices().contains(leadDevice)).isTrue(); - verify(mAudioManager, times(1)).handleBluetoothActiveDeviceChanged(eq(leadDevice), any(), - any(BluetoothProfileConnectionInfo.class)); + verify(mAudioManager, times(1)) + .handleBluetoothActiveDeviceChanged( + eq(leadDevice), any(), any(BluetoothProfileConnectionInfo.class)); /* Since LeAudioService called AudioManager - assume Audio manager calles properly callback * mAudioManager.onAudioDeviceAdded */ @@ -2363,16 +2449,15 @@ public class LeAudioServiceTest { injectAndVerifyDeviceDisconnected(memberDevice); injectAndVerifyDeviceDisconnected(leadDevice); - verify(mAudioManager, times(1)).handleBluetoothActiveDeviceChanged(eq(null), eq(leadDevice), - any(BluetoothProfileConnectionInfo.class)); + verify(mAudioManager, times(1)) + .handleBluetoothActiveDeviceChanged( + eq(null), eq(leadDevice), any(BluetoothProfileConnectionInfo.class)); verify(mTbsService).setInbandRingtoneSupport(mLeftDevice); verify(mTbsService).setInbandRingtoneSupport(mRightDevice); } - /** - * Test volume caching for the group - */ + /** Test volume caching for the group */ @Test public void testVolumeCache() { int groupId = 1; @@ -2388,20 +2473,20 @@ public class LeAudioServiceTest { assertThat(mService.setActiveDevice(mLeftDevice)).isFalse(); ArgumentCaptor profileInfo = - ArgumentCaptor.forClass(BluetoothProfileConnectionInfo.class); + ArgumentCaptor.forClass(BluetoothProfileConnectionInfo.class); - //Add location support. + // Add location support. injectAudioConfChanged(groupId, availableContexts, direction); assertThat(mService.setActiveDevice(mLeftDevice)).isTrue(); TestUtils.waitForLooperToFinishScheduledTask(mService.getMainLooper()); doReturn(-1).when(mVolumeControlService).getAudioDeviceGroupVolume(groupId); - //Set group and device as active. + // Set group and device as active. injectGroupStatusChange(groupId, LeAudioStackEvent.GROUP_STATUS_ACTIVE); - verify(mAudioManager, times(1)).handleBluetoothActiveDeviceChanged(any(), eq(null), - profileInfo.capture()); + verify(mAudioManager, times(1)) + .handleBluetoothActiveDeviceChanged(any(), eq(null), profileInfo.capture()); assertThat(profileInfo.getValue().getVolume()).isEqualTo(-1); mService.setVolume(volume); @@ -2410,17 +2495,18 @@ public class LeAudioServiceTest { // Set group to inactive. injectGroupStatusChange(groupId, LeAudioStackEvent.GROUP_STATUS_INACTIVE); - verify(mAudioManager, times(1)).handleBluetoothActiveDeviceChanged(eq(null), any(), - any(BluetoothProfileConnectionInfo.class)); + verify(mAudioManager, times(1)) + .handleBluetoothActiveDeviceChanged( + eq(null), any(), any(BluetoothProfileConnectionInfo.class)); TestUtils.waitForLooperToFinishScheduledTask(mService.getMainLooper()); doReturn(100).when(mVolumeControlService).getAudioDeviceGroupVolume(groupId); - //Set back to active and check if last volume is restored. + // Set back to active and check if last volume is restored. injectGroupStatusChange(groupId, LeAudioStackEvent.GROUP_STATUS_ACTIVE); - verify(mAudioManager, times(2)).handleBluetoothActiveDeviceChanged(any(), eq(null), - profileInfo.capture()); + verify(mAudioManager, times(2)) + .handleBluetoothActiveDeviceChanged(any(), eq(null), profileInfo.capture()); assertThat(profileInfo.getValue().getVolume()).isEqualTo(volume); } @@ -2520,11 +2606,11 @@ public class LeAudioServiceTest { public void testGetDevicesMatchingConnectionStates() { assertThat(mService.getDevicesMatchingConnectionStates(null)).isEmpty(); - int[] states = new int[] { BluetoothProfile.STATE_CONNECTED }; + int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; doReturn(null).when(mAdapterService).getBondedDevices(); assertThat(mService.getDevicesMatchingConnectionStates(states)).isEmpty(); - doReturn(new BluetoothDevice[] { mSingleDevice }).when(mAdapterService).getBondedDevices(); + doReturn(new BluetoothDevice[] {mSingleDevice}).when(mAdapterService).getBondedDevices(); assertThat(mService.getDevicesMatchingConnectionStates(states)).isEmpty(); } @@ -2562,11 +2648,11 @@ public class LeAudioServiceTest { @Test public void testDump_doesNotCrash() { - doReturn(new ParcelUuid[]{BluetoothUuid.LE_AUDIO}).when(mAdapterService) + doReturn(new ParcelUuid[] {BluetoothUuid.LE_AUDIO}) + .when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - doReturn(new BluetoothDevice[]{mSingleDevice}).when(mAdapterService).getBondedDevices(); - when(mDatabaseManager - .getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) + doReturn(new BluetoothDevice[] {mSingleDevice}).when(mAdapterService).getBondedDevices(); + when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); @@ -2577,9 +2663,7 @@ public class LeAudioServiceTest { mService.dump(sb); } - /** - * Test setting authorization for LeAudio device in the McpService - */ + /** Test setting authorization for LeAudio device in the McpService */ @Test public void testAuthorizeMcpServiceWhenDeviceConnecting() { int groupId = 1; @@ -2592,9 +2676,7 @@ public class LeAudioServiceTest { verify(mMcpService, times(1)).setDeviceAuthorized(mRightDevice, true); } - /** - * Test setting authorization for LeAudio device in the McpService - */ + /** Test setting authorization for LeAudio device in the McpService */ @Test public void testAuthorizeMcpServiceOnBluetoothEnableAndNodeRemoval() { int groupId = 1; @@ -2622,10 +2704,10 @@ public class LeAudioServiceTest { } /** - * Test verifying that when the LE Audio connection policy of a device is set to - * {@link BluetoothProfile#CONNECTION_POLICY_FORBIDDEN}, we unauthorize McpService and - * TbsService. When the LE Audio connection policy is set to - * {@link BluetoothProfile#CONNECTION_POLICY_ALLOWED}, we will authorize these services. + * Test verifying that when the LE Audio connection policy of a device is set to {@link + * BluetoothProfile#CONNECTION_POLICY_FORBIDDEN}, we unauthorize McpService and TbsService. When + * the LE Audio connection policy is set to {@link BluetoothProfile#CONNECTION_POLICY_ALLOWED}, + * we will authorize these services. */ @Test public void testMcsAndTbsAuthorizationWithConnectionPolicy() { @@ -2634,14 +2716,17 @@ public class LeAudioServiceTest { mService.handleBluetoothEnabled(); doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); - doReturn(true).when(mDatabaseManager).setProfileConnectionPolicy(any(BluetoothDevice.class), - anyInt(), anyInt()); + doReturn(true) + .when(mDatabaseManager) + .setProfileConnectionPolicy(any(BluetoothDevice.class), anyInt(), anyInt()); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); // Ensures GATT server services are not authorized when the device does not have a group - assertThat(mService.setConnectionPolicy(mSingleDevice, - BluetoothProfile.CONNECTION_POLICY_ALLOWED)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED)) + .isTrue(); verify(mMcpService, never()).setDeviceAuthorized(mSingleDevice, false); verify(mTbsService, never()).setDeviceAuthorized(mSingleDevice, false); @@ -2651,14 +2736,18 @@ public class LeAudioServiceTest { verify(mTbsService, times(1)).setDeviceAuthorized(mSingleDevice, true); // Ensure that disconnecting unauthorizes GATT server services - assertThat(mService.setConnectionPolicy(mSingleDevice, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + .isTrue(); verify(mMcpService, times(1)).setDeviceAuthorized(mSingleDevice, false); verify(mTbsService, times(1)).setDeviceAuthorized(mSingleDevice, false); // Connecting a device that has a group re-authorizes the GATT server services - assertThat(mService.setConnectionPolicy(mSingleDevice, - BluetoothProfile.CONNECTION_POLICY_ALLOWED)).isTrue(); + assertThat( + mService.setConnectionPolicy( + mSingleDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED)) + .isTrue(); verify(mMcpService, times(2)).setDeviceAuthorized(mSingleDevice, true); verify(mTbsService, times(2)).setDeviceAuthorized(mSingleDevice, true); } @@ -2676,8 +2765,8 @@ public class LeAudioServiceTest { // Checks group device lists for groupId 1 List firstGroupDevicesById = mService.getGroupDevices(firstGroupId); List firstGroupDevicesByLeftDevice = mService.getGroupDevices(mLeftDevice); - List firstGroupDevicesByRightDevice = mService.getGroupDevices( - mRightDevice); + List firstGroupDevicesByRightDevice = + mService.getGroupDevices(mRightDevice); assertThat(firstGroupDevicesById.size()).isEqualTo(2); assertThat(firstGroupDevicesById.contains(mLeftDevice)).isTrue(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java index 2921483669d..7f28da4771b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java @@ -98,13 +98,11 @@ public class LeAudioStateMachineTest { TestUtils.clearAdapterService(mAdapterService); } - /** - * Test that default state is disconnected - */ + /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { - assertThat(BluetoothProfile.STATE_DISCONNECTED).isEqualTo( - mLeAudioStateMachine.getConnectionState()); + assertThat(BluetoothProfile.STATE_DISCONNECTED) + .isEqualTo(mLeAudioStateMachine.getConnectionState()); } /** @@ -116,9 +114,7 @@ public class LeAudioStateMachineTest { doReturn(allow).when(mLeAudioService).okToConnect(any(BluetoothDevice.class)); } - /** - * Test that an incoming connection with low priority is rejected - */ + /** Test that an incoming connection with low priority is rejected */ @Test public void testIncomingPriorityReject() { allowConnection(false); @@ -131,23 +127,21 @@ public class LeAudioStateMachineTest { mLeAudioStateMachine.sendMessage(LeAudioStateMachine.STACK_EVENT, connStCh); // Verify that no connection state broadcast is executed - verify(mLeAudioService, after(TIMEOUT_MS).never()).sendBroadcast(any(Intent.class), - anyString(), any(Bundle.class)); + verify(mLeAudioService, after(TIMEOUT_MS).never()) + .sendBroadcast(any(Intent.class), anyString(), any(Bundle.class)); // Check that we are in Disconnected state assertThat(mLeAudioStateMachine.getCurrentState()) .isInstanceOf(LeAudioStateMachine.Disconnected.class); } - /** - * Test that an incoming connection with high priority is accepted - */ + /** Test that an incoming connection with high priority is accepted */ @Test public void testIncomingPriorityAccept() { allowConnection(true); // Inject an event for when incoming connection is requested LeAudioStackEvent connStCh = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); + new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); connStCh.device = mTestDevice; connStCh.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_CONNECTING; mLeAudioStateMachine.sendMessage(LeAudioStateMachine.STACK_EVENT, connStCh); @@ -181,16 +175,12 @@ public class LeAudioStateMachineTest { .isInstanceOf(LeAudioStateMachine.Connected.class); } - /** - * Test that an outgoing connection times out - */ + /** Test that an outgoing connection times out */ @Test public void testOutgoingTimeout() { allowConnection(true); - doReturn(true).when(mLeAudioNativeInterface).connectLeAudio(any( - BluetoothDevice.class)); - doReturn(true).when(mLeAudioNativeInterface).disconnectLeAudio(any( - BluetoothDevice.class)); + doReturn(true).when(mLeAudioNativeInterface).connectLeAudio(any(BluetoothDevice.class)); + doReturn(true).when(mLeAudioNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); // Send a connect request mLeAudioStateMachine.sendMessage(LeAudioStateMachine.CONNECT, mTestDevice); @@ -214,16 +204,12 @@ public class LeAudioStateMachineTest { .isInstanceOf(LeAudioStateMachine.Disconnected.class); } - /** - * Test that an incoming connection times out - */ + /** Test that an incoming connection times out */ @Test public void testIncomingTimeout() { allowConnection(true); - doReturn(true).when(mLeAudioNativeInterface).connectLeAudio(any( - BluetoothDevice.class)); - doReturn(true).when(mLeAudioNativeInterface).disconnectLeAudio(any( - BluetoothDevice.class)); + doReturn(true).when(mLeAudioNativeInterface).connectLeAudio(any(BluetoothDevice.class)); + doReturn(true).when(mLeAudioNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); // Inject an event for when incoming connection is requested LeAudioStackEvent connStCh = diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioTmapGattServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioTmapGattServerTest.java index 6afe455ca19..0eea74fe333 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioTmapGattServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioTmapGattServerTest.java @@ -53,8 +53,7 @@ public class LeAudioTmapGattServerTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private LeAudioTmapGattServer.BluetoothGattServerProxy mGattServerProxy; + @Mock private LeAudioTmapGattServer.BluetoothGattServerProxy mGattServerProxy; private LeAudioTmapGattServer mServer; diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfoTest.java index 674278dee7d..c56769fa969 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfoTest.java @@ -24,9 +24,7 @@ import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; -/** - * Test cases for {@link AdvtFilterOnFoundOnLostInfoTest}. - */ +/** Test cases for {@link AdvtFilterOnFoundOnLostInfoTest}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class AdvtFilterOnFoundOnLostInfoTest { @@ -35,9 +33,9 @@ public class AdvtFilterOnFoundOnLostInfoTest { public void advtFilterOnFoundOnLostInfoParams() { int clientIf = 0; int advPktLen = 1; - byte[] advPkt = new byte[]{0x02}; + byte[] advPkt = new byte[] {0x02}; int scanRspLen = 3; - byte[] scanRsp = new byte[]{0x04}; + byte[] scanRsp = new byte[] {0x04}; int filtIndex = 5; int advState = 6; int advInfoPresent = 7; @@ -47,21 +45,21 @@ public class AdvtFilterOnFoundOnLostInfoTest { int rssiValue = 10; int timeStamp = 11; - AdvtFilterOnFoundOnLostInfo advtFilterOnFoundOnLostInfo = new AdvtFilterOnFoundOnLostInfo( - clientIf, - advPktLen, - advPkt, - scanRspLen, - scanRsp, - filtIndex, - advState, - advInfoPresent, - address, - addrType, - txPower, - rssiValue, - timeStamp - ); + AdvtFilterOnFoundOnLostInfo advtFilterOnFoundOnLostInfo = + new AdvtFilterOnFoundOnLostInfo( + clientIf, + advPktLen, + advPkt, + scanRspLen, + scanRsp, + filtIndex, + advState, + advInfoPresent, + address, + addrType, + txPower, + rssiValue, + timeStamp); assertThat(advtFilterOnFoundOnLostInfo.getClientIf()).isEqualTo(clientIf); assertThat(advtFilterOnFoundOnLostInfo.getFiltIndex()).isEqualTo(filtIndex); @@ -77,7 +75,7 @@ public class AdvtFilterOnFoundOnLostInfoTest { assertThat(advtFilterOnFoundOnLostInfo.getScanRspData()).isEqualTo(scanRsp); assertThat(advtFilterOnFoundOnLostInfo.getScanRspLen()).isEqualTo(scanRspLen); - byte[] resultByteArray = new byte[]{2, 4}; + byte[] resultByteArray = new byte[] {2, 4}; assertThat(advtFilterOnFoundOnLostInfo.getResult()).isEqualTo(resultByteArray); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/AppScanStatsTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/AppScanStatsTest.java index d7b92e0ec6d..93ae20319b7 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/AppScanStatsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/AppScanStatsTest.java @@ -47,20 +47,16 @@ import org.mockito.junit.MockitoRule; import java.util.ArrayList; import java.util.List; -/** - * Test cases for {@link AppScanStats}. - */ +/** Test cases for {@link AppScanStats}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class AppScanStatsTest { - @Rule - public final ServiceTestRule mServiceRule = new ServiceTestRule(); + @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule(); @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private ContextMap map; + @Mock private ContextMap map; @Mock private Context mMockContext; @Mock private TransitionalScanHelper mMockScanHelper; diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java index 973ae194964..55ae14f223e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java @@ -29,9 +29,7 @@ import org.junit.runner.RunWith; import java.util.UUID; -/** - * Test cases for {@link ScanFilterQueue}. - */ +/** Test cases for {@link ScanFilterQueue}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class ScanFilterQueueTest { @@ -42,7 +40,7 @@ public class ScanFilterQueueTest { String address = "address"; byte type = 1; - byte[] irk = new byte[]{0x02}; + byte[] irk = new byte[] {0x02}; queue.addDeviceAddress(address, type, irk); queue.addServiceChanged(); @@ -61,20 +59,20 @@ public class ScanFilterQueueTest { queue.addName(name); int company = 2; - byte[] data = new byte[]{0x04}; + byte[] data = new byte[] {0x04}; queue.addManufacturerData(company, data); int companyMask = 2; - byte[] dataMask = new byte[]{0x05}; + byte[] dataMask = new byte[] {0x05}; queue.addManufacturerData(company, companyMask, data, dataMask); - byte[] serviceData = new byte[]{0x06}; - byte[] serviceDataMask = new byte[]{0x08}; + byte[] serviceData = new byte[] {0x06}; + byte[] serviceDataMask = new byte[] {0x08}; queue.addServiceData(serviceData, serviceDataMask); int adType = 3; - byte[] adData = new byte[]{0x10}; - byte[] adDataMask = new byte[]{0x12}; + byte[] adData = new byte[] {0x10}; + byte[] adDataMask = new byte[] {0x12}; queue.addAdvertisingDataType(adType, adData, adDataMask); ScanFilterQueue.Entry[] entries = queue.toArray(); @@ -130,8 +128,8 @@ public class ScanFilterQueueTest { public void popFromQueue() { ScanFilterQueue queue = new ScanFilterQueue(); - byte[] serviceData = new byte[]{0x02}; - byte[] serviceDataMask = new byte[]{0x04}; + byte[] serviceData = new byte[] {0x02}; + byte[] serviceDataMask = new byte[] {0x04}; queue.addServiceData(serviceData, serviceDataMask); ScanFilterQueue.Entry entry = queue.pop(); @@ -143,8 +141,8 @@ public class ScanFilterQueueTest { public void checkFeatureSelection() { ScanFilterQueue queue = new ScanFilterQueue(); - byte[] serviceData = new byte[]{0x02}; - byte[] serviceDataMask = new byte[]{0x04}; + byte[] serviceData = new byte[] {0x02}; + byte[] serviceDataMask = new byte[] {0x04}; queue.addServiceData(serviceData, serviceDataMask); int feature = 1 << ScanFilterQueue.TYPE_SERVICE_DATA; @@ -155,8 +153,8 @@ public class ScanFilterQueueTest { public void convertQueueToArray() { ScanFilterQueue queue = new ScanFilterQueue(); - byte[] serviceData = new byte[]{0x02}; - byte[] serviceDataMask = new byte[]{0x04}; + byte[] serviceData = new byte[] {0x02}; + byte[] serviceDataMask = new byte[] {0x04}; queue.addServiceData(serviceData, serviceDataMask); ScanFilterQueue.Entry[] entries = queue.toArray(); @@ -182,15 +180,16 @@ public class ScanFilterQueueTest { byte[] serviceData = new byte[0]; int advertisingDataType = 1; - ScanFilter filter = new ScanFilter.Builder() - .setDeviceName(name) - .setDeviceAddress(deviceAddress) - .setServiceUuid(serviceUuid) - .setServiceSolicitationUuid(serviceSolicitationUuid) - .setManufacturerData(manufacturerId, manufacturerData) - .setServiceData(serviceDataUuid, serviceData) - .setAdvertisingDataType(advertisingDataType) - .build(); + ScanFilter filter = + new ScanFilter.Builder() + .setDeviceName(name) + .setDeviceAddress(deviceAddress) + .setServiceUuid(serviceUuid) + .setServiceSolicitationUuid(serviceSolicitationUuid) + .setManufacturerData(manufacturerId, manufacturerData) + .setServiceData(serviceDataUuid, serviceData) + .setAdvertisingDataType(advertisingDataType) + .build(); queue.addScanFilter(filter); int numOfEntries = 7; diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java index 6816b9654db..9746c58cb9a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java @@ -99,9 +99,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -/** - * Test cases for {@link ScanManager}. - */ +/** Test cases for {@link ScanManager}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class ScanManagerTest { @@ -140,7 +138,7 @@ public class ScanManagerTest { @Spy private GattObjectsFactory mFactory = GattObjectsFactory.getInstance(); @Mock private GattNativeInterface mNativeInterface; @Mock private ScanNativeInterface mScanNativeInterface; - @Mock private MetricsLogger mMetricsLogger; + @Mock private MetricsLogger mMetricsLogger; private AppScanStats mMockAppScanStats; private MockContentResolver mMockContentResolver; @@ -269,8 +267,7 @@ public class ScanManagerTest { } private ScanClient createScanClient( - int id, boolean isFiltered, int scanMode, - boolean isBatch, boolean isAutoBatch) { + int id, boolean isFiltered, int scanMode, boolean isBatch, boolean isAutoBatch) { return createScanClient(id, isFiltered, false, scanMode, isBatch, isAutoBatch); } @@ -297,12 +294,18 @@ public class ScanManagerTest { ScanSettings scanSettings = null; if (isBatch && isAutoBatch) { int autoCallbackType = CALLBACK_TYPE_ALL_MATCHES_AUTO_BATCH; - scanSettings = new ScanSettings.Builder().setScanMode(scanMode) - .setReportDelay(mScanReportDelay).setCallbackType(autoCallbackType) - .build(); + scanSettings = + new ScanSettings.Builder() + .setScanMode(scanMode) + .setReportDelay(mScanReportDelay) + .setCallbackType(autoCallbackType) + .build(); } else if (isBatch) { - scanSettings = new ScanSettings.Builder().setScanMode(scanMode) - .setReportDelay(mScanReportDelay).build(); + scanSettings = + new ScanSettings.Builder() + .setScanMode(scanMode) + .setReportDelay(mScanReportDelay) + .build(); } else { scanSettings = new ScanSettings.Builder().setScanMode(scanMode).build(); } @@ -347,9 +350,10 @@ public class ScanManagerTest { } private Message createImportanceMessage(boolean isForeground) { - final int importance = isForeground ? ActivityManager.RunningAppProcessInfo - .IMPORTANCE_FOREGROUND_SERVICE : ActivityManager.RunningAppProcessInfo - .IMPORTANCE_FOREGROUND_SERVICE + 1; + final int importance = + isForeground + ? ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE + : ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE + 1; final int uid = Binder.getCallingUid(); Message message = new Message(); message.what = ScanManager.MSG_IMPORTANCE_CHANGE; @@ -359,8 +363,8 @@ public class ScanManagerTest { private Message createConnectingMessage(boolean isConnectingOn) { Message message = new Message(); - message.what = isConnectingOn ? ScanManager.MSG_START_CONNECTING : - ScanManager.MSG_STOP_CONNECTING; + message.what = + isConnectingOn ? ScanManager.MSG_START_CONNECTING : ScanManager.MSG_STOP_CONNECTING; message.obj = null; return message; } @@ -379,8 +383,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -408,8 +416,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -438,8 +450,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -467,8 +483,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -496,8 +516,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -525,8 +549,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -559,8 +587,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -595,8 +627,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -642,8 +678,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen mHandler.sendMessage(createScreenOnOffMessage(true)); @@ -729,8 +769,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -768,8 +812,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -804,14 +852,18 @@ public class ScanManagerTest { scanModeMap.put(SCAN_MODE_LOW_LATENCY, SCAN_MODE_LOW_LATENCY); scanModeMap.put(SCAN_MODE_AMBIENT_DISCOVERY, SCAN_MODE_LOW_LATENCY); // Set scan upgrade duration through Mock - when(mAdapterService.getScanUpgradeDurationMillis()). - thenReturn((long) DELAY_SCAN_UPGRADE_DURATION_MS); + when(mAdapterService.getScanUpgradeDurationMillis()) + .thenReturn((long) DELAY_SCAN_UPGRADE_DURATION_MS); for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -842,17 +894,21 @@ public class ScanManagerTest { scanModeMap.put(SCAN_MODE_LOW_LATENCY, SCAN_MODE_BALANCED); scanModeMap.put(SCAN_MODE_AMBIENT_DISCOVERY, SCAN_MODE_BALANCED); // Set scan upgrade duration through Mock - when(mAdapterService.getScanUpgradeDurationMillis()). - thenReturn((long) DELAY_SCAN_UPGRADE_DURATION_MS); + when(mAdapterService.getScanUpgradeDurationMillis()) + .thenReturn((long) DELAY_SCAN_UPGRADE_DURATION_MS); // Set scan downgrade duration through Mock - when(mAdapterService.getScanDowngradeDurationMillis()). - thenReturn((long) DELAY_SCAN_DOWNGRADE_DURATION_MS); + when(mAdapterService.getScanDowngradeDurationMillis()) + .thenReturn((long) DELAY_SCAN_DOWNGRADE_DURATION_MS); for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -868,8 +924,10 @@ public class ScanManagerTest { assertThat(mScanManager.getSuspendedScanQueue().contains(client)).isFalse(); assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); // Wait for upgrade and downgrade duration - int max_duration = DELAY_SCAN_UPGRADE_DURATION_MS > DELAY_SCAN_DOWNGRADE_DURATION_MS ? - DELAY_SCAN_UPGRADE_DURATION_MS : DELAY_SCAN_DOWNGRADE_DURATION_MS; + int max_duration = + DELAY_SCAN_UPGRADE_DURATION_MS > DELAY_SCAN_DOWNGRADE_DURATION_MS + ? DELAY_SCAN_UPGRADE_DURATION_MS + : DELAY_SCAN_DOWNGRADE_DURATION_MS; testSleep(max_duration + DELAY_ASYNC_MS); TestUtils.waitForLooperToFinishScheduledTask(mHandler.getLooper()); assertThat(client.settings.getScanMode()).isEqualTo(ScanMode); @@ -887,14 +945,18 @@ public class ScanManagerTest { scanModeMap.put(SCAN_MODE_LOW_LATENCY, SCAN_MODE_BALANCED); scanModeMap.put(SCAN_MODE_AMBIENT_DISCOVERY, SCAN_MODE_AMBIENT_DISCOVERY); // Set scan downgrade duration through Mock - when(mAdapterService.getScanDowngradeDurationMillis()). - thenReturn((long) DELAY_SCAN_DOWNGRADE_DURATION_MS); + when(mAdapterService.getScanDowngradeDurationMillis()) + .thenReturn((long) DELAY_SCAN_DOWNGRADE_DURATION_MS); for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -929,14 +991,18 @@ public class ScanManagerTest { scanModeMap.put(SCAN_MODE_LOW_LATENCY, SCAN_MODE_LOW_LATENCY); scanModeMap.put(SCAN_MODE_AMBIENT_DISCOVERY, SCAN_MODE_SCREEN_OFF_BALANCED); // Set scan downgrade duration through Mock - when(mAdapterService.getScanDowngradeDurationMillis()). - thenReturn((long) DELAY_SCAN_DOWNGRADE_DURATION_MS); + when(mAdapterService.getScanDowngradeDurationMillis()) + .thenReturn((long) DELAY_SCAN_DOWNGRADE_DURATION_MS); for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen mHandler.sendMessage(createScreenOnOffMessage(true)); @@ -980,14 +1046,18 @@ public class ScanManagerTest { scanModeMap.put(SCAN_MODE_LOW_LATENCY, SCAN_MODE_LOW_POWER); scanModeMap.put(SCAN_MODE_AMBIENT_DISCOVERY, SCAN_MODE_LOW_POWER); // Set scan downgrade duration through Mock - when(mAdapterService.getScanDowngradeDurationMillis()). - thenReturn((long) DELAY_SCAN_DOWNGRADE_DURATION_MS); + when(mAdapterService.getScanDowngradeDurationMillis()) + .thenReturn((long) DELAY_SCAN_DOWNGRADE_DURATION_MS); for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); @@ -1029,8 +1099,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -1066,8 +1140,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -1106,8 +1184,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -1153,8 +1235,12 @@ public class ScanManagerTest { for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); int expectedScanMode = scanModeMap.get(ScanMode); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " expectedScanMode: " + String.valueOf(expectedScanMode)); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " expectedScanMode: " + + String.valueOf(expectedScanMode)); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); @@ -1187,10 +1273,12 @@ public class ScanManagerTest { // Set filtered scan flag final boolean isFiltered = false; // Set scan mode array - int[] scanModeArr = {SCAN_MODE_LOW_POWER, - SCAN_MODE_BALANCED, - SCAN_MODE_LOW_LATENCY, - SCAN_MODE_AMBIENT_DISCOVERY}; + int[] scanModeArr = { + SCAN_MODE_LOW_POWER, + SCAN_MODE_BALANCED, + SCAN_MODE_LOW_LATENCY, + SCAN_MODE_AMBIENT_DISCOVERY + }; for (int i = 0; i < scanModeArr.length; i++) { int ScanMode = scanModeArr[i]; @@ -1241,8 +1329,10 @@ public class ScanManagerTest { .cacheCount( eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_ON), anyLong()); - verify(mMetricsLogger, never()).cacheCount( - eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), anyLong()); + verify(mMetricsLogger, never()) + .cacheCount( + eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), + anyLong()); Mockito.clearInvocations(mMetricsLogger); testSleep(50); // Stop scan @@ -1253,8 +1343,10 @@ public class ScanManagerTest { .cacheCount( eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_ON), anyLong()); - verify(mMetricsLogger, never()).cacheCount( - eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), anyLong()); + verify(mMetricsLogger, never()) + .cacheCount( + eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), + anyLong()); Mockito.clearInvocations(mMetricsLogger); } @@ -1317,8 +1409,10 @@ public class ScanManagerTest { .cacheCount( eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_ON), anyLong()); - verify(mMetricsLogger, never()).cacheCount( - eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), anyLong()); + verify(mMetricsLogger, never()) + .cacheCount( + eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), + anyLong()); Mockito.clearInvocations(mMetricsLogger); } @@ -1340,8 +1434,10 @@ public class ScanManagerTest { .cacheCount( eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_ON), anyLong()); - verify(mMetricsLogger, never()).cacheCount( - eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), anyLong()); + verify(mMetricsLogger, never()) + .cacheCount( + eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), + anyLong()); Mockito.clearInvocations(mMetricsLogger); testSleep(50); // Start scan with higher duty cycle @@ -1352,8 +1448,10 @@ public class ScanManagerTest { .cacheCount( eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_ON), anyLong()); - verify(mMetricsLogger, never()).cacheCount( - eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), anyLong()); + verify(mMetricsLogger, never()) + .cacheCount( + eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), + anyLong()); Mockito.clearInvocations(mMetricsLogger); testSleep(50); // Stop scan with lower duty cycle @@ -1368,8 +1466,10 @@ public class ScanManagerTest { .cacheCount( eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_ON), anyLong()); - verify(mMetricsLogger, never()).cacheCount( - eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), anyLong()); + verify(mMetricsLogger, never()) + .cacheCount( + eq(BluetoothProtoEnums.LE_SCAN_RADIO_DURATION_REGULAR_SCREEN_OFF), + anyLong()); Mockito.clearInvocations(mMetricsLogger); } @@ -1391,9 +1491,14 @@ public class ScanManagerTest { Mockito.clearInvocations(mMetricsLogger); for (int i = 0; i < scanModeMap.size(); i++) { int ScanMode = scanModeMap.keyAt(i); - long weightedScanDuration = (long)(scanTestDuration * scanModeMap.get(ScanMode) * 0.01); - Log.d(TAG, "ScanMode: " + String.valueOf(ScanMode) - + " weightedScanDuration: " + String.valueOf(weightedScanDuration)); + long weightedScanDuration = + (long) (scanTestDuration * scanModeMap.get(ScanMode) * 0.01); + Log.d( + TAG, + "ScanMode: " + + String.valueOf(ScanMode) + + " weightedScanDuration: " + + String.valueOf(weightedScanDuration)); // Create scan client ScanClient client = createScanClient(i, isFiltered, ScanMode); @@ -1423,17 +1528,17 @@ public class ScanManagerTest { Mockito.clearInvocations(mMetricsLogger); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); - verify(mMetricsLogger, never()).cacheCount( - eq(BluetoothProtoEnums.SCREEN_OFF_EVENT), anyLong()); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.SCREEN_ON_EVENT), anyLong()); + verify(mMetricsLogger, never()) + .cacheCount(eq(BluetoothProtoEnums.SCREEN_OFF_EVENT), anyLong()); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.SCREEN_ON_EVENT), anyLong()); Mockito.clearInvocations(mMetricsLogger); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); - verify(mMetricsLogger, never()).cacheCount( - eq(BluetoothProtoEnums.SCREEN_ON_EVENT), anyLong()); - verify(mMetricsLogger, times(1)).cacheCount( - eq(BluetoothProtoEnums.SCREEN_OFF_EVENT), anyLong()); + verify(mMetricsLogger, never()) + .cacheCount(eq(BluetoothProtoEnums.SCREEN_ON_EVENT), anyLong()); + verify(mMetricsLogger, times(1)) + .cacheCount(eq(BluetoothProtoEnums.SCREEN_OFF_EVENT), anyLong()); Mockito.clearInvocations(mMetricsLogger); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapAccountItemTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapAccountItemTest.java index 9b2e2ec633d..4993b863a60 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapAccountItemTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapAccountItemTest.java @@ -39,9 +39,16 @@ public class BluetoothMapAccountItemTest { @Test public void create_withAllParameters() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItem.getId()).isEqualTo(TEST_ID); assertThat(accountItem.getAccountId()).isEqualTo(Long.parseLong(TEST_ID)); assertThat(accountItem.getName()).isEqualTo(TEST_NAME); @@ -55,8 +62,14 @@ public class BluetoothMapAccountItemTest { @Test public void create_withoutIdAndUciData() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(/*id=*/null, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + /* id= */ null, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE); assertThat(accountItem.getId()).isNull(); assertThat(accountItem.getAccountId()).isEqualTo(-1); assertThat(accountItem.getName()).isEqualTo(TEST_NAME); @@ -70,17 +83,38 @@ public class BluetoothMapAccountItemTest { @Test public void getUciFull() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); - - BluetoothMapAccountItem accountItemWithoutUciPrefix = BluetoothMapAccountItem.create( - TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, null); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithoutUci = BluetoothMapAccountItem.create(TEST_ID, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, null, null); + BluetoothMapAccountItem accountItemWithoutUciPrefix = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + null); + + BluetoothMapAccountItem accountItemWithoutUci = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + null, + null); assertThat(accountItem.getUciFull()).isEqualTo("uci_prefix:uci"); assertThat(accountItemWithoutUciPrefix.getUciFull()).isNull(); @@ -89,13 +123,25 @@ public class BluetoothMapAccountItemTest { @Test public void compareIfTwoObjectsAreEqual_returnFalse_whenTypesAreDifferent() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithDifferentType = BluetoothMapAccountItem.create( - TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - BluetoothMapUtils.TYPE.MMS); + BluetoothMapAccountItem accountItemWithDifferentType = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + BluetoothMapUtils.TYPE.MMS); assertThat(accountItem.equals(accountItemWithDifferentType)).isFalse(); assertThat(accountItem.compareTo(accountItemWithDifferentType)).isEqualTo(-1); @@ -103,12 +149,25 @@ public class BluetoothMapAccountItemTest { @Test public void compareIfTwoObjectsAreEqual_returnTrue_evenWhenUcisAreDifferent() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithoutUciData = BluetoothMapAccountItem.create(TEST_ID, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE); + BluetoothMapAccountItem accountItemWithoutUciData = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE); assertThat(accountItem.equals(accountItemWithoutUciData)).isTrue(); assertThat(accountItem.compareTo(accountItemWithoutUciData)).isEqualTo(0); @@ -116,17 +175,32 @@ public class BluetoothMapAccountItemTest { @Test public void equals_withSameInstance() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItem.equals(accountItem)).isTrue(); } + @Test public void equals_withNull() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItem).isNotEqualTo(null); } @@ -134,9 +208,16 @@ public class BluetoothMapAccountItemTest { @SuppressWarnings("EqualsIncompatibleType") @Test public void equals_withDifferentClass() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); String accountItemString = "accountItem_string"; assertThat(accountItem.equals(accountItemString)).isFalse(); @@ -144,12 +225,26 @@ public class BluetoothMapAccountItemTest { @Test public void equals_withNullId() { - BluetoothMapAccountItem accountItemWithNullId = BluetoothMapAccountItem.create(/*id=*/null, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE, - TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithNonNullId = BluetoothMapAccountItem.create(TEST_ID, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE, - TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNullId = + BluetoothMapAccountItem.create( + /* id= */ null, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNonNullId = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItemWithNullId).isNotEqualTo(accountItemWithNonNullId); } @@ -157,24 +252,52 @@ public class BluetoothMapAccountItemTest { @Test public void equals_withDifferentId() { String TEST_ID_DIFFERENT = "2222"; - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithDifferentId = BluetoothMapAccountItem.create( - TEST_ID_DIFFERENT, TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, - TEST_DRAWABLE, TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithDifferentId = + BluetoothMapAccountItem.create( + TEST_ID_DIFFERENT, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItem).isNotEqualTo(accountItemWithDifferentId); } @Test public void equals_withNullName() { - BluetoothMapAccountItem accountItemWithNullName = BluetoothMapAccountItem.create( - TEST_ID, /*name=*/null, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithNonNullName = BluetoothMapAccountItem.create(TEST_ID, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE, - TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNullName = + BluetoothMapAccountItem.create( + TEST_ID, + /* name= */ null, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNonNullName = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItemWithNullName).isNotEqualTo(accountItemWithNonNullName); } @@ -182,24 +305,52 @@ public class BluetoothMapAccountItemTest { @Test public void equals_withDifferentName() { String TEST_NAME_DIFFERENT = "test_name_different"; - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithDifferentName = BluetoothMapAccountItem.create( - TEST_ID, TEST_NAME_DIFFERENT, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, - TEST_DRAWABLE, TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithDifferentName = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME_DIFFERENT, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItem).isNotEqualTo(accountItemWithDifferentName); } @Test public void equals_withNullPackageName() { - BluetoothMapAccountItem accountItemWithNullPackageName = BluetoothMapAccountItem.create( - TEST_ID, TEST_NAME, /*package_name=*/null, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithNonNullPackageName = BluetoothMapAccountItem.create( - TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNullPackageName = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + /* package_name= */ null, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNonNullPackageName = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItemWithNullPackageName).isNotEqualTo(accountItemWithNonNullPackageName); } @@ -207,12 +358,25 @@ public class BluetoothMapAccountItemTest { @Test public void equals_withDifferentPackageName() { String TEST_PACKAGE_NAME_DIFFERENT = "test.different.package.name"; - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); BluetoothMapAccountItem accountItemWithDifferentPackageName = - BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, TEST_PACKAGE_NAME_DIFFERENT, - TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE, TEST_UCI, + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME_DIFFERENT, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, TEST_UCI_PREFIX); assertThat(accountItem).isNotEqualTo(accountItemWithDifferentPackageName); @@ -220,12 +384,26 @@ public class BluetoothMapAccountItemTest { @Test public void equals_withNullAuthority() { - BluetoothMapAccountItem accountItemWithNullAuthority = BluetoothMapAccountItem.create( - TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, /*provider_authority=*/null, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithNonNullAuthority = BluetoothMapAccountItem.create( - TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNullAuthority = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + /* provider_authority= */ null, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNonNullAuthority = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItemWithNullAuthority).isNotEqualTo(accountItemWithNonNullAuthority); } @@ -233,12 +411,25 @@ public class BluetoothMapAccountItemTest { @Test public void equals_withDifferentAuthority() { String TEST_PROVIDER_AUTHORITY_DIFFERENT = "test.project.different.provider"; - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); BluetoothMapAccountItem accountItemWithDifferentAuthority = - BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, - TEST_PROVIDER_AUTHORITY_DIFFERENT, TEST_DRAWABLE, TEST_TYPE, TEST_UCI, + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY_DIFFERENT, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, TEST_UCI_PREFIX); assertThat(accountItem).isNotEqualTo(accountItemWithDifferentAuthority); @@ -246,20 +437,34 @@ public class BluetoothMapAccountItemTest { @Test public void equals_withNullType() { - BluetoothMapAccountItem accountItemWithNullType = BluetoothMapAccountItem.create( - TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - /*type=*/null, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapAccountItem accountItemWithNonNullType = BluetoothMapAccountItem.create(TEST_ID, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE, - TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNullType = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + /* type= */ null, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItemWithNonNullType = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); assertThat(accountItemWithNullType).isNotEqualTo(accountItemWithNonNullType); } @Test public void hashCode_withOnlyIdNotNull() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, null, - null, null, null, null); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create(TEST_ID, null, null, null, null, null); int expected = (31 + TEST_ID.hashCode()) * 31 * 31 * 31; assertThat(accountItem.hashCode()).isEqualTo(expected); @@ -267,12 +472,19 @@ public class BluetoothMapAccountItemTest { @Test public void toString_returnsNameAndUriInfo() { - BluetoothMapAccountItem accountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, - TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + BluetoothMapAccountItem accountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); String expected = TEST_NAME + " (" + "content://" + TEST_PROVIDER_AUTHORITY + "/" + TEST_ID + ")"; assertThat(accountItem.toString()).isEqualTo(expected); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapAppParamsTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapAppParamsTest.java index 900835a4622..95fa60a6e8f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapAppParamsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapAppParamsTest.java @@ -149,9 +149,10 @@ public class BluetoothMapAppParamsTest { assertThat(appParamsDecoded.getPresenceStatus()).isEqualTo(TEST_PRESENCE_STATUS); assertThat(appParamsDecoded.getLastActivity()).isEqualTo(TEST_LAST_ACTIVITY); assertThat(appParamsDecoded.getConvoListingSize()).isEqualTo(TEST_CONVO_LISTING_SIZE); - assertThat(appParamsDecoded.getChatStateConvoId()).isEqualTo(new SignedLongLong( - TEST_ID_HIGH, TEST_ID_LOW)); + assertThat(appParamsDecoded.getChatStateConvoId()) + .isEqualTo(new SignedLongLong(TEST_ID_HIGH, TEST_ID_LOW)); } + @Test public void settersAndGetters() throws Exception { ByteBuffer ret = ByteBuffer.allocate(16); @@ -204,22 +205,25 @@ public class BluetoothMapAppParamsTest { assertThat(appParams.getAttachment()).isEqualTo(TEST_ATTACHMENT); assertThat(appParams.getCharset()).isEqualTo(TEST_CHARSET); assertThat(appParams.getChatState()).isEqualTo(TEST_CHAT_STATE); - assertThat(appParams.getChatStateConvoId()).isEqualTo(new SignedLongLong( - TEST_ID_HIGH, TEST_ID_LOW)); + assertThat(appParams.getChatStateConvoId()) + .isEqualTo(new SignedLongLong(TEST_ID_HIGH, TEST_ID_LOW)); assertThat(appParams.getChatStateConvoIdByteArray()).isEqualTo(ret.array()); assertThat(appParams.getChatStateConvoIdString()).isEqualTo(new String(ret.array())); assertThat(appParams.getConvoListingSize()).isEqualTo(TEST_CONVO_LISTING_SIZE); assertThat(appParams.getConvoListingVerCounter()).isEqualTo(ret.array()); assertThat(appParams.getConvoParameterMask()).isEqualTo(TEST_CONVO_PARAMETER_MASK); assertThat(appParams.getDatabaseIdentifier()).isEqualTo(ret.array()); - assertThat(appParams.getFilterConvoId()).isEqualTo( - SignedLongLong.fromString(TEST_FILTER_CONVO_ID)); - assertThat(appParams.getFilterConvoIdString()).isEqualTo(BluetoothMapUtils.getLongAsString( - SignedLongLong.fromString(TEST_FILTER_CONVO_ID).getLeastSignificantBits())); - assertThat(appParams.getFilterMsgHandle()).isEqualTo( - BluetoothMapUtils.getLongFromString(TEST_FILTER_MSG_HANDLE)); - assertThat(appParams.getFilterMsgHandleString()).isEqualTo( - BluetoothMapUtils.getLongAsString(appParams.getFilterMsgHandle())); + assertThat(appParams.getFilterConvoId()) + .isEqualTo(SignedLongLong.fromString(TEST_FILTER_CONVO_ID)); + assertThat(appParams.getFilterConvoIdString()) + .isEqualTo( + BluetoothMapUtils.getLongAsString( + SignedLongLong.fromString(TEST_FILTER_CONVO_ID) + .getLeastSignificantBits())); + assertThat(appParams.getFilterMsgHandle()) + .isEqualTo(BluetoothMapUtils.getLongFromString(TEST_FILTER_MSG_HANDLE)); + assertThat(appParams.getFilterMsgHandleString()) + .isEqualTo(BluetoothMapUtils.getLongAsString(appParams.getFilterMsgHandle())); assertThat(appParams.getFilterOriginator()).isEqualTo(TEST_FILTER_ORIGINATOR); assertThat(appParams.getFilterPresence()).isEqualTo(TEST_FILTER_PRESENCE); assertThat(appParams.getFilterReadStatus()).isEqualTo(TEST_FILTER_READ_STATUS); @@ -254,8 +258,8 @@ public class BluetoothMapAppParamsTest { appParams.setFilterLastActivityBegin(lastActivityBeginString); appParams.setFilterLastActivityEnd(lastActivityEndString); - assertThat(appParams.getFilterLastActivityBegin()).isEqualTo( - TEST_FILTER_LAST_ACTIVITY_BEGIN); + assertThat(appParams.getFilterLastActivityBegin()) + .isEqualTo(TEST_FILTER_LAST_ACTIVITY_BEGIN); assertThat(appParams.getFilterLastActivityEnd()).isEqualTo(TEST_FILTER_LAST_ACTIVITY_END); } @@ -302,59 +306,84 @@ public class BluetoothMapAppParamsTest { int ILLEGAL_PARAMETER_INT = -2; long ILLEGAL_PARAMETER_LONG = -2; - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setAttachment(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, - () -> appParams.setCharset(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setCharset(ILLEGAL_PARAMETER_INT)); + assertThrows( + IllegalArgumentException.class, () -> appParams.setChatState(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setConvoListingSize(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setConvoParameterMask(ILLEGAL_PARAMETER_LONG)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setFilterMessageType(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setFilterPresence(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setFilterPriority(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setFilterReadStatus(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setFilterUidPresent(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setFolderListingSize(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setFractionDeliver(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setFractionRequest(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setMasInstanceId(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setMaxListCount(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setMessageListingSize(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setNewMessage(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setNotificationFilter(ILLEGAL_PARAMETER_LONG)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setNotificationStatus(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setParameterMask(ILLEGAL_PARAMETER_LONG)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setPresenceAvailability(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, - () -> appParams.setRetry(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setRetry(ILLEGAL_PARAMETER_INT)); + assertThrows( + IllegalArgumentException.class, () -> appParams.setStartOffset(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setStatusIndicator(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setStatusValue(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setSubjectLength(ILLEGAL_PARAMETER_INT)); - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> appParams.setTransparent(ILLEGAL_PARAMETER_INT)); } @@ -368,4 +397,4 @@ public class BluetoothMapAppParamsTest { assertThat(appParams.getFilterConvoId()).isNull(); assertThat(appParams.getFilterMsgHandle()).isEqualTo(-1); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java index 2cb6a218e2d..99a83597047 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java @@ -124,24 +124,15 @@ public class BluetoothMapContentObserverTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); - @Mock - private BluetoothMnsObexClient mClient; - @Mock - private BluetoothMapMasInstance mInstance; - @Mock - private TelephonyManager mTelephonyManager; - @Mock - private UserManager mUserService; - @Mock - private Context mContext; - @Mock - private ContentProviderClient mProviderClient; - @Mock - private BluetoothMapAccountItem mItem; - @Mock - private Intent mIntent; - @Spy - private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); + @Mock private BluetoothMnsObexClient mClient; + @Mock private BluetoothMapMasInstance mInstance; + @Mock private TelephonyManager mTelephonyManager; + @Mock private UserManager mUserService; + @Mock private Context mContext; + @Mock private ContentProviderClient mProviderClient; + @Mock private BluetoothMapAccountItem mItem; + @Mock private Intent mIntent; + @Spy private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); private ExceptionTestProvider mProvider; private MockContentResolver mMockContentResolver; @@ -222,8 +213,8 @@ public class BluetoothMapContentObserverTest { message.setType(BluetoothMapUtils.TYPE.MMS); message.setFolder("telecom/msg/outbox"); message.addSender("Zero", "0"); - message.addRecipient("One", new String[]{TEST_NUMBER_ONE}, null); - message.addRecipient("Two", new String[]{TEST_NUMBER_TWO}, null); + message.addRecipient("One", new String[] {TEST_NUMBER_ONE}, null); + message.addRecipient("Two", new String[] {TEST_NUMBER_TWO}, null); BluetoothMapbMessageMime.MimePart body = message.addMimePart(); try { body.mContentType = "text/plain"; @@ -247,8 +238,8 @@ public class BluetoothMapContentObserverTest { } catch (IOException e) { Assert.fail("Threw IOException"); } catch (NullPointerException e) { - //expected that the test case will end in a NPE as part of the sendMultimediaMessage - //pendingSendIntent + // expected that the test case will end in a NPE as part of the sendMultimediaMessage + // pendingSendIntent } // Validate that 3 addresses were inserted into the database with 2 being the recipients @@ -263,8 +254,8 @@ public class BluetoothMapContentObserverTest { mObserver.setNotificationFilter(0); String eventType = BluetoothMapContentObserver.EVENT_TYPE_NEW; - BluetoothMapContentObserver.Event event = mObserver.new Event(eventType, TEST_HANDLE_ONE, - null, null); + BluetoothMapContentObserver.Event event = + mObserver.new Event(eventType, TEST_HANDLE_ONE, null, null); mObserver.sendEvent(event); verify(mClient, never()).sendEvent(any(), anyInt()); @@ -314,8 +305,8 @@ public class BluetoothMapContentObserverTest { when(mClient.isConnected()).thenReturn(true); String eventType = BluetoothMapContentObserver.EVENT_TYPE_NEW; - BluetoothMapContentObserver.Event event = mObserver.new Event(eventType, TEST_HANDLE_ONE, - null, null); + BluetoothMapContentObserver.Event event = + mObserver.new Event(eventType, TEST_HANDLE_ONE, null, null); mObserver.sendEvent(event); @@ -402,11 +393,13 @@ public class BluetoothMapContentObserverTest { BluetoothMapContentObserver.Msg msg = createSimpleMsg(); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListSms(map, true); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); - Assert.assertTrue(mObserver.setMessageStatusRead(TEST_HANDLE_ONE, type, TEST_URI_STR, - TEST_STATUS_VALUE)); + Assert.assertTrue( + mObserver.setMessageStatusRead( + TEST_HANDLE_ONE, type, TEST_URI_STR, TEST_STATUS_VALUE)); Assert.assertEquals(msg.flagRead, TEST_STATUS_VALUE); } @@ -418,11 +411,13 @@ public class BluetoothMapContentObserverTest { BluetoothMapContentObserver.Msg msg = createSimpleMsg(); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMms(map, true); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); - Assert.assertTrue(mObserver.setMessageStatusRead(TEST_HANDLE_ONE, type, TEST_URI_STR, - TEST_STATUS_VALUE)); + Assert.assertTrue( + mObserver.setMessageStatusRead( + TEST_HANDLE_ONE, type, TEST_URI_STR, TEST_STATUS_VALUE)); Assert.assertEquals(msg.flagRead, TEST_STATUS_VALUE); } @@ -437,8 +432,9 @@ public class BluetoothMapContentObserverTest { mObserver.mProviderClient = mProviderClient; when(mProviderClient.update(any(), any(), any(), any())).thenReturn(TEST_PLACEHOLDER_INT); - Assert.assertTrue(mObserver.setMessageStatusRead(TEST_HANDLE_ONE, type, TEST_URI_STR, - TEST_STATUS_VALUE)); + Assert.assertTrue( + mObserver.setMessageStatusRead( + TEST_HANDLE_ONE, type, TEST_URI_STR, TEST_STATUS_VALUE)); Assert.assertEquals(msg.flagRead, TEST_STATUS_VALUE); } @@ -446,18 +442,20 @@ public class BluetoothMapContentObserverTest { @Test public void testDeleteMessageMms_withNonDeletedThreadId() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMms(map, true); Assert.assertEquals(msg.threadId, TEST_THREAD_ID); MatrixCursor cursor = new MatrixCursor(new String[] {Mms.THREAD_ID}); cursor.addRow(new Object[] {TEST_THREAD_ID}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); Assert.assertTrue(mObserver.deleteMessageMms(TEST_HANDLE_ONE)); @@ -467,18 +465,20 @@ public class BluetoothMapContentObserverTest { @Test public void testDeleteMessageMms_withDeletedThreadId() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMms(map, true); Assert.assertNotNull(mObserver.getMsgListMms().get(TEST_HANDLE_ONE)); MatrixCursor cursor = new MatrixCursor(new String[] {Mms.THREAD_ID}); cursor.addRow(new Object[] {BluetoothMapContentObserver.DELETED_THREAD_ID}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverDelete(any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverDelete(any(), any(), any(), any()); Assert.assertTrue(mObserver.deleteMessageMms(TEST_HANDLE_ONE)); @@ -488,18 +488,20 @@ public class BluetoothMapContentObserverTest { @Test public void testDeleteMessageSms_withNonDeletedThreadId() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Sms.MESSAGE_TYPE_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Sms.MESSAGE_TYPE_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListSms(map, true); Assert.assertEquals(msg.threadId, TEST_THREAD_ID); MatrixCursor cursor = new MatrixCursor(new String[] {Mms.THREAD_ID}); cursor.addRow(new Object[] {TEST_THREAD_ID}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); Assert.assertTrue(mObserver.deleteMessageSms(TEST_HANDLE_ONE)); @@ -509,18 +511,20 @@ public class BluetoothMapContentObserverTest { @Test public void testDeleteMessageSms_withDeletedThreadId() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Sms.MESSAGE_TYPE_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Sms.MESSAGE_TYPE_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListSms(map, true); Assert.assertNotNull(mObserver.getMsgListSms().get(TEST_HANDLE_ONE)); MatrixCursor cursor = new MatrixCursor(new String[] {Mms.THREAD_ID}); cursor.addRow(new Object[] {BluetoothMapContentObserver.DELETED_THREAD_ID}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverDelete(any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverDelete(any(), any(), any(), any()); Assert.assertTrue(mObserver.deleteMessageSms(TEST_HANDLE_ONE)); @@ -530,23 +534,32 @@ public class BluetoothMapContentObserverTest { @Test public void testUnDeleteMessageMms_withDeletedThreadId_andMessageBoxInbox() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMms(map, true); Assert.assertEquals(msg.threadId, TEST_THREAD_ID); Assert.assertEquals(msg.type, Mms.MESSAGE_BOX_ALL); - MatrixCursor cursor = new MatrixCursor( - new String[] {Mms.THREAD_ID, Mms._ID, Mms.MESSAGE_BOX, Mms.Addr.ADDRESS}); - cursor.addRow(new Object[] {BluetoothMapContentObserver.DELETED_THREAD_ID, 1L, - Mms.MESSAGE_BOX_INBOX, TEST_ADDRESS}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); - doReturn(TEST_OLD_THREAD_ID).when(mMapMethodProxy).telephonyGetOrCreateThreadId(any(), - any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] {Mms.THREAD_ID, Mms._ID, Mms.MESSAGE_BOX, Mms.Addr.ADDRESS}); + cursor.addRow( + new Object[] { + BluetoothMapContentObserver.DELETED_THREAD_ID, + 1L, + Mms.MESSAGE_BOX_INBOX, + TEST_ADDRESS + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); + doReturn(TEST_OLD_THREAD_ID) + .when(mMapMethodProxy) + .telephonyGetOrCreateThreadId(any(), any()); Assert.assertTrue(mObserver.unDeleteMessageMms(TEST_HANDLE_ONE)); @@ -557,23 +570,32 @@ public class BluetoothMapContentObserverTest { @Test public void testUnDeleteMessageMms_withDeletedThreadId_andMessageBoxSent() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMms(map, true); Assert.assertEquals(msg.threadId, TEST_THREAD_ID); Assert.assertEquals(msg.type, Mms.MESSAGE_BOX_ALL); - MatrixCursor cursor = new MatrixCursor( - new String[] {Mms.THREAD_ID, Mms._ID, Mms.MESSAGE_BOX, Mms.Addr.ADDRESS}); - cursor.addRow(new Object[] {BluetoothMapContentObserver.DELETED_THREAD_ID, 1L, - Mms.MESSAGE_BOX_SENT, TEST_ADDRESS}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); - doReturn(TEST_OLD_THREAD_ID).when(mMapMethodProxy).telephonyGetOrCreateThreadId(any(), - any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] {Mms.THREAD_ID, Mms._ID, Mms.MESSAGE_BOX, Mms.Addr.ADDRESS}); + cursor.addRow( + new Object[] { + BluetoothMapContentObserver.DELETED_THREAD_ID, + 1L, + Mms.MESSAGE_BOX_SENT, + TEST_ADDRESS + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); + doReturn(TEST_OLD_THREAD_ID) + .when(mMapMethodProxy) + .telephonyGetOrCreateThreadId(any(), any()); Assert.assertTrue(mObserver.unDeleteMessageMms(TEST_HANDLE_ONE)); @@ -584,20 +606,25 @@ public class BluetoothMapContentObserverTest { @Test public void testUnDeleteMessageMms_withoutDeletedThreadId() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Mms.MESSAGE_BOX_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMms(map, true); Assert.assertEquals(msg.threadId, TEST_THREAD_ID); Assert.assertEquals(msg.type, Mms.MESSAGE_BOX_ALL); - MatrixCursor cursor = new MatrixCursor( - new String[] {Mms.THREAD_ID, Mms._ID, Mms.MESSAGE_BOX, Mms.Addr.ADDRESS,}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms.THREAD_ID, Mms._ID, Mms.MESSAGE_BOX, Mms.Addr.ADDRESS, + }); cursor.addRow(new Object[] {TEST_THREAD_ID, 1L, Mms.MESSAGE_BOX_SENT, TEST_ADDRESS}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_OLD_THREAD_ID).when(mMapMethodProxy).telephonyGetOrCreateThreadId(any(), - any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_OLD_THREAD_ID) + .when(mMapMethodProxy) + .telephonyGetOrCreateThreadId(any(), any()); Assert.assertTrue(mObserver.unDeleteMessageMms(TEST_HANDLE_ONE)); @@ -609,22 +636,24 @@ public class BluetoothMapContentObserverTest { @Test public void testUnDeleteMessageSms_withDeletedThreadId() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Sms.MESSAGE_TYPE_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Sms.MESSAGE_TYPE_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListSms(map, true); Assert.assertEquals(msg.threadId, TEST_THREAD_ID); Assert.assertEquals(msg.type, Sms.MESSAGE_TYPE_ALL); - MatrixCursor cursor = new MatrixCursor( - new String[] {Sms.THREAD_ID, Sms.ADDRESS}); + MatrixCursor cursor = new MatrixCursor(new String[] {Sms.THREAD_ID, Sms.ADDRESS}); cursor.addRow(new Object[] {BluetoothMapContentObserver.DELETED_THREAD_ID, TEST_ADDRESS}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); - doReturn(TEST_OLD_THREAD_ID).when(mMapMethodProxy).telephonyGetOrCreateThreadId(any(), - any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); + doReturn(TEST_OLD_THREAD_ID) + .when(mMapMethodProxy) + .telephonyGetOrCreateThreadId(any(), any()); Assert.assertTrue(mObserver.unDeleteMessageSms(TEST_HANDLE_ONE)); @@ -635,20 +664,21 @@ public class BluetoothMapContentObserverTest { @Test public void testUnDeleteMessageSms_withoutDeletedThreadId() { Map map = new HashMap<>(); - BluetoothMapContentObserver.Msg msg = createMsgWithTypeAndThreadId(Sms.MESSAGE_TYPE_ALL, - TEST_THREAD_ID); + BluetoothMapContentObserver.Msg msg = + createMsgWithTypeAndThreadId(Sms.MESSAGE_TYPE_ALL, TEST_THREAD_ID); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListSms(map, true); Assert.assertEquals(msg.threadId, TEST_THREAD_ID); Assert.assertEquals(msg.type, Sms.MESSAGE_TYPE_ALL); - MatrixCursor cursor = new MatrixCursor( - new String[] {Sms.THREAD_ID, Sms.ADDRESS}); + MatrixCursor cursor = new MatrixCursor(new String[] {Sms.THREAD_ID, Sms.ADDRESS}); cursor.addRow(new Object[] {TEST_THREAD_ID, TEST_ADDRESS}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_OLD_THREAD_ID).when(mMapMethodProxy).telephonyGetOrCreateThreadId(any(), - any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_OLD_THREAD_ID) + .when(mMapMethodProxy) + .telephonyGetOrCreateThreadId(any(), any()); Assert.assertTrue(mObserver.unDeleteMessageSms(TEST_HANDLE_ONE)); @@ -677,45 +707,53 @@ public class BluetoothMapContentObserverTest { @Test public void setEmailMessageStatusDelete_withStatusValueYes() { - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, - TEST_DELETE_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, TEST_DELETE_FOLDER_ID); mObserver.setFolderStructure(mFolders); Map map = new HashMap<>(); BluetoothMapContentObserver.Msg msg = createSimpleMsg(); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); - - Assert.assertTrue(mObserver.setEmailMessageStatusDelete(mCurrentFolder, TEST_URI_STR, - TEST_HANDLE_ONE, BluetoothMapAppParams.STATUS_VALUE_YES)); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); + + Assert.assertTrue( + mObserver.setEmailMessageStatusDelete( + mCurrentFolder, + TEST_URI_STR, + TEST_HANDLE_ONE, + BluetoothMapAppParams.STATUS_VALUE_YES)); Assert.assertEquals(msg.folderId, TEST_DELETE_FOLDER_ID); } @Test public void setEmailMessageStatusDelete_withStatusValueYes_andUpdateCountZero() { - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, - TEST_DELETE_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, TEST_DELETE_FOLDER_ID); mObserver.setFolderStructure(mFolders); Map map = new HashMap<>(); BluetoothMapContentObserver.Msg msg = createSimpleMsg(); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); - doReturn(0).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(0).when(mMapMethodProxy).contentResolverUpdate(any(), any(), any(), any(), any()); - Assert.assertFalse(mObserver.setEmailMessageStatusDelete(mCurrentFolder, TEST_URI_STR, - TEST_HANDLE_ONE, BluetoothMapAppParams.STATUS_VALUE_YES)); + Assert.assertFalse( + mObserver.setEmailMessageStatusDelete( + mCurrentFolder, + TEST_URI_STR, + TEST_HANDLE_ONE, + BluetoothMapAppParams.STATUS_VALUE_YES)); } @Test public void setEmailMessageStatusDelete_withStatusValueNo() { - setFolderStructureWithTelecomAndMsg(mCurrentFolder, BluetoothMapContract.FOLDER_NAME_INBOX, - TEST_INBOX_FOLDER_ID); - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, - TEST_DELETE_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mCurrentFolder, BluetoothMapContract.FOLDER_NAME_INBOX, TEST_INBOX_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, TEST_DELETE_FOLDER_ID); mObserver.setFolderStructure(mFolders); Map map = new HashMap<>(); @@ -724,21 +762,26 @@ public class BluetoothMapContentObserverTest { msg.folderId = TEST_DELETE_FOLDER_ID; map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); - - Assert.assertTrue(mObserver.setEmailMessageStatusDelete(mCurrentFolder, TEST_URI_STR, - TEST_HANDLE_ONE, BluetoothMapAppParams.STATUS_VALUE_NO)); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); + + Assert.assertTrue( + mObserver.setEmailMessageStatusDelete( + mCurrentFolder, + TEST_URI_STR, + TEST_HANDLE_ONE, + BluetoothMapAppParams.STATUS_VALUE_NO)); Assert.assertEquals(msg.folderId, TEST_INBOX_FOLDER_ID); } @Test public void setEmailMessageStatusDelete_withStatusValueNo_andOldFolderIdMinusOne() { int oldFolderId = -1; - setFolderStructureWithTelecomAndMsg(mCurrentFolder, BluetoothMapContract.FOLDER_NAME_INBOX, - TEST_INBOX_FOLDER_ID); - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, - TEST_DELETE_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mCurrentFolder, BluetoothMapContract.FOLDER_NAME_INBOX, TEST_INBOX_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, TEST_DELETE_FOLDER_ID); mObserver.setFolderStructure(mFolders); Map map = new HashMap<>(); @@ -747,21 +790,28 @@ public class BluetoothMapContentObserverTest { msg.folderId = TEST_DELETE_FOLDER_ID; map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); - - Assert.assertTrue(mObserver.setEmailMessageStatusDelete(mCurrentFolder, TEST_URI_STR, - TEST_HANDLE_ONE, BluetoothMapAppParams.STATUS_VALUE_NO)); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); + + Assert.assertTrue( + mObserver.setEmailMessageStatusDelete( + mCurrentFolder, + TEST_URI_STR, + TEST_HANDLE_ONE, + BluetoothMapAppParams.STATUS_VALUE_NO)); Assert.assertEquals(msg.folderId, TEST_INBOX_FOLDER_ID); } @Test public void setEmailMessageStatusDelete_withStatusValueNo_andInboxFolderNull() { // This sets mCurrentFolder to have a sent folder, but not an inbox folder - setFolderStructureWithTelecomAndMsg(mCurrentFolder, BluetoothMapContract.FOLDER_NAME_SENT, + setFolderStructureWithTelecomAndMsg( + mCurrentFolder, + BluetoothMapContract.FOLDER_NAME_SENT, BluetoothMapContract.FOLDER_ID_SENT); - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, - TEST_DELETE_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, TEST_DELETE_FOLDER_ID); mObserver.setFolderStructure(mFolders); Map map = new HashMap<>(); @@ -770,75 +820,124 @@ public class BluetoothMapContentObserverTest { msg.folderId = TEST_DELETE_FOLDER_ID; map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); - - Assert.assertTrue(mObserver.setEmailMessageStatusDelete(mCurrentFolder, TEST_URI_STR, - TEST_HANDLE_ONE, BluetoothMapAppParams.STATUS_VALUE_NO)); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); + + Assert.assertTrue( + mObserver.setEmailMessageStatusDelete( + mCurrentFolder, + TEST_URI_STR, + TEST_HANDLE_ONE, + BluetoothMapAppParams.STATUS_VALUE_NO)); Assert.assertEquals(msg.folderId, TEST_OLD_FOLDER_ID); } @Test public void setMessageStatusDeleted_withTypeEmail() { - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, - TEST_DELETE_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, TEST_DELETE_FOLDER_ID); mObserver.setFolderStructure(mFolders); Map map = new HashMap<>(); BluetoothMapContentObserver.Msg msg = createSimpleMsg(); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); - Assert.assertTrue(mObserver.setMessageStatusDeleted(TEST_HANDLE_ONE, TYPE.EMAIL, - mCurrentFolder, TEST_URI_STR, BluetoothMapAppParams.STATUS_VALUE_YES)); + Assert.assertTrue( + mObserver.setMessageStatusDeleted( + TEST_HANDLE_ONE, + TYPE.EMAIL, + mCurrentFolder, + TEST_URI_STR, + BluetoothMapAppParams.STATUS_VALUE_YES)); } @Test public void setMessageStatusDeleted_withTypeIm() { - Assert.assertFalse(mObserver.setMessageStatusDeleted(TEST_HANDLE_ONE, TYPE.IM, - mCurrentFolder, TEST_URI_STR, BluetoothMapAppParams.STATUS_VALUE_YES)); + Assert.assertFalse( + mObserver.setMessageStatusDeleted( + TEST_HANDLE_ONE, + TYPE.IM, + mCurrentFolder, + TEST_URI_STR, + BluetoothMapAppParams.STATUS_VALUE_YES)); } @Test public void setMessageStatusDeleted_withTypeGsmOrMms_andStatusValueNo() { - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_OLD_THREAD_ID).when(mMapMethodProxy).telephonyGetOrCreateThreadId(any(), - any()); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_OLD_THREAD_ID) + .when(mMapMethodProxy) + .telephonyGetOrCreateThreadId(any(), any()); // setMessageStatusDeleted with type Gsm or Mms calls either deleteMessage() or // unDeleteMessage(), which returns false when no cursor is set with BluetoothMethodProxy. - Assert.assertFalse(mObserver.setMessageStatusDeleted(TEST_HANDLE_ONE, TYPE.MMS, - mCurrentFolder, TEST_URI_STR, BluetoothMapAppParams.STATUS_VALUE_NO)); - Assert.assertFalse(mObserver.setMessageStatusDeleted(TEST_HANDLE_ONE, TYPE.SMS_GSM, - mCurrentFolder, TEST_URI_STR, BluetoothMapAppParams.STATUS_VALUE_NO)); + Assert.assertFalse( + mObserver.setMessageStatusDeleted( + TEST_HANDLE_ONE, + TYPE.MMS, + mCurrentFolder, + TEST_URI_STR, + BluetoothMapAppParams.STATUS_VALUE_NO)); + Assert.assertFalse( + mObserver.setMessageStatusDeleted( + TEST_HANDLE_ONE, + TYPE.SMS_GSM, + mCurrentFolder, + TEST_URI_STR, + BluetoothMapAppParams.STATUS_VALUE_NO)); } @Test public void setMessageStatusDeleted_withTypeGsmOrMms_andStatusValueYes() { - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); // setMessageStatusDeleted with type Gsm or Mms calls either deleteMessage() or // unDeleteMessage(), which returns false when no cursor is set with BluetoothMethodProxy. - Assert.assertFalse(mObserver.setMessageStatusDeleted(TEST_HANDLE_ONE, TYPE.MMS, - mCurrentFolder, TEST_URI_STR, BluetoothMapAppParams.STATUS_VALUE_YES)); - Assert.assertFalse(mObserver.setMessageStatusDeleted(TEST_HANDLE_ONE, TYPE.SMS_GSM, - mCurrentFolder, TEST_URI_STR, BluetoothMapAppParams.STATUS_VALUE_YES)); + Assert.assertFalse( + mObserver.setMessageStatusDeleted( + TEST_HANDLE_ONE, + TYPE.MMS, + mCurrentFolder, + TEST_URI_STR, + BluetoothMapAppParams.STATUS_VALUE_YES)); + Assert.assertFalse( + mObserver.setMessageStatusDeleted( + TEST_HANDLE_ONE, + TYPE.SMS_GSM, + mCurrentFolder, + TEST_URI_STR, + BluetoothMapAppParams.STATUS_VALUE_YES)); } @Test public void initMsgList_withMsgSms() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, - Sms.READ}); - cursor.addRow(new Object[] {(long) TEST_ID, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, - TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContentObserver.SMS_PROJECTION_SHORT), any(), any(), any()); + MatrixCursor cursor = + new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, Sms.READ}); + cursor.addRow( + new Object[] { + (long) TEST_ID, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContentObserver.SMS_PROJECTION_SHORT), + any(), + any(), + any()); cursor.moveToFirst(); Map map = new HashMap<>(); mObserver.setMsgListMsg(map, true); @@ -854,14 +953,30 @@ public class BluetoothMapContentObserverTest { @Test public void initMsgList_withMsgMms() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.THREAD_ID, Mms.READ}); - cursor.addRow(new Object[] {(long) TEST_ID, TEST_MMS_TYPE_ALL, TEST_THREAD_ID, - TEST_READ_FLAG_ZERO}); - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContentObserver.SMS_PROJECTION_SHORT), any(), any(), any()); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContentObserver.MMS_PROJECTION_SHORT), any(), any(), any()); + MatrixCursor cursor = + new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, Mms.THREAD_ID, Mms.READ}); + cursor.addRow( + new Object[] { + (long) TEST_ID, TEST_MMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO + }); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContentObserver.SMS_PROJECTION_SHORT), + any(), + any(), + any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContentObserver.MMS_PROJECTION_SHORT), + any(), + any(), + any()); cursor.moveToFirst(); Map map = new HashMap<>(); mObserver.setMsgListMsg(map, true); @@ -877,13 +992,30 @@ public class BluetoothMapContentObserverTest { @Test public void initMsgList_withMsg() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] {MessageColumns._ID, - MessageColumns.FOLDER_ID, MessageColumns.FLAG_READ}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + MessageColumns._ID, MessageColumns.FOLDER_ID, MessageColumns.FLAG_READ + }); cursor.addRow(new Object[] {(long) TEST_ID, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE}); - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContentObserver.SMS_PROJECTION_SHORT), any(), any(), any()); - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContentObserver.MMS_PROJECTION_SHORT), any(), any(), any()); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContentObserver.SMS_PROJECTION_SHORT), + any(), + any(), + any()); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContentObserver.MMS_PROJECTION_SHORT), + any(), + any(), + any()); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); cursor.moveToFirst(); Map map = new HashMap<>(); @@ -899,23 +1031,38 @@ public class BluetoothMapContentObserverTest { @Test public void initContactsList() throws Exception { - MatrixCursor cursor = new MatrixCursor( - new String[] {BluetoothMapContract.ConvoContactColumns.CONVO_ID, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.CHAT_STATE, - BluetoothMapContract.ConvoContactColumns.UCI, - BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, - BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, - BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, - BluetoothMapContract.ConvoContactColumns.PRIORITY, - BluetoothMapContract.ConvoContactColumns.LAST_ONLINE}); - cursor.addRow(new Object[] {TEST_CONVO_ID, TEST_NAME, TEST_DISPLAY_NAME, TEST_BT_UID, - TEST_CHAT_STATE, TEST_UCI, TEST_LAST_ACTIVITY, TEST_PRESENCE_STATE, - TEST_STATUS_TEXT, TEST_PRIORITY, TEST_LAST_ONLINE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.ConvoContactColumns.CONVO_ID, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.CHAT_STATE, + BluetoothMapContract.ConvoContactColumns.UCI, + BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, + BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, + BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, + BluetoothMapContract.ConvoContactColumns.PRIORITY, + BluetoothMapContract.ConvoContactColumns.LAST_ONLINE + }); + cursor.addRow( + new Object[] { + TEST_CONVO_ID, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_BT_UID, + TEST_CHAT_STATE, + TEST_UCI, + TEST_LAST_ACTIVITY, + TEST_PRESENCE_STATE, + TEST_STATUS_TEXT, + TEST_PRIORITY, + TEST_LAST_ONLINE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mObserver.mContactUri = mock(Uri.class); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); @@ -933,30 +1080,42 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(contactElement.getChatState(), TEST_CHAT_STATE); Assert.assertEquals(contactElement.getPresenceStatus(), TEST_STATUS_TEXT); Assert.assertEquals(contactElement.getPresenceAvailability(), TEST_PRESENCE_STATE); - Assert.assertEquals(contactElement.getLastActivityString(), format.format( - TEST_LAST_ACTIVITY)); + Assert.assertEquals( + contactElement.getLastActivityString(), format.format(TEST_LAST_ACTIVITY)); Assert.assertEquals(contactElement.getPriority(), TEST_PRIORITY); } @Test public void handleMsgListChangesMsg_withNonExistingMessage_andVersion11() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.DATE, - BluetoothMapContract.MessageColumns.SUBJECT, - BluetoothMapContract.MessageColumns.FROM_LIST, - BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE, - TEST_DATE_MS, TEST_SUBJECT, TEST_ADDRESS, 1}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.DATE, + BluetoothMapContract.MessageColumns.SUBJECT, + BluetoothMapContract.MessageColumns.FROM_LIST, + BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_INBOX_FOLDER_ID, + TEST_READ_FLAG_ONE, + TEST_DATE_MS, + TEST_SUBJECT, + TEST_ADDRESS, + 1 + }); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesMsg() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); msg.localInitiatedSend = true; msg.transparent = true; map.put(TEST_HANDLE_TWO, msg); @@ -968,33 +1127,47 @@ public class BluetoothMapContentObserverTest { mObserver.handleMsgListChangesMsg(TEST_URI); Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).type, - TEST_INBOX_FOLDER_ID); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).type, TEST_INBOX_FOLDER_ID); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMsg_withNonExistingMessage_andVersion12() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.DATE, - BluetoothMapContract.MessageColumns.SUBJECT, - BluetoothMapContract.MessageColumns.FROM_LIST, - BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, - BluetoothMapContract.MessageColumns.THREAD_ID, - BluetoothMapContract.MessageColumns.THREAD_NAME}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE, - TEST_DATE_MS, TEST_SUBJECT, TEST_ADDRESS, 1, 1, "threadName"}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.DATE, + BluetoothMapContract.MessageColumns.SUBJECT, + BluetoothMapContract.MessageColumns.FROM_LIST, + BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, + BluetoothMapContract.MessageColumns.THREAD_ID, + BluetoothMapContract.MessageColumns.THREAD_NAME + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_INBOX_FOLDER_ID, + TEST_READ_FLAG_ONE, + TEST_DATE_MS, + TEST_SUBJECT, + TEST_ADDRESS, + 1, + 1, + "threadName" + }); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesMsg() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); msg.localInitiatedSend = false; msg.transparent = false; map.put(TEST_HANDLE_TWO, msg); @@ -1004,26 +1177,30 @@ public class BluetoothMapContentObserverTest { mObserver.handleMsgListChangesMsg(TEST_URI); Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).type, - TEST_INBOX_FOLDER_ID); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).type, TEST_INBOX_FOLDER_ID); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMsg_withNonExistingMessage_andVersion10() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ + }); cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE}); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesMsg() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); msg.localInitiatedSend = false; msg.transparent = false; map.put(TEST_HANDLE_TWO, msg); @@ -1035,161 +1212,198 @@ public class BluetoothMapContentObserverTest { mObserver.handleMsgListChangesMsg(TEST_URI); Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).type, - TEST_INBOX_FOLDER_ID); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).type, TEST_INBOX_FOLDER_ID); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMsg_withExistingMessage_andNonNullDeletedFolder() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ,}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + }); cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_DELETE_FOLDER_ID, TEST_READ_FLAG_ONE}); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesMsg() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ZERO); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V11; - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, - TEST_DELETE_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_DELETED, TEST_DELETE_FOLDER_ID); mObserver.setFolderStructure(mFolders); mObserver.handleMsgListChangesMsg(TEST_URI); Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).folderId, - TEST_DELETE_FOLDER_ID); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).folderId, TEST_DELETE_FOLDER_ID); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMsg_withExistingMessage_andNonNullSentFolder() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ,}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + }); cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_SENT_FOLDER_ID, TEST_READ_FLAG_ONE}); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesMsg() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ZERO); msg.localInitiatedSend = true; msg.transparent = false; map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V11; - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_SENT, - TEST_SENT_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_SENT, TEST_SENT_FOLDER_ID); mObserver.setFolderStructure(mFolders); mObserver.handleMsgListChangesMsg(TEST_URI); Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).folderId, - TEST_SENT_FOLDER_ID); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).folderId, TEST_SENT_FOLDER_ID); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMsg_withExistingMessage_andNonNullTransparentSentFolder() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ,}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + }); cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_SENT_FOLDER_ID, TEST_READ_FLAG_ONE}); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesMsg() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ZERO); msg.localInitiatedSend = true; msg.transparent = true; map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V11; - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverDelete(any(), any(), - any(), any()); - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_SENT, - TEST_SENT_FOLDER_ID); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverDelete(any(), any(), any(), any()); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_SENT, TEST_SENT_FOLDER_ID); mObserver.setFolderStructure(mFolders); mObserver.mMessageUri = Mms.CONTENT_URI; mObserver.handleMsgListChangesMsg(TEST_URI); Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).folderId, - TEST_SENT_FOLDER_ID); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).folderId, TEST_SENT_FOLDER_ID); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test - public void handleMsgListChangesMsg_withExistingMessage_andUnknownOldFolder() - throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ,}); + public void handleMsgListChangesMsg_withExistingMessage_andUnknownOldFolder() throws Exception { + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + }); cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE}); when(mProviderClient.query(any(), any(), any(), any(), any())).thenReturn(cursor); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesMsg() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_SENT_FOLDER_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_SENT_FOLDER_ID, TEST_READ_FLAG_ZERO); msg.localInitiatedSend = true; msg.transparent = false; map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListMsg(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V11; - setFolderStructureWithTelecomAndMsg(mFolders, BluetoothMapContract.FOLDER_NAME_DRAFT, - TEST_DRAFT_FOLDER_ID); + setFolderStructureWithTelecomAndMsg( + mFolders, BluetoothMapContract.FOLDER_NAME_DRAFT, TEST_DRAFT_FOLDER_ID); mObserver.setFolderStructure(mFolders); mObserver.handleMsgListChangesMsg(TEST_URI); Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).folderId, - TEST_INBOX_FOLDER_ID); - Assert.assertEquals(mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).folderId, TEST_INBOX_FOLDER_ID); + Assert.assertEquals( + mObserver.getMsgListMsg().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMms_withNonExistingMessage_andVersion11() { - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ, Mms.DATE, Mms.SUBJECT, - Mms.PRIORITY, Mms.Addr.ADDRESS}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_MMS_MTYPE, - TEST_THREAD_ID, TEST_READ_FLAG_ONE, TEST_DATE_SEC, TEST_SUBJECT, - PduHeaders.PRIORITY_HIGH, null}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms._ID, + Mms.MESSAGE_BOX, + Mms.MESSAGE_TYPE, + Mms.THREAD_ID, + Mms.READ, + Mms.DATE, + Mms.SUBJECT, + Mms.PRIORITY, + Mms.Addr.ADDRESS + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_MMS_TYPE_ALL, + TEST_MMS_MTYPE, + TEST_THREAD_ID, + TEST_READ_FLAG_ONE, + TEST_DATE_SEC, + TEST_SUBJECT, + PduHeaders.PRIORITY_HIGH, + null + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesMms() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); map.put(TEST_HANDLE_TWO, msg); mObserver.setMsgListMms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V11; @@ -1198,28 +1412,49 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).type, TEST_MMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMms_withNonExistingMessage_andVersion12() { - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ, Mms.DATE, Mms.SUBJECT, - Mms.PRIORITY, Mms.Addr.ADDRESS}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_MMS_MTYPE, - TEST_THREAD_ID, TEST_READ_FLAG_ONE, TEST_DATE_SEC, TEST_SUBJECT, - PduHeaders.PRIORITY_HIGH, null}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms._ID, + Mms.MESSAGE_BOX, + Mms.MESSAGE_TYPE, + Mms.THREAD_ID, + Mms.READ, + Mms.DATE, + Mms.SUBJECT, + Mms.PRIORITY, + Mms.Addr.ADDRESS + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_MMS_TYPE_ALL, + TEST_MMS_MTYPE, + TEST_THREAD_ID, + TEST_READ_FLAG_ONE, + TEST_DATE_SEC, + TEST_SUBJECT, + PduHeaders.PRIORITY_HIGH, + null + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesMms() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); map.put(TEST_HANDLE_TWO, msg); mObserver.setMsgListMms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12; @@ -1228,10 +1463,10 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).type, TEST_MMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test @@ -1242,20 +1477,41 @@ public class BluetoothMapContentObserverTest { cal.add(Calendar.DATE, -1); long timestampSec = TimeUnit.MILLISECONDS.toSeconds(cal.getTimeInMillis()); - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ, Mms.DATE, Mms.SUBJECT, - Mms.PRIORITY, Mms.Addr.ADDRESS}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_MMS_MTYPE, - TEST_THREAD_ID, TEST_READ_FLAG_ONE, timestampSec, TEST_SUBJECT, - PduHeaders.PRIORITY_HIGH, null}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms._ID, + Mms.MESSAGE_BOX, + Mms.MESSAGE_TYPE, + Mms.THREAD_ID, + Mms.READ, + Mms.DATE, + Mms.SUBJECT, + Mms.PRIORITY, + Mms.Addr.ADDRESS + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_MMS_TYPE_ALL, + TEST_MMS_MTYPE, + TEST_THREAD_ID, + TEST_READ_FLAG_ONE, + timestampSec, + TEST_SUBJECT, + PduHeaders.PRIORITY_HIGH, + null + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesMms() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); map.put(TEST_HANDLE_TWO, msg); mObserver.setMsgListMms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12; @@ -1319,18 +1575,29 @@ public class BluetoothMapContentObserverTest { @Test public void handleMsgListChangesMms_withNonExistingMessage_andVersion10() { - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_MMS_MTYPE, - TEST_THREAD_ID, TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms._ID, Mms.MESSAGE_BOX, Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_MMS_TYPE_ALL, + TEST_MMS_MTYPE, + TEST_THREAD_ID, + TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesMms() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_INBOX_FOLDER_ID, TEST_READ_FLAG_ONE); map.put(TEST_HANDLE_TWO, msg); mObserver.setMsgListMms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V10; @@ -1339,26 +1606,37 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).type, TEST_MMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMms_withExistingMessage_withNonEqualType_andLocalSendFalse() { - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_MMS_MTYPE, - TEST_THREAD_ID, TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms._ID, Mms.MESSAGE_BOX, Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_MMS_TYPE_ALL, + TEST_MMS_MTYPE, + TEST_THREAD_ID, + TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesMms() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_MMS_TYPE_INBOX, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_MMS_TYPE_INBOX, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); map.put(TEST_HANDLE_ONE, msg); msg.localInitiatedSend = false; mObserver.setMsgListMms(map, true); @@ -1368,26 +1646,37 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).type, TEST_MMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMms_withExistingMessage_withNonEqualType_andLocalSendTrue() { - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_MMS_MTYPE, - TEST_THREAD_ID, TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms._ID, Mms.MESSAGE_BOX, Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_MMS_TYPE_ALL, + TEST_MMS_MTYPE, + TEST_THREAD_ID, + TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesMms() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_MMS_TYPE_INBOX, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_MMS_TYPE_INBOX, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); map.put(TEST_HANDLE_ONE, msg); msg.localInitiatedSend = true; mObserver.setMsgListMms(map, true); @@ -1397,26 +1686,37 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).type, TEST_MMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMms_withExistingMessage_withDeletedThreadId() { - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_MMS_MTYPE, - BluetoothMapContentObserver.DELETED_THREAD_ID, TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms._ID, Mms.MESSAGE_BOX, Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_MMS_TYPE_ALL, + TEST_MMS_MTYPE, + BluetoothMapContentObserver.DELETED_THREAD_ID, + TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesMms() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_MMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); map.put(TEST_HANDLE_ONE, msg); msg.localInitiatedSend = true; mObserver.setMsgListMms(map, true); @@ -1426,27 +1726,39 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).type, TEST_MMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, BluetoothMapContentObserver.DELETED_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesMms_withExistingMessage_withUndeletedThreadId() { int undeletedThreadId = 0; - MatrixCursor cursor = new MatrixCursor(new String[] {Mms._ID, Mms.MESSAGE_BOX, - Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_MMS_MTYPE, - undeletedThreadId, TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Mms._ID, Mms.MESSAGE_BOX, Mms.MESSAGE_TYPE, Mms.THREAD_ID, Mms.READ + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_MMS_TYPE_ALL, + TEST_MMS_MTYPE, + undeletedThreadId, + TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesMms() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_MMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_MMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); map.put(TEST_HANDLE_ONE, msg); msg.localInitiatedSend = true; mObserver.setMsgListMms(map, true); @@ -1456,26 +1768,47 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).type, TEST_MMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, - undeletedThreadId); - Assert.assertEquals(mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).threadId, undeletedThreadId); + Assert.assertEquals( + mObserver.getMsgListMms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesSms_withNonExistingMessage_andVersion11() { - MatrixCursor cursor = new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, - Sms.READ, Sms.DATE, Sms.BODY, Sms.ADDRESS, ContactsContract.Contacts.DISPLAY_NAME}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_SMS_TYPE_INBOX, TEST_THREAD_ID, - TEST_READ_FLAG_ONE, TEST_DATE_MS, TEST_SUBJECT, TEST_ADDRESS, null}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Sms._ID, + Sms.TYPE, + Sms.THREAD_ID, + Sms.READ, + Sms.DATE, + Sms.BODY, + Sms.ADDRESS, + ContactsContract.Contacts.DISPLAY_NAME + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_SMS_TYPE_INBOX, + TEST_THREAD_ID, + TEST_READ_FLAG_ONE, + TEST_DATE_MS, + TEST_SUBJECT, + TEST_ADDRESS, + null + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesSms() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_SMS_TYPE_ALL, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_SMS_TYPE_ALL, TEST_READ_FLAG_ONE); map.put(TEST_HANDLE_TWO, msg); mObserver.setMsgListSms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V11; @@ -1483,28 +1816,47 @@ public class BluetoothMapContentObserverTest { mObserver.handleMsgListChangesSms(); Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, - TEST_SMS_TYPE_INBOX); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, TEST_SMS_TYPE_INBOX); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesSms_withNonExistingMessage_andVersion12() { - MatrixCursor cursor = new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, - Sms.READ, Sms.DATE, Sms.BODY, Sms.ADDRESS}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, - TEST_READ_FLAG_ONE, TEST_DATE_MS, "", null}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Sms._ID, + Sms.TYPE, + Sms.THREAD_ID, + Sms.READ, + Sms.DATE, + Sms.BODY, + Sms.ADDRESS + }); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_SMS_TYPE_ALL, + TEST_THREAD_ID, + TEST_READ_FLAG_ONE, + TEST_DATE_MS, + "", + null + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesSms() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_SMS_TYPE_INBOX, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_SMS_TYPE_INBOX, TEST_READ_FLAG_ONE); map.put(TEST_HANDLE_TWO, msg); mObserver.setMsgListSms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12; @@ -1512,12 +1864,11 @@ public class BluetoothMapContentObserverTest { mObserver.handleMsgListChangesSms(); Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, - TEST_SMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, TEST_SMS_TYPE_ALL); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test @@ -1595,14 +1946,16 @@ public class BluetoothMapContentObserverTest { "", null }); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesMms() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_SMS_TYPE_INBOX, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_SMS_TYPE_INBOX, TEST_READ_FLAG_ONE); map.put(TEST_HANDLE_TWO, msg); mObserver.setMsgListSms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12; @@ -1614,18 +1967,22 @@ public class BluetoothMapContentObserverTest { @Test public void handleMsgListChangesSms_withNonExistingMessage_andVersion10() { - MatrixCursor cursor = new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, - Sms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, - TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, Sms.READ}); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving a different handle for msg below and cursor above makes handleMsgListChangesSms() // function for a non-existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_TWO, - TEST_SMS_TYPE_INBOX, TEST_READ_FLAG_ONE); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_TWO, TEST_SMS_TYPE_INBOX, TEST_READ_FLAG_ONE); map.put(TEST_HANDLE_TWO, msg); mObserver.setMsgListSms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V10; @@ -1633,28 +1990,31 @@ public class BluetoothMapContentObserverTest { mObserver.handleMsgListChangesSms(); Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, - TEST_SMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, TEST_SMS_TYPE_ALL); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesSms_withExistingMessage_withNonEqualType() { - MatrixCursor cursor = new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, - Sms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, - TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, Sms.READ}); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesSms() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_SMS_TYPE_INBOX, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_SMS_TYPE_INBOX, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListSms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12; @@ -1662,28 +2022,34 @@ public class BluetoothMapContentObserverTest { mObserver.handleMsgListChangesSms(); Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, - TEST_SMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, - TEST_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, TEST_SMS_TYPE_ALL); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, TEST_THREAD_ID); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesSms_withExistingMessage_withDeletedThreadId() { - MatrixCursor cursor = new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, - Sms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, - BluetoothMapContentObserver.DELETED_THREAD_ID, TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, Sms.READ}); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, + TEST_SMS_TYPE_ALL, + BluetoothMapContentObserver.DELETED_THREAD_ID, + TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesSms() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_SMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListSms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12; @@ -1692,27 +2058,32 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, TEST_SMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, BluetoothMapContentObserver.DELETED_THREAD_ID); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test public void handleMsgListChangesSms_withExistingMessage_withUndeletedThreadId() { int undeletedThreadId = 0; - MatrixCursor cursor = new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, - Sms.READ}); - cursor.addRow(new Object[] {TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, undeletedThreadId, - TEST_READ_FLAG_ONE}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = + new MatrixCursor(new String[] {Sms._ID, Sms.TYPE, Sms.THREAD_ID, Sms.READ}); + cursor.addRow( + new Object[] { + TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, undeletedThreadId, TEST_READ_FLAG_ONE + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); Map map = new HashMap<>(); // Giving the same handle for msg below and cursor above makes handleMsgListChangesSms() // function for an existing message - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_HANDLE_ONE, - TEST_SMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg( + TEST_HANDLE_ONE, TEST_SMS_TYPE_ALL, TEST_THREAD_ID, TEST_READ_FLAG_ZERO); map.put(TEST_HANDLE_ONE, msg); mObserver.setMsgListSms(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12; @@ -1721,10 +2092,10 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).id, TEST_HANDLE_ONE); Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).type, TEST_SMS_TYPE_ALL); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, - undeletedThreadId); - Assert.assertEquals(mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, - TEST_READ_FLAG_ONE); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).threadId, undeletedThreadId); + Assert.assertEquals( + mObserver.getMsgListSms().get(TEST_HANDLE_ONE).flagRead, TEST_READ_FLAG_ONE); } @Test @@ -1737,8 +2108,9 @@ public class BluetoothMapContentObserverTest { @Test public void handleMmsSendIntent_withInvalidHandle() { when(mClient.isConnected()).thenReturn(true); - doReturn((long) -1).when(mIntent).getLongExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); + doReturn((long) -1) + .when(mIntent) + .getLongExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); Assert.assertTrue(mObserver.handleMmsSendIntent(mContext, mIntent)); } @@ -1746,12 +2118,17 @@ public class BluetoothMapContentObserverTest { @Test public void handleMmsSendIntent_withActivityResultOk() { when(mClient.isConnected()).thenReturn(true); - doReturn(TEST_HANDLE_ONE).when(mIntent).getLongExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); - doReturn(Activity.RESULT_OK).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_RESULT, Activity.RESULT_CANCELED); - doReturn(0).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(TEST_HANDLE_ONE) + .when(mIntent) + .getLongExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); + doReturn(Activity.RESULT_OK) + .when(mIntent) + .getIntExtra( + BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_RESULT, + Activity.RESULT_CANCELED); + doReturn(0) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); mObserver.mObserverRegistered = true; Assert.assertTrue(mObserver.handleMmsSendIntent(mContext, mIntent)); @@ -1760,13 +2137,18 @@ public class BluetoothMapContentObserverTest { @Test public void handleMmsSendIntent_withActivityResultFirstUser() { when(mClient.isConnected()).thenReturn(true); - doReturn(TEST_HANDLE_ONE).when(mIntent).getLongExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); - doReturn(Activity.RESULT_FIRST_USER).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_RESULT, Activity.RESULT_CANCELED); + doReturn(TEST_HANDLE_ONE) + .when(mIntent) + .getLongExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); + doReturn(Activity.RESULT_FIRST_USER) + .when(mIntent) + .getIntExtra( + BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_RESULT, + Activity.RESULT_CANCELED); mObserver.mObserverRegistered = true; - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverDelete(any(), any(), - any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverDelete(any(), any(), any(), any()); Assert.assertTrue(mObserver.handleMmsSendIntent(mContext, mIntent)); } @@ -1776,13 +2158,18 @@ public class BluetoothMapContentObserverTest { Map mmsMsgList = new HashMap<>(); BluetoothMapContentObserver.Msg msg = createSimpleMsg(); mmsMsgList.put(TEST_HANDLE_ONE, msg); - doReturn(1).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); - doReturn((long) -1).when(mIntent).getLongExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); + doReturn(1) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn((long) -1) + .when(mIntent) + .getLongExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); // This mock sets type to MMS - doReturn(4).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_MSG_TYPE, TYPE.NONE.ordinal()); + doReturn(4) + .when(mIntent) + .getIntExtra( + BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_MSG_TYPE, + TYPE.NONE.ordinal()); mObserver.actionMessageSentDisconnected(mContext, mIntent, 1); @@ -1792,13 +2179,18 @@ public class BluetoothMapContentObserverTest { @Test public void actionMessageSentDisconnected_withTypeEmail() { // This sets to null uriString - doReturn(null).when(mIntent).getStringExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); - doReturn(1).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(null) + .when(mIntent) + .getStringExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); + doReturn(1) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); // This mock sets type to Email - doReturn(1).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_MSG_TYPE, TYPE.NONE.ordinal()); + doReturn(1) + .when(mIntent) + .getIntExtra( + BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_MSG_TYPE, + TYPE.NONE.ordinal()); clearInvocations(mContext); mObserver.actionMessageSentDisconnected(mContext, mIntent, Activity.RESULT_FIRST_USER); @@ -1811,10 +2203,12 @@ public class BluetoothMapContentObserverTest { Map mmsMsgList = new HashMap<>(); BluetoothMapContentObserver.Msg msg = createSimpleMsg(); mmsMsgList.put(TEST_HANDLE_ONE, msg); - doReturn(1).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); - doReturn((long) -1).when(mIntent).getLongExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); + doReturn(1) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn((long) -1) + .when(mIntent) + .getLongExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); mObserver.actionMmsSent(mContext, mIntent, 1, mmsMsgList); @@ -1827,12 +2221,15 @@ public class BluetoothMapContentObserverTest { BluetoothMapContentObserver.Msg msg = createSimpleMsg(); mmsMsgList.put(TEST_HANDLE_ONE, msg); // This mock turns on the transparent flag - doReturn(1).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); - doReturn(TEST_HANDLE_ONE).when(mIntent).getLongExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverDelete(any(), any(), - any(), any()); + doReturn(1) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(TEST_HANDLE_ONE) + .when(mIntent) + .getLongExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverDelete(any(), any(), any(), any()); mObserver.actionMmsSent(mContext, mIntent, 1, mmsMsgList); @@ -1845,16 +2242,20 @@ public class BluetoothMapContentObserverTest { BluetoothMapContentObserver.Msg msg = createSimpleMsg(); mmsMsgList.put(TEST_HANDLE_ONE, msg); // This mock turns off the transparent flag - doReturn(0).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); - doReturn(TEST_HANDLE_ONE).when(mIntent).getLongExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); + doReturn(0) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(TEST_HANDLE_ONE) + .when(mIntent) + .getLongExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); MatrixCursor cursor = new MatrixCursor(new String[] {}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); mObserver.actionMmsSent(mContext, mIntent, Activity.RESULT_OK, mmsMsgList); @@ -1867,10 +2268,12 @@ public class BluetoothMapContentObserverTest { BluetoothMapContentObserver.Msg msg = createSimpleMsg(); mmsMsgList.put(TEST_HANDLE_ONE, msg); // This mock turns off the transparent flag - doReturn(0).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); - doReturn(TEST_HANDLE_ONE).when(mIntent).getLongExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); + doReturn(0) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(TEST_HANDLE_ONE) + .when(mIntent) + .getLongExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_HANDLE, -1); mObserver.actionMmsSent(mContext, mIntent, Activity.RESULT_FIRST_USER, mmsMsgList); @@ -1880,10 +2283,12 @@ public class BluetoothMapContentObserverTest { @Test public void actionSmsSentDisconnected_withNullUriString() { // This sets to null uriString - doReturn(null).when(mIntent).getStringExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); - doReturn(1).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(null) + .when(mIntent) + .getStringExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); + doReturn(1) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); clearInvocations(mContext); mObserver.actionSmsSentDisconnected(mContext, mIntent, Activity.RESULT_FIRST_USER); @@ -1893,13 +2298,16 @@ public class BluetoothMapContentObserverTest { @Test public void actionSmsSentDisconnected_withActivityResultOk_andTransparentOff() { - doReturn(TEST_URI_STR).when(mIntent).getStringExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); + doReturn(TEST_URI_STR) + .when(mIntent) + .getStringExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); // This mock turns off the transparent flag - doReturn(0).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(0) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); clearInvocations(mContext); mObserver.actionSmsSentDisconnected(mContext, mIntent, Activity.RESULT_OK); @@ -1909,13 +2317,16 @@ public class BluetoothMapContentObserverTest { @Test public void actionSmsSentDisconnected_withActivityResultOk_andTransparentOn() { - doReturn(TEST_URI_STR).when(mIntent).getStringExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); + doReturn(TEST_URI_STR) + .when(mIntent) + .getStringExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); // This mock turns on the transparent flag - doReturn(1).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverDelete(any(), any(), - any(), any()); + doReturn(1) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverDelete(any(), any(), any(), any()); clearInvocations(mContext); mObserver.actionSmsSentDisconnected(mContext, mIntent, Activity.RESULT_OK); @@ -1925,13 +2336,16 @@ public class BluetoothMapContentObserverTest { @Test public void actionSmsSentDisconnected_withActivityResultFirstUser_andTransparentOff() { - doReturn(TEST_URI_STR).when(mIntent).getStringExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); + doReturn(TEST_URI_STR) + .when(mIntent) + .getStringExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); // This mock turns off the transparent flag - doReturn(0).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); - doReturn(TEST_PLACEHOLDER_INT).when(mMapMethodProxy).contentResolverUpdate(any(), any(), - any(), any(), any()); + doReturn(0) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(TEST_PLACEHOLDER_INT) + .when(mMapMethodProxy) + .contentResolverUpdate(any(), any(), any(), any(), any()); clearInvocations(mContext); mObserver.actionSmsSentDisconnected(mContext, mIntent, Activity.RESULT_OK); @@ -1941,11 +2355,13 @@ public class BluetoothMapContentObserverTest { @Test public void actionSmsSentDisconnected_withActivityResultFirstUser_andTransparentOn() { - doReturn(TEST_URI_STR).when(mIntent).getStringExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); + doReturn(TEST_URI_STR) + .when(mIntent) + .getStringExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_URI); // This mock turns on the transparent flag - doReturn(1).when(mIntent).getIntExtra( - BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); + doReturn(1) + .when(mIntent) + .getIntExtra(BluetoothMapContentObserver.EXTRA_MESSAGE_SENT_TRANSPARENT, 0); doReturn(null).when(mContext).getContentResolver(); clearInvocations(mContext); @@ -1960,21 +2376,35 @@ public class BluetoothMapContentObserverTest { mObserver.mAuthority = TEST_AUTHORITY; when(uri.getAuthority()).thenReturn(TEST_AUTHORITY); - MatrixCursor cursor = new MatrixCursor( - new String[]{BluetoothMapContract.ConvoContactColumns.CONVO_ID, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.CHAT_STATE, - BluetoothMapContract.ConvoContactColumns.UCI, - BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, - BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, - BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, - BluetoothMapContract.ConvoContactColumns.PRIORITY, - BluetoothMapContract.ConvoContactColumns.LAST_ONLINE}); - cursor.addRow(new Object[] {TEST_CONVO_ID, TEST_NAME, TEST_DISPLAY_NAME, TEST_BT_UID, - TEST_CHAT_STATE, TEST_UCI, TEST_LAST_ACTIVITY, TEST_PRESENCE_STATE, - TEST_STATUS_TEXT, TEST_PRIORITY, TEST_LAST_ONLINE}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.ConvoContactColumns.CONVO_ID, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.CHAT_STATE, + BluetoothMapContract.ConvoContactColumns.UCI, + BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, + BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, + BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, + BluetoothMapContract.ConvoContactColumns.PRIORITY, + BluetoothMapContract.ConvoContactColumns.LAST_ONLINE + }); + cursor.addRow( + new Object[] { + TEST_CONVO_ID, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_BT_UID, + TEST_CHAT_STATE, + TEST_UCI, + TEST_LAST_ACTIVITY, + TEST_PRESENCE_STATE, + TEST_STATUS_TEXT, + TEST_PRIORITY, + TEST_LAST_ONLINE + }); doReturn(cursor).when(mProviderClient).query(any(), any(), any(), any(), any()); Map map = new HashMap<>(); @@ -1993,8 +2423,8 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(contactElement.getChatState(), TEST_CHAT_STATE); Assert.assertEquals(contactElement.getPresenceStatus(), TEST_STATUS_TEXT); Assert.assertEquals(contactElement.getPresenceAvailability(), TEST_PRESENCE_STATE); - Assert.assertEquals(contactElement.getLastActivityString(), format.format( - TEST_LAST_ACTIVITY)); + Assert.assertEquals( + contactElement.getLastActivityString(), format.format(TEST_LAST_ACTIVITY)); Assert.assertEquals(contactElement.getPriority(), TEST_PRIORITY); } @@ -2004,29 +2434,50 @@ public class BluetoothMapContentObserverTest { mObserver.mAuthority = TEST_AUTHORITY; when(uri.getAuthority()).thenReturn(TEST_AUTHORITY); - MatrixCursor cursor = new MatrixCursor( - new String[]{BluetoothMapContract.ConvoContactColumns.CONVO_ID, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.CHAT_STATE, - BluetoothMapContract.ConvoContactColumns.UCI, - BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, - BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, - BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, - BluetoothMapContract.ConvoContactColumns.PRIORITY, - BluetoothMapContract.ConvoContactColumns.LAST_ONLINE}); - cursor.addRow(new Object[] {TEST_CONVO_ID, TEST_NAME, TEST_DISPLAY_NAME, TEST_BT_UID, - TEST_CHAT_STATE, TEST_UCI, TEST_LAST_ACTIVITY, TEST_PRESENCE_STATE, - TEST_STATUS_TEXT, TEST_PRIORITY, TEST_LAST_ONLINE}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.ConvoContactColumns.CONVO_ID, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.CHAT_STATE, + BluetoothMapContract.ConvoContactColumns.UCI, + BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, + BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, + BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, + BluetoothMapContract.ConvoContactColumns.PRIORITY, + BluetoothMapContract.ConvoContactColumns.LAST_ONLINE + }); + cursor.addRow( + new Object[] { + TEST_CONVO_ID, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_BT_UID, + TEST_CHAT_STATE, + TEST_UCI, + TEST_LAST_ACTIVITY, + TEST_PRESENCE_STATE, + TEST_STATUS_TEXT, + TEST_PRIORITY, + TEST_LAST_ONLINE + }); doReturn(cursor).when(mProviderClient).query(any(), any(), any(), any(), any()); Map map = new HashMap<>(); map.put(TEST_UCI_DIFFERENT, null); - BluetoothMapConvoContactElement contact = new BluetoothMapConvoContactElement(TEST_UCI, - TEST_NAME, TEST_DISPLAY_NAME, TEST_STATUS_TEXT_DIFFERENT, - TEST_PRESENCE_STATE_DIFFERENT, TEST_LAST_ACTIVITY, TEST_CHAT_STATE_DIFFERENT, - TEST_PRIORITY, TEST_BT_UID); + BluetoothMapConvoContactElement contact = + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_STATUS_TEXT_DIFFERENT, + TEST_PRESENCE_STATE_DIFFERENT, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE_DIFFERENT, + TEST_PRIORITY, + TEST_BT_UID); map.put(TEST_UCI, contact); mObserver.setContactList(map, true); mObserver.mMapEventReportVersion = BluetoothMapUtils.MAP_EVENT_REPORT_V12; @@ -2043,8 +2494,8 @@ public class BluetoothMapContentObserverTest { Assert.assertEquals(contactElement.getChatState(), TEST_CHAT_STATE); Assert.assertEquals(contactElement.getPresenceStatus(), TEST_STATUS_TEXT); Assert.assertEquals(contactElement.getPresenceAvailability(), TEST_PRESENCE_STATE); - Assert.assertEquals(contactElement.getLastActivityString(), format.format( - TEST_LAST_ACTIVITY)); + Assert.assertEquals( + contactElement.getLastActivityString(), format.format(TEST_LAST_ACTIVITY)); Assert.assertEquals(contactElement.getPriority(), TEST_PRIORITY); } @@ -2068,12 +2519,12 @@ public class BluetoothMapContentObserverTest { return new BluetoothMapContentObserver.Msg(1, type, threadId, 1); } - private void setFolderStructureWithTelecomAndMsg(BluetoothMapFolderElement folderElement, - String folderName, long folderId) { + private void setFolderStructureWithTelecomAndMsg( + BluetoothMapFolderElement folderElement, String folderName, long folderId) { folderElement.addFolder("telecom"); folderElement.getSubFolder("telecom").addFolder("msg"); - BluetoothMapFolderElement subFolder = folderElement.getSubFolder("telecom").getSubFolder( - "msg").addFolder(folderName); + BluetoothMapFolderElement subFolder = + folderElement.getSubFolder("telecom").getSubFolder("msg").addFolder(folderName); subFolder.setFolderId(folderId); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentTest.java index 20237fe8961..c464035f440 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentTest.java @@ -115,20 +115,13 @@ public class BluetoothMapContentTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private BluetoothMapAccountItem mAccountItem; - @Mock - private BluetoothMapMasInstance mMasInstance; - @Mock - private Context mContext; - @Mock - private TelephonyManager mTelephonyManager; - @Mock - private ContentResolver mContentResolver; - @Mock - private BluetoothMapAppParams mParams; - @Spy - private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); + @Mock private BluetoothMapAccountItem mAccountItem; + @Mock private BluetoothMapMasInstance mMasInstance; + @Mock private Context mContext; + @Mock private TelephonyManager mTelephonyManager; + @Mock private ContentResolver mContentResolver; + @Mock private BluetoothMapAppParams mParams; + @Spy private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); private BluetoothMapContent mContent; private FilterInfo mInfo; @@ -154,8 +147,7 @@ public class BluetoothMapContentTest { @Test public void constructor_withNonNullAccountItem() { - BluetoothMapContent content = new BluetoothMapContent(mContext, mAccountItem, - mMasInstance); + BluetoothMapContent content = new BluetoothMapContent(mContext, mAccountItem, mMasInstance); assertThat(content.mBaseUri).isNotNull(); } @@ -176,8 +168,9 @@ public class BluetoothMapContentTest { when(cursor.getString(1)).thenReturn("text/plain"); when(cursor.getColumnIndex("text")).thenReturn(2); when(cursor.getString(2)).thenReturn(TEST_TEXT); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); assertThat(BluetoothMapContent.getTextPartsMms(mContentResolver, id)).isEqualTo(TEST_TEXT); } @@ -189,12 +182,12 @@ public class BluetoothMapContentTest { when(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).thenReturn(1); when(cursor.getCount()).thenReturn(1); when(cursor.getString(1)).thenReturn(TEST_TEXT); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); - assertThat( - BluetoothMapContent.getContactNameFromPhone(phoneName, mContentResolver)).isEqualTo( - TEST_TEXT); + assertThat(BluetoothMapContent.getContactNameFromPhone(phoneName, mContentResolver)) + .isEqualTo(TEST_TEXT); } @Test @@ -205,12 +198,12 @@ public class BluetoothMapContentTest { when(cursor.getString(0)).thenReturn("recipientIdOne recipientIdTwo"); when(cursor.getColumnIndex(Telephony.CanonicalAddressesColumns.ADDRESS)).thenReturn(1); when(cursor.getString(1)).thenReturn("recipientAddress"); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); - assertThat( - BluetoothMapContent.getCanonicalAddressSms(mContentResolver, threadId)).isEqualTo( - "recipientAddress"); + assertThat(BluetoothMapContent.getCanonicalAddressSms(mContentResolver, threadId)) + .isEqualTo("recipientAddress"); } @Test @@ -221,23 +214,24 @@ public class BluetoothMapContentTest { when(cursor.moveToFirst()).thenReturn(true); when(cursor.getColumnIndex(Telephony.Mms.Addr.ADDRESS)).thenReturn(1); when(cursor.getString(1)).thenReturn(TEST_TEXT); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); - assertThat(BluetoothMapContent.getAddressMms(mContentResolver, id, type)).isEqualTo( - TEST_TEXT); + assertThat(BluetoothMapContent.getAddressMms(mContentResolver, id, type)) + .isEqualTo(TEST_TEXT); } @Test public void setAttachment_withTypeMms() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_ATTACHMENT_SIZE); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_ATTACHMENT_SIZE); mInfo.mMsgType = FilterInfo.TYPE_MMS; mInfo.mMmsColTextOnly = 0; mInfo.mMmsColAttachmentSize = 1; - MatrixCursor cursor = new MatrixCursor( - new String[]{"MmsColTextOnly", "MmsColAttachmentSize"}); - cursor.addRow(new Object[]{0, -1}); + MatrixCursor cursor = + new MatrixCursor(new String[] {"MmsColTextOnly", "MmsColAttachmentSize"}); + cursor.addRow(new Object[] {0, -1}); cursor.moveToFirst(); mContent.setAttachment(mMessageListingElement, cursor, mInfo, mParams); @@ -247,14 +241,14 @@ public class BluetoothMapContentTest { @Test public void setAttachment_withTypeEmail() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_ATTACHMENT_SIZE); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_ATTACHMENT_SIZE); mInfo.mMsgType = FilterInfo.TYPE_EMAIL; mInfo.mMessageColAttachment = 0; mInfo.mMessageColAttachmentSize = 1; - MatrixCursor cursor = new MatrixCursor(new String[]{"MessageColAttachment", - "MessageColAttachmentSize"}); - cursor.addRow(new Object[]{1, 0}); + MatrixCursor cursor = + new MatrixCursor(new String[] {"MessageColAttachment", "MessageColAttachmentSize"}); + cursor.addRow(new Object[] {1, 0}); cursor.moveToFirst(); mContent.setAttachment(mMessageListingElement, cursor, mInfo, mParams); @@ -271,10 +265,14 @@ public class BluetoothMapContentTest { mInfo.mMessageColAttachment = 0; mInfo.mMessageColAttachmentSize = 1; mInfo.mMessageColAttachmentMime = 2; - MatrixCursor cursor = new MatrixCursor(new String[]{"MessageColAttachment", - "MessageColAttachmentSize", - "MessageColAttachmentMime"}); - cursor.addRow(new Object[]{1, 0, "test_mime_type"}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + "MessageColAttachment", + "MessageColAttachmentSize", + "MessageColAttachmentMime" + }); + cursor.addRow(new Object[] {1, 0, "test_mime_type"}); cursor.moveToFirst(); mContent.setRemoteFeatureMask(featureMask); @@ -291,8 +289,8 @@ public class BluetoothMapContentTest { mContent.setRemoteFeatureMask(featureMask); assertThat(mContent.getRemoteFeatureMask()).isEqualTo(featureMask); - assertThat(mContent.mMsgListingVersion).isEqualTo( - BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V11); + assertThat(mContent.mMsgListingVersion) + .isEqualTo(BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V11); } @Test @@ -311,14 +309,8 @@ public class BluetoothMapContentTest { StringBuilder expected = new StringBuilder(); expected.append(" AND ").append(Threads.READ).append(" = 0"); expected.append(" AND ").append(Threads.READ).append(" = 1"); - expected.append(" AND ") - .append(Threads.DATE) - .append(" >= ") - .append(lastActivity); - expected.append(" AND ") - .append(Threads.DATE) - .append(" <= ") - .append(lastActivity); + expected.append(" AND ").append(Threads.DATE).append(" >= ").append(lastActivity); + expected.append(" AND ").append(Threads.DATE).append(" <= ").append(lastActivity); expected.append(" AND ") .append(Threads._ID) .append(" = ") @@ -331,8 +323,8 @@ public class BluetoothMapContentTest { when(mParams.getParameterMask()).thenReturn((long) BluetoothMapContent.MASK_DATETIME); mInfo.mMsgType = FilterInfo.TYPE_SMS; mInfo.mSmsColDate = 0; - MatrixCursor cursor = new MatrixCursor(new String[]{"SmsColDate"}); - cursor.addRow(new Object[]{2L}); + MatrixCursor cursor = new MatrixCursor(new String[] {"SmsColDate"}); + cursor.addRow(new Object[] {2L}); cursor.moveToFirst(); mContent.setDateTime(mMessageListingElement, cursor, mInfo, mParams); @@ -345,8 +337,8 @@ public class BluetoothMapContentTest { when(mParams.getParameterMask()).thenReturn((long) BluetoothMapContent.MASK_DATETIME); mInfo.mMsgType = FilterInfo.TYPE_MMS; mInfo.mMmsColDate = 0; - MatrixCursor cursor = new MatrixCursor(new String[]{"MmsColDate"}); - cursor.addRow(new Object[]{2L}); + MatrixCursor cursor = new MatrixCursor(new String[] {"MmsColDate"}); + cursor.addRow(new Object[] {2L}); cursor.moveToFirst(); mContent.setDateTime(mMessageListingElement, cursor, mInfo, mParams); @@ -359,8 +351,8 @@ public class BluetoothMapContentTest { when(mParams.getParameterMask()).thenReturn((long) BluetoothMapContent.MASK_DATETIME); mInfo.mMsgType = FilterInfo.TYPE_IM; mInfo.mMessageColDate = 0; - MatrixCursor cursor = new MatrixCursor(new String[]{"MessageColDate"}); - cursor.addRow(new Object[]{2L}); + MatrixCursor cursor = new MatrixCursor(new String[] {"MessageColDate"}); + cursor.addRow(new Object[] {2L}); cursor.moveToFirst(); mContent.setDateTime(mMessageListingElement, cursor, mInfo, mParams); @@ -370,12 +362,12 @@ public class BluetoothMapContentTest { @Test public void setDeliveryStatus() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_DELIVERY_STATUS); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_DELIVERY_STATUS); mInfo.mMsgType = FilterInfo.TYPE_EMAIL; mInfo.mMessageColDelivery = 0; - MatrixCursor cursor = new MatrixCursor(new String[]{"MessageColDelivery"}); - cursor.addRow(new Object[]{"test_delivery_status"}); + MatrixCursor cursor = new MatrixCursor(new String[] {"MessageColDelivery"}); + cursor.addRow(new Object[] {"test_delivery_status"}); cursor.moveToFirst(); mContent.setDeliveryStatus(mMessageListingElement, cursor, mInfo, mParams); @@ -397,8 +389,8 @@ public class BluetoothMapContentTest { @Test public void smsSelected_withInvalidFilter() { - when(mParams.getFilterMessageType()).thenReturn( - BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(mParams.getFilterMessageType()) + .thenReturn(BluetoothMapAppParams.INVALID_VALUE_PARAMETER); assertThat(mContent.smsSelected(mInfo, mParams)).isTrue(); } @@ -443,8 +435,8 @@ public class BluetoothMapContentTest { @Test public void mmsSelected_withInvalidFilter() { - when(mParams.getFilterMessageType()).thenReturn( - BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(mParams.getFilterMessageType()) + .thenReturn(BluetoothMapAppParams.INVALID_VALUE_PARAMETER); assertThat(mContent.mmsSelected(mParams)).isTrue(); } @@ -469,9 +461,12 @@ public class BluetoothMapContentTest { mInfo.mMessageColCcAddress = 1; mInfo.mMessageColBccAddress = 2; - MatrixCursor cursor = new MatrixCursor( - new String[]{"MessageColToAddress", "MessageColCcAddress", "MessageColBccAddress"}); - cursor.addRow(new Object[]{TEST_TO_ADDRESS, TEST_CC_ADDRESS, TEST_BCC_ADDRESS}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + "MessageColToAddress", "MessageColCcAddress", "MessageColBccAddress" + }); + cursor.addRow(new Object[] {TEST_TO_ADDRESS, TEST_CC_ADDRESS, TEST_BCC_ADDRESS}); cursor.moveToFirst(); StringBuilder expected = new StringBuilder(); @@ -480,8 +475,7 @@ public class BluetoothMapContentTest { expected.append(Rfc822Tokenizer.tokenize(TEST_CC_ADDRESS)[0].getName()); expected.append("; "); expected.append(Rfc822Tokenizer.tokenize(TEST_BCC_ADDRESS)[0].getName()); - assertThat(mContent.getRecipientNameEmail(cursor, mInfo)).isEqualTo( - expected.toString()); + assertThat(mContent.getRecipientNameEmail(cursor, mInfo)).isEqualTo(expected.toString()); } @Test @@ -490,9 +484,12 @@ public class BluetoothMapContentTest { mInfo.mMessageColCcAddress = 1; mInfo.mMessageColBccAddress = 2; - MatrixCursor cursor = new MatrixCursor( - new String[]{"MessageColToAddress", "MessageColCcAddress", "MessageColBccAddress"}); - cursor.addRow(new Object[]{TEST_TO_ADDRESS, TEST_CC_ADDRESS, TEST_BCC_ADDRESS}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + "MessageColToAddress", "MessageColCcAddress", "MessageColBccAddress" + }); + cursor.addRow(new Object[] {TEST_TO_ADDRESS, TEST_CC_ADDRESS, TEST_BCC_ADDRESS}); cursor.moveToFirst(); StringBuilder expected = new StringBuilder(); @@ -501,14 +498,14 @@ public class BluetoothMapContentTest { expected.append(Rfc822Tokenizer.tokenize(TEST_CC_ADDRESS)[0].getAddress()); expected.append("; "); expected.append(Rfc822Tokenizer.tokenize(TEST_BCC_ADDRESS)[0].getAddress()); - assertThat(mContent.getRecipientAddressingEmail(cursor, mInfo)).isEqualTo( - expected.toString()); + assertThat(mContent.getRecipientAddressingEmail(cursor, mInfo)) + .isEqualTo(expected.toString()); } @Test public void setRecipientAddressing_withFilterMsgTypeSms_andSmsMsgTypeInbox() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_RECIPIENT_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_RECIPIENT_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_SMS; mInfo.mPhoneNum = TEST_ADDRESS; mInfo.mSmsColType = 0; @@ -523,15 +520,27 @@ public class BluetoothMapContentTest { @Test public void setRecipientAddressing_withFilterMsgTypeSms_andSmsMsgTypeDraft() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_RECIPIENT_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_RECIPIENT_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_SMS; mInfo.mSmsColType = 2; - MatrixCursor cursor = new MatrixCursor(new String[] {"RecipientIds", - Telephony.CanonicalAddressesColumns.ADDRESS, "SmsColType", - Telephony.Sms.ADDRESS, Telephony.Sms.THREAD_ID}); - cursor.addRow(new Object[] {"recipientIdOne recipientIdTwo", "recipientAddress", - Telephony.Sms.MESSAGE_TYPE_DRAFT, null, "0"}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + "RecipientIds", + Telephony.CanonicalAddressesColumns.ADDRESS, + "SmsColType", + Telephony.Sms.ADDRESS, + Telephony.Sms.THREAD_ID + }); + cursor.addRow( + new Object[] { + "recipientIdOne recipientIdTwo", + "recipientAddress", + Telephony.Sms.MESSAGE_TYPE_DRAFT, + null, + "0" + }); cursor.moveToFirst(); mContent.setRecipientAddressing(mMessageListingElement, cursor, mInfo, mParams); @@ -541,15 +550,16 @@ public class BluetoothMapContentTest { @Test public void setRecipientAddressing_withFilterMsgTypeMms() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_RECIPIENT_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_RECIPIENT_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_MMS; - MatrixCursor cursor = new MatrixCursor( - new String[]{BaseColumns._ID, Telephony.Mms.Addr.ADDRESS}); + MatrixCursor cursor = + new MatrixCursor(new String[] {BaseColumns._ID, Telephony.Mms.Addr.ADDRESS}); cursor.addRow(new Object[] {Telephony.Sms.MESSAGE_TYPE_INBOX, null}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setRecipientAddressing(mMessageListingElement, cursor, mInfo, mParams); @@ -558,15 +568,18 @@ public class BluetoothMapContentTest { @Test public void setRecipientAddressing_withFilterMsgTypeEmail() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_RECIPIENT_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_RECIPIENT_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_EMAIL; mInfo.mMessageColToAddress = 0; mInfo.mMessageColCcAddress = 1; mInfo.mMessageColBccAddress = 2; - MatrixCursor cursor = new MatrixCursor( - new String[]{"MessageColToAddress", "MessageColCcAddress", "MessageColBccAddress"}); - cursor.addRow(new Object[]{TEST_TO_ADDRESS, TEST_CC_ADDRESS, TEST_BCC_ADDRESS}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + "MessageColToAddress", "MessageColCcAddress", "MessageColBccAddress" + }); + cursor.addRow(new Object[] {TEST_TO_ADDRESS, TEST_CC_ADDRESS, TEST_BCC_ADDRESS}); cursor.moveToFirst(); mContent.setRecipientAddressing(mMessageListingElement, cursor, mInfo, mParams); @@ -582,27 +595,28 @@ public class BluetoothMapContentTest { @Test public void setSenderAddressing_withFilterMsgTypeSms_andSmsMsgTypeInbox() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_SENDER_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_SENDER_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_SMS; mInfo.mSmsColType = 0; mInfo.mSmsColAddress = 1; MatrixCursor cursor = new MatrixCursor(new String[] {"SmsColType", "SmsColAddress"}); cursor.addRow(new Object[] {Telephony.Sms.MESSAGE_TYPE_INBOX, TEST_ADDRESS}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setSenderAddressing(mMessageListingElement, cursor, mInfo, mParams); - assertThat(mMessageListingElement.getSenderAddressing()).isEqualTo( - PhoneNumberUtils.extractNetworkPortion(TEST_ADDRESS)); + assertThat(mMessageListingElement.getSenderAddressing()) + .isEqualTo(PhoneNumberUtils.extractNetworkPortion(TEST_ADDRESS)); } @Test public void setSenderAddressing_withFilterMsgTypeSms_andSmsMsgTypeDraft() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_SENDER_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_SENDER_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_SMS; mInfo.mPhoneNum = null; mInfo.mSmsColType = 0; @@ -617,16 +631,17 @@ public class BluetoothMapContentTest { @Test public void setSenderAddressing_withFilterMsgTypeMms() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_SENDER_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_SENDER_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_MMS; mInfo.mMmsColId = 0; - MatrixCursor cursor = new MatrixCursor( - new String[]{"MmsColId", Telephony.Mms.Addr.ADDRESS}); + MatrixCursor cursor = + new MatrixCursor(new String[] {"MmsColId", Telephony.Mms.Addr.ADDRESS}); cursor.addRow(new Object[] {0, ""}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setSenderAddressing(mMessageListingElement, cursor, mInfo, mParams); @@ -635,13 +650,12 @@ public class BluetoothMapContentTest { @Test public void setSenderAddressing_withFilterTypeEmail() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_SENDER_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_SENDER_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_EMAIL; mInfo.mMessageColFromAddress = 0; - MatrixCursor cursor = new MatrixCursor( - new String[]{"MessageColFromAddress"}); - cursor.addRow(new Object[]{TEST_FROM_ADDRESS}); + MatrixCursor cursor = new MatrixCursor(new String[] {"MessageColFromAddress"}); + cursor.addRow(new Object[] {TEST_FROM_ADDRESS}); cursor.moveToFirst(); mContent.setSenderAddressing(mMessageListingElement, cursor, mInfo, mParams); @@ -653,16 +667,20 @@ public class BluetoothMapContentTest { @Test public void setSenderAddressing_withFilterTypeIm() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapContent.MASK_SENDER_ADDRESSING); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapContent.MASK_SENDER_ADDRESSING); mInfo.mMsgType = FilterInfo.TYPE_IM; mInfo.mMessageColFromAddress = 0; - MatrixCursor cursor = new MatrixCursor(new String[] {"MessageColFromAddress", - BluetoothMapContract.ConvoContactColumns.UCI}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + "MessageColFromAddress", BluetoothMapContract.ConvoContactColumns.UCI + }); cursor.addRow(new Object[] {(long) 1, TEST_ADDRESS}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setSenderAddressing(mMessageListingElement, cursor, mInfo, mParams); @@ -674,12 +692,18 @@ public class BluetoothMapContentTest { when(mParams.getParameterMask()).thenReturn((long) BluetoothMapContent.MASK_SENDER_NAME); mInfo.mMsgType = FilterInfo.TYPE_SMS; mInfo.mSmsColAddress = 1; - MatrixCursor cursor = new MatrixCursor(new String[] {Telephony.Sms.TYPE, "SmsColAddress", - ContactsContract.Contacts.DISPLAY_NAME}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + Telephony.Sms.TYPE, + "SmsColAddress", + ContactsContract.Contacts.DISPLAY_NAME + }); cursor.addRow(new Object[] {Telephony.Sms.MESSAGE_TYPE_INBOX, TEST_PHONE, TEST_PHONE_NAME}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setSenderName(mMessageListingElement, cursor, mInfo, mParams); @@ -694,8 +718,9 @@ public class BluetoothMapContentTest { MatrixCursor cursor = new MatrixCursor(new String[] {Telephony.Sms.TYPE}); cursor.addRow(new Object[] {Telephony.Sms.MESSAGE_TYPE_DRAFT}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setSenderName(mMessageListingElement, cursor, mInfo, mParams); @@ -708,12 +733,18 @@ public class BluetoothMapContentTest { mInfo.mMsgType = FilterInfo.TYPE_MMS; mInfo.mMmsColId = 0; mMessageListingElement.setSenderAddressing(TEST_ADDRESS); - MatrixCursor cursor = new MatrixCursor(new String[] {"MmsColId", Telephony.Mms.Addr.ADDRESS, - ContactsContract.Contacts.DISPLAY_NAME}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + "MmsColId", + Telephony.Mms.Addr.ADDRESS, + ContactsContract.Contacts.DISPLAY_NAME + }); cursor.addRow(new Object[] {0, TEST_PHONE, TEST_PHONE_NAME}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setSenderName(mMessageListingElement, cursor, mInfo, mParams); @@ -728,8 +759,9 @@ public class BluetoothMapContentTest { MatrixCursor cursor = new MatrixCursor(new String[] {"MmsColId"}); cursor.addRow(new Object[] {0}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setSenderName(mMessageListingElement, cursor, mInfo, mParams); @@ -757,12 +789,16 @@ public class BluetoothMapContentTest { when(mParams.getParameterMask()).thenReturn((long) BluetoothMapContent.MASK_SENDER_NAME); mInfo.mMsgType = FilterInfo.TYPE_IM; mInfo.mMessageColFromAddress = 0; - MatrixCursor cursor = new MatrixCursor(new String[] {"MessageColFromAddress", - BluetoothMapContract.ConvoContactColumns.NAME}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + "MessageColFromAddress", BluetoothMapContract.ConvoContactColumns.NAME + }); cursor.addRow(new Object[] {(long) 1, TEST_NAME}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContent.setSenderName(mMessageListingElement, cursor, mInfo, mParams); @@ -789,8 +825,8 @@ public class BluetoothMapContentTest { public void setLastActivity_withFilterTypeSms() { mInfo.mMsgType = FilterInfo.TYPE_SMS; mInfo.mConvoColLastActivity = 0; - MatrixCursor cursor = new MatrixCursor(new String[] {"ConvoColLastActivity", - "MmsSmsThreadColDate"}); + MatrixCursor cursor = + new MatrixCursor(new String[] {"ConvoColLastActivity", "MmsSmsThreadColDate"}); cursor.addRow(new Object[] {TEST_DATE_EMAIL, TEST_DATE_SMS}); cursor.moveToFirst(); @@ -803,8 +839,8 @@ public class BluetoothMapContentTest { public void setLastActivity_withFilterTypeEmail() { mInfo.mMsgType = FilterInfo.TYPE_EMAIL; mInfo.mConvoColLastActivity = 0; - MatrixCursor cursor = new MatrixCursor(new String[] {"ConvoColLastActivity", - "MmsSmsThreadColDate"}); + MatrixCursor cursor = + new MatrixCursor(new String[] {"ConvoColLastActivity", "MmsSmsThreadColDate"}); cursor.addRow(new Object[] {TEST_DATE_EMAIL, TEST_DATE_SMS}); cursor.moveToFirst(); @@ -817,19 +853,22 @@ public class BluetoothMapContentTest { public void getEmailMessage_withCharsetNative() { when(mParams.getCharset()).thenReturn(BluetoothMapContent.MAP_MESSAGE_CHARSET_NATIVE); - assertThrows(IllegalArgumentException.class, () -> mContent.getEmailMessage(TEST_ID, - mParams, mCurrentFolder)); + assertThrows( + IllegalArgumentException.class, + () -> mContent.getEmailMessage(TEST_ID, mParams, mCurrentFolder)); } @Test public void getEmailMessage_withEmptyCursor() { when(mParams.getCharset()).thenReturn(BluetoothMapContent.MAP_MESSAGE_CHARSET_UTF8); MatrixCursor cursor = new MatrixCursor(new String[] {}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); - assertThrows(IllegalArgumentException.class, () -> mContent.getEmailMessage(TEST_ID, - mParams, mCurrentFolder)); + assertThrows( + IllegalArgumentException.class, + () -> mContent.getEmailMessage(TEST_ID, mParams, mCurrentFolder)); } @Test @@ -838,41 +877,51 @@ public class BluetoothMapContentTest { when(mParams.getFractionRequest()).thenReturn(BluetoothMapAppParams.FRACTION_REQUEST_FIRST); when(mParams.getAttachment()).thenReturn(0); - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.TO_LIST, - BluetoothMapContract.MessageColumns.FROM_LIST - }); - cursor.addRow(new Object[] {BluetoothMapContract.RECEPTION_STATE_FRACTIONED, "1", - TEST_INBOX_FOLDER_ID, TEST_TO_ADDRESS, TEST_FROM_ADDRESS}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns.RECEPTION_STATE, + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.TO_LIST, + BluetoothMapContract.MessageColumns.FROM_LIST + }); + cursor.addRow( + new Object[] { + BluetoothMapContract.RECEPTION_STATE_FRACTIONED, + "1", + TEST_INBOX_FOLDER_ID, + TEST_TO_ADDRESS, + TEST_FROM_ADDRESS + }); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mCurrentFolder.setFolderId(TEST_INBOX_FOLDER_ID); // This mock sets up FileNotFoundException during email body access - doThrow(FileNotFoundException.class).when( - mMapMethodProxy).contentResolverOpenFileDescriptor(any(), any(), any()); + doThrow(FileNotFoundException.class) + .when(mMapMethodProxy) + .contentResolverOpenFileDescriptor(any(), any(), any()); byte[] encodedMessageEmail = mContent.getEmailMessage(TEST_ID, mParams, mCurrentFolder); InputStream inputStream = new ByteArrayInputStream(encodedMessageEmail); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_UTF8); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_UTF8); assertThat(messageParsed.getType()).isEqualTo(TYPE.EMAIL); - assertThat(messageParsed.getVersionString()).isEqualTo("VERSION:" + - mContent.mMessageVersion); + assertThat(messageParsed.getVersionString()) + .isEqualTo("VERSION:" + mContent.mMessageVersion); assertThat(messageParsed.getFolder()).isEqualTo(mCurrentFolder.getFullPath()); - assertThat(messageParsed.getRecipients().get(0).getName()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getName()); - assertThat(messageParsed.getRecipients().get(0).getFirstEmail()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getAddress()); - assertThat(messageParsed.getOriginators().get(0).getName()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getName()); - assertThat(messageParsed.getOriginators().get(0).getFirstEmail()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getAddress()); + assertThat(messageParsed.getRecipients().get(0).getName()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getName()); + assertThat(messageParsed.getRecipients().get(0).getFirstEmail()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getAddress()); + assertThat(messageParsed.getOriginators().get(0).getName()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getName()); + assertThat(messageParsed.getOriginators().get(0).getFirstEmail()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getAddress()); } @Test @@ -881,41 +930,51 @@ public class BluetoothMapContentTest { when(mParams.getFractionRequest()).thenReturn(BluetoothMapAppParams.FRACTION_REQUEST_FIRST); when(mParams.getAttachment()).thenReturn(0); - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.TO_LIST, - BluetoothMapContract.MessageColumns.FROM_LIST - }); - cursor.addRow(new Object[] {BluetoothMapContract.RECEPTION_STATE_FRACTIONED, null, - TEST_INBOX_FOLDER_ID, TEST_TO_ADDRESS, TEST_FROM_ADDRESS}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns.RECEPTION_STATE, + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.TO_LIST, + BluetoothMapContract.MessageColumns.FROM_LIST + }); + cursor.addRow( + new Object[] { + BluetoothMapContract.RECEPTION_STATE_FRACTIONED, + null, + TEST_INBOX_FOLDER_ID, + TEST_TO_ADDRESS, + TEST_FROM_ADDRESS + }); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mCurrentFolder.setFolderId(TEST_INBOX_FOLDER_ID); // This mock sets up NullPointerException during email body access - doThrow(NullPointerException.class).when( - mMapMethodProxy).contentResolverOpenFileDescriptor(any(), any(), any()); + doThrow(NullPointerException.class) + .when(mMapMethodProxy) + .contentResolverOpenFileDescriptor(any(), any(), any()); byte[] encodedMessageEmail = mContent.getEmailMessage(TEST_ID, mParams, mCurrentFolder); InputStream inputStream = new ByteArrayInputStream(encodedMessageEmail); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_UTF8); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_UTF8); assertThat(messageParsed.getType()).isEqualTo(TYPE.EMAIL); - assertThat(messageParsed.getVersionString()).isEqualTo("VERSION:" + - mContent.mMessageVersion); + assertThat(messageParsed.getVersionString()) + .isEqualTo("VERSION:" + mContent.mMessageVersion); assertThat(messageParsed.getFolder()).isEqualTo(mCurrentFolder.getFullPath()); - assertThat(messageParsed.getRecipients().get(0).getName()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getName()); - assertThat(messageParsed.getRecipients().get(0).getFirstEmail()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getAddress()); - assertThat(messageParsed.getOriginators().get(0).getName()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getName()); - assertThat(messageParsed.getOriginators().get(0).getFirstEmail()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getAddress()); + assertThat(messageParsed.getRecipients().get(0).getName()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getName()); + assertThat(messageParsed.getRecipients().get(0).getFirstEmail()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getAddress()); + assertThat(messageParsed.getOriginators().get(0).getName()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getName()); + assertThat(messageParsed.getOriginators().get(0).getFirstEmail()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getAddress()); } @Test @@ -924,18 +983,27 @@ public class BluetoothMapContentTest { when(mParams.getFractionRequest()).thenReturn(BluetoothMapAppParams.FRACTION_REQUEST_FIRST); when(mParams.getAttachment()).thenReturn(0); - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.TO_LIST, - BluetoothMapContract.MessageColumns.FROM_LIST - }); - cursor.addRow(new Object[] {BluetoothMapContract.RECEPTION_STATE_FRACTIONED, "1", - TEST_INBOX_FOLDER_ID, TEST_TO_ADDRESS, TEST_FROM_ADDRESS}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns.RECEPTION_STATE, + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.TO_LIST, + BluetoothMapContract.MessageColumns.FROM_LIST + }); + cursor.addRow( + new Object[] { + BluetoothMapContract.RECEPTION_STATE_FRACTIONED, + "1", + TEST_INBOX_FOLDER_ID, + TEST_TO_ADDRESS, + TEST_FROM_ADDRESS + }); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mCurrentFolder.setFolderId(TEST_INBOX_FOLDER_ID); FileDescriptor fd = new FileDescriptor(); @@ -945,29 +1013,30 @@ public class BluetoothMapContentTest { byte[] encodedMessageEmail = mContent.getEmailMessage(TEST_ID, mParams, mCurrentFolder); InputStream inputStream = new ByteArrayInputStream(encodedMessageEmail); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_UTF8); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_UTF8); assertThat(messageParsed.getType()).isEqualTo(TYPE.EMAIL); - assertThat(messageParsed.getVersionString()).isEqualTo("VERSION:" + - mContent.mMessageVersion); + assertThat(messageParsed.getVersionString()) + .isEqualTo("VERSION:" + mContent.mMessageVersion); assertThat(messageParsed.getFolder()).isEqualTo(mCurrentFolder.getFullPath()); - assertThat(messageParsed.getRecipients().get(0).getName()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getName()); - assertThat(messageParsed.getRecipients().get(0).getFirstEmail()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getAddress()); - assertThat(messageParsed.getOriginators().get(0).getName()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getName()); - assertThat(messageParsed.getOriginators().get(0).getFirstEmail()).isEqualTo( - Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getAddress()); + assertThat(messageParsed.getRecipients().get(0).getName()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getName()); + assertThat(messageParsed.getRecipients().get(0).getFirstEmail()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_TO_ADDRESS)[0].getAddress()); + assertThat(messageParsed.getOriginators().get(0).getName()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getName()); + assertThat(messageParsed.getOriginators().get(0).getFirstEmail()) + .isEqualTo(Rfc822Tokenizer.tokenize(TEST_FROM_ADDRESS)[0].getAddress()); } @Test public void getIMMessage_withCharsetNative() { when(mParams.getCharset()).thenReturn(BluetoothMapContent.MAP_MESSAGE_CHARSET_NATIVE); - assertThrows(IllegalArgumentException.class, () -> mContent.getIMMessage(TEST_ID, - mParams, mCurrentFolder)); + assertThrows( + IllegalArgumentException.class, + () -> mContent.getIMMessage(TEST_ID, mParams, mCurrentFolder)); } @Test @@ -975,11 +1044,13 @@ public class BluetoothMapContentTest { when(mParams.getCharset()).thenReturn(BluetoothMapContent.MAP_MESSAGE_CHARSET_UTF8); MatrixCursor cursor = new MatrixCursor(new String[] {}); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); - assertThrows(IllegalArgumentException.class, () -> mContent.getIMMessage(TEST_ID, - mParams, mCurrentFolder)); + assertThrows( + IllegalArgumentException.class, + () -> mContent.getIMMessage(TEST_ID, mParams, mCurrentFolder)); } @Test @@ -987,26 +1058,41 @@ public class BluetoothMapContentTest { when(mParams.getCharset()).thenReturn(BluetoothMapContent.MAP_MESSAGE_CHARSET_UTF8); when(mParams.getAttachment()).thenReturn(1); - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.THREAD_ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.SUBJECT, - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.DATE, - BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, - BluetoothMapContract.MessageColumns.BODY, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.UCI, - }); - cursor.addRow(new Object[] {1, 1, TEST_SENT_FOLDER_ID, TEST_SUBJECT, TEST_MESSAGE_ID, - TEST_DATE, 0, "body", TEST_NAME, TEST_FIRST_BT_UID, TEST_FORMATTED_NAME, - TEST_FIRST_BT_UCI_RECIPIENT}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.THREAD_ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.SUBJECT, + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.DATE, + BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, + BluetoothMapContract.MessageColumns.BODY, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.UCI, + }); + cursor.addRow( + new Object[] { + 1, + 1, + TEST_SENT_FOLDER_ID, + TEST_SUBJECT, + TEST_MESSAGE_ID, + TEST_DATE, + 0, + "body", + TEST_NAME, + TEST_FIRST_BT_UID, + TEST_FORMATTED_NAME, + TEST_FIRST_BT_UCI_RECIPIENT + }); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mCurrentFolder.setFolderId(TEST_SENT_FOLDER_ID); when(mAccountItem.getUciFull()).thenReturn(TEST_FIRST_BT_UCI_ORIGINATOR); @@ -1017,14 +1103,14 @@ public class BluetoothMapContentTest { assertThat(messageMimeParsed.mAppParamCharset).isEqualTo(1); assertThat(messageMimeParsed.getType()).isEqualTo(TYPE.IM); - assertThat(messageMimeParsed.getVersionString()).isEqualTo("VERSION:" + - mContent.mMessageVersion); + assertThat(messageMimeParsed.getVersionString()) + .isEqualTo("VERSION:" + mContent.mMessageVersion); assertThat(messageMimeParsed.getFolder()).isEqualTo(mCurrentFolder.getFullPath()); assertThat(messageMimeParsed.getRecipients().size()).isEqualTo(1); assertThat(messageMimeParsed.getOriginators().size()).isEqualTo(1); assertThat(messageMimeParsed.getOriginators().get(0).getName()).isEmpty(); - assertThat(messageMimeParsed.getRecipients().get(0).getName()).isEqualTo( - TEST_FORMATTED_NAME); + assertThat(messageMimeParsed.getRecipients().get(0).getName()) + .isEqualTo(TEST_FORMATTED_NAME); } @Test @@ -1032,26 +1118,41 @@ public class BluetoothMapContentTest { when(mParams.getCharset()).thenReturn(BluetoothMapContent.MAP_MESSAGE_CHARSET_UTF8); when(mParams.getAttachment()).thenReturn(1); - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.THREAD_ID, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.SUBJECT, - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.DATE, - BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, - BluetoothMapContract.MessageColumns.BODY, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.UCI, - }); - cursor.addRow(new Object[] {0, 1, TEST_INBOX_FOLDER_ID, TEST_SUBJECT, TEST_MESSAGE_ID, - TEST_DATE, 0, "body", TEST_NAME, TEST_FIRST_BT_UID, TEST_FORMATTED_NAME, - TEST_FIRST_BT_UCI_ORIGINATOR}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.THREAD_ID, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.SUBJECT, + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.DATE, + BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, + BluetoothMapContract.MessageColumns.BODY, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.UCI, + }); + cursor.addRow( + new Object[] { + 0, + 1, + TEST_INBOX_FOLDER_ID, + TEST_SUBJECT, + TEST_MESSAGE_ID, + TEST_DATE, + 0, + "body", + TEST_NAME, + TEST_FIRST_BT_UID, + TEST_FORMATTED_NAME, + TEST_FIRST_BT_UCI_ORIGINATOR + }); cursor.moveToFirst(); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mCurrentFolder.setFolderId(TEST_INBOX_FOLDER_ID); when(mAccountItem.getUciFull()).thenReturn(TEST_FIRST_BT_UCI_RECIPIENT); @@ -1062,55 +1163,88 @@ public class BluetoothMapContentTest { assertThat(messageMimeParsed.mAppParamCharset).isEqualTo(1); assertThat(messageMimeParsed.getType()).isEqualTo(TYPE.IM); - assertThat(messageMimeParsed.getVersionString()).isEqualTo("VERSION:" + - mContent.mMessageVersion); + assertThat(messageMimeParsed.getVersionString()) + .isEqualTo("VERSION:" + mContent.mMessageVersion); assertThat(messageMimeParsed.getFolder()).isEqualTo(mCurrentFolder.getFullPath()); assertThat(messageMimeParsed.getRecipients().size()).isEqualTo(1); assertThat(messageMimeParsed.getOriginators().size()).isEqualTo(1); - assertThat(messageMimeParsed.getOriginators().get(0).getName()).isEqualTo( - TEST_FORMATTED_NAME); + assertThat(messageMimeParsed.getOriginators().get(0).getName()) + .isEqualTo(TEST_FORMATTED_NAME); assertThat(messageMimeParsed.getRecipients().get(0).getName()).isEmpty(); } @Test public void convoListing_withNullFilterRecipient() { - when(mParams.getConvoParameterMask()).thenReturn( - (long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(mParams.getConvoParameterMask()) + .thenReturn((long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); when(mParams.getFilterMessageType()).thenReturn(TEST_NO_FILTER); when(mParams.getMaxListCount()).thenReturn(2); when(mParams.getStartOffset()).thenReturn(0); // This mock sets filter recipient to null when(mParams.getFilterRecipient()).thenReturn(null); - MatrixCursor smsMmsCursor = new MatrixCursor(new String[] {"MmsSmsThreadColId", - "MmsSmsThreadColDate", "MmsSmsThreadColSnippet", "MmsSmsThreadSnippetCharset", - "MmsSmsThreadColRead", "MmsSmsThreadColRecipientIds"}); - smsMmsCursor.addRow(new Object[] {TEST_ID, TEST_DATE_SMS, "test_col_snippet", - "test_col_snippet_cs", 1, "test_recipient_ids"}); + MatrixCursor smsMmsCursor = + new MatrixCursor( + new String[] { + "MmsSmsThreadColId", + "MmsSmsThreadColDate", + "MmsSmsThreadColSnippet", + "MmsSmsThreadSnippetCharset", + "MmsSmsThreadColRead", + "MmsSmsThreadColRecipientIds" + }); + smsMmsCursor.addRow( + new Object[] { + TEST_ID, + TEST_DATE_SMS, + "test_col_snippet", + "test_col_snippet_cs", + 1, + "test_recipient_ids" + }); smsMmsCursor.moveToFirst(); - doReturn(smsMmsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContent.MMS_SMS_THREAD_PROJECTION), any(), any(), any()); - - MatrixCursor imEmailCursor = new MatrixCursor( - new String[] {BluetoothMapContract.ConversationColumns.THREAD_ID, - BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY, - BluetoothMapContract.ConversationColumns.THREAD_NAME, - BluetoothMapContract.ConversationColumns.READ_STATUS, - BluetoothMapContract.ConversationColumns.VERSION_COUNTER, - BluetoothMapContract.ConversationColumns.SUMMARY, - BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.CHAT_STATE, - BluetoothMapContract.ConvoContactColumns.UCI, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, - BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, - BluetoothMapContract.ConvoContactColumns.PRIORITY}); - imEmailCursor.addRow(new Object[] {TEST_ID, TEST_DATE_EMAIL, TEST_NAME, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0}); - doReturn(imEmailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_CONVERSATION_PROJECTION), any(), any(), any()); + doReturn(smsMmsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContent.MMS_SMS_THREAD_PROJECTION), + any(), + any(), + any()); + + MatrixCursor imEmailCursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.ConversationColumns.THREAD_ID, + BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY, + BluetoothMapContract.ConversationColumns.THREAD_NAME, + BluetoothMapContract.ConversationColumns.READ_STATUS, + BluetoothMapContract.ConversationColumns.VERSION_COUNTER, + BluetoothMapContract.ConversationColumns.SUMMARY, + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.CHAT_STATE, + BluetoothMapContract.ConvoContactColumns.UCI, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, + BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, + BluetoothMapContract.ConvoContactColumns.PRIORITY + }); + imEmailCursor.addRow( + new Object[] { + TEST_ID, TEST_DATE_EMAIL, TEST_NAME, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }); + doReturn(imEmailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_CONVERSATION_PROJECTION), + any(), + any(), + any()); BluetoothMapConvoListing listing = mContent.convoListing(mParams, false); @@ -1129,55 +1263,92 @@ public class BluetoothMapContentTest { @Test public void convoListing_withNonNullFilterRecipient() { - when(mParams.getConvoParameterMask()).thenReturn( - (long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(mParams.getConvoParameterMask()) + .thenReturn((long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); when(mParams.getFilterMessageType()).thenReturn(BluetoothMapAppParams.FILTER_NO_EMAIL); when(mParams.getMaxListCount()).thenReturn(2); when(mParams.getStartOffset()).thenReturn(0); // This mock sets filter recipient to non null when(mParams.getFilterRecipient()).thenReturn(TEST_CONTACT_NAME_FILTER); - MatrixCursor smsMmsCursor = new MatrixCursor(new String[] {"MmsSmsThreadColId", - "MmsSmsThreadColDate", "MmsSmsThreadColSnippet", "MmsSmsThreadSnippetCharset", - "MmsSmsThreadColRead", "MmsSmsThreadColRecipientIds"}); - smsMmsCursor.addRow(new Object[] {TEST_ID, TEST_DATE_SMS, "test_col_snippet", - "test_col_snippet_cs", 1, String.valueOf(TEST_ID)}); + MatrixCursor smsMmsCursor = + new MatrixCursor( + new String[] { + "MmsSmsThreadColId", + "MmsSmsThreadColDate", + "MmsSmsThreadColSnippet", + "MmsSmsThreadSnippetCharset", + "MmsSmsThreadColRead", + "MmsSmsThreadColRecipientIds" + }); + smsMmsCursor.addRow( + new Object[] { + TEST_ID, + TEST_DATE_SMS, + "test_col_snippet", + "test_col_snippet_cs", + 1, + String.valueOf(TEST_ID) + }); smsMmsCursor.moveToFirst(); - doReturn(smsMmsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContent.MMS_SMS_THREAD_PROJECTION), any(), any(), any()); - - MatrixCursor addressCursor = new MatrixCursor(new String[] {"COL_ADDR_ID", - "COL_ADDR_ADDR"}); - addressCursor.addRow(new Object[]{TEST_ID, TEST_ADDRESS}); - doReturn(addressCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(SmsMmsContacts.ADDRESS_PROJECTION), any(), any(), any()); - - MatrixCursor contactCursor = new MatrixCursor(new String[] {"COL_CONTACT_ID", - "COL_CONTACT_NAME"}); - contactCursor.addRow(new Object[]{TEST_ID, TEST_NAME}); - doReturn(contactCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(SmsMmsContacts.CONTACT_PROJECTION), any(), any(), any()); - - MatrixCursor imEmailCursor = new MatrixCursor( - new String[] {BluetoothMapContract.ConversationColumns.THREAD_ID, - BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY, - BluetoothMapContract.ConversationColumns.THREAD_NAME, - BluetoothMapContract.ConversationColumns.READ_STATUS, - BluetoothMapContract.ConversationColumns.VERSION_COUNTER, - BluetoothMapContract.ConversationColumns.SUMMARY, - BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.CHAT_STATE, - BluetoothMapContract.ConvoContactColumns.UCI, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, - BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, - BluetoothMapContract.ConvoContactColumns.PRIORITY}); - imEmailCursor.addRow(new Object[] {TEST_ID, TEST_DATE_EMAIL, TEST_NAME, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0}); - doReturn(imEmailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_CONVERSATION_PROJECTION), any(), any(), any()); + doReturn(smsMmsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContent.MMS_SMS_THREAD_PROJECTION), + any(), + any(), + any()); + + MatrixCursor addressCursor = + new MatrixCursor(new String[] {"COL_ADDR_ID", "COL_ADDR_ADDR"}); + addressCursor.addRow(new Object[] {TEST_ID, TEST_ADDRESS}); + doReturn(addressCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), any(), eq(SmsMmsContacts.ADDRESS_PROJECTION), any(), any(), any()); + + MatrixCursor contactCursor = + new MatrixCursor(new String[] {"COL_CONTACT_ID", "COL_CONTACT_NAME"}); + contactCursor.addRow(new Object[] {TEST_ID, TEST_NAME}); + doReturn(contactCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), any(), eq(SmsMmsContacts.CONTACT_PROJECTION), any(), any(), any()); + + MatrixCursor imEmailCursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.ConversationColumns.THREAD_ID, + BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY, + BluetoothMapContract.ConversationColumns.THREAD_NAME, + BluetoothMapContract.ConversationColumns.READ_STATUS, + BluetoothMapContract.ConversationColumns.VERSION_COUNTER, + BluetoothMapContract.ConversationColumns.SUMMARY, + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.CHAT_STATE, + BluetoothMapContract.ConvoContactColumns.UCI, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, + BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, + BluetoothMapContract.ConvoContactColumns.PRIORITY + }); + imEmailCursor.addRow( + new Object[] { + TEST_ID, TEST_DATE_EMAIL, TEST_NAME, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }); + doReturn(imEmailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_CONVERSATION_PROJECTION), + any(), + any(), + any()); BluetoothMapConvoListing listing = mContent.convoListing(mParams, false); @@ -1196,8 +1367,8 @@ public class BluetoothMapContentTest { @Test public void msgListing_withSmsCursorOnly() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); int noMms = BluetoothMapAppParams.FILTER_NO_MMS; when(mParams.getFilterMessageType()).thenReturn(noMms); when(mParams.getMaxListCount()).thenReturn(1); @@ -1207,16 +1378,46 @@ public class BluetoothMapContentTest { mCurrentFolder.setFolderId(TEST_ID); mContent.mMsgListingVersion = BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V11; - MatrixCursor smsCursor = new MatrixCursor(new String[] {BaseColumns._ID, Telephony.Sms.TYPE, - Telephony.Sms.READ, Telephony.Sms.BODY, Telephony.Sms.ADDRESS, Telephony.Sms.DATE, - Telephony.Sms.THREAD_ID, ContactsContract.Contacts.DISPLAY_NAME}); - smsCursor.addRow(new Object[] {TEST_ID, TEST_SENT_NO, TEST_READ_TRUE, TEST_SUBJECT, - TEST_ADDRESS, TEST_DATE_SMS, TEST_THREAD_ID, TEST_PHONE_NAME}); - doReturn(smsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContent.SMS_PROJECTION), any(), any(), any()); - doReturn(smsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(new String[] {ContactsContract.Contacts._ID, - ContactsContract.Contacts.DISPLAY_NAME}), any(), any(), any()); + MatrixCursor smsCursor = + new MatrixCursor( + new String[] { + BaseColumns._ID, + Telephony.Sms.TYPE, + Telephony.Sms.READ, + Telephony.Sms.BODY, + Telephony.Sms.ADDRESS, + Telephony.Sms.DATE, + Telephony.Sms.THREAD_ID, + ContactsContract.Contacts.DISPLAY_NAME + }); + smsCursor.addRow( + new Object[] { + TEST_ID, + TEST_SENT_NO, + TEST_READ_TRUE, + TEST_SUBJECT, + TEST_ADDRESS, + TEST_DATE_SMS, + TEST_THREAD_ID, + TEST_PHONE_NAME + }); + doReturn(smsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), any(), eq(BluetoothMapContent.SMS_PROJECTION), any(), any(), any()); + doReturn(smsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq( + new String[] { + ContactsContract.Contacts._ID, + ContactsContract.Contacts.DISPLAY_NAME + }), + any(), + any(), + any()); BluetoothMapMessageListing listing = mContent.msgListing(mCurrentFolder, mParams); assertThat(listing.getCount()).isEqualTo(1); @@ -1226,8 +1427,8 @@ public class BluetoothMapContentTest { assertThat(smsElement.getDateTime()).isEqualTo(TEST_DATE_SMS); assertThat(smsElement.getType()).isEqualTo(TYPE.SMS_GSM); assertThat(smsElement.getReadBool()).isTrue(); - assertThat(smsElement.getSenderAddressing()).isEqualTo( - PhoneNumberUtils.extractNetworkPortion(TEST_ADDRESS)); + assertThat(smsElement.getSenderAddressing()) + .isEqualTo(PhoneNumberUtils.extractNetworkPortion(TEST_ADDRESS)); assertThat(smsElement.getSenderName()).isEqualTo(TEST_PHONE_NAME); assertThat(smsElement.getSize()).isEqualTo(TEST_SUBJECT.length()); assertThat(smsElement.getPriority()).isEqualTo(TEST_NO); @@ -1240,10 +1441,11 @@ public class BluetoothMapContentTest { @Test public void msgListing_withMmsCursorOnly() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); int onlyMms = - BluetoothMapAppParams.FILTER_NO_EMAIL | BluetoothMapAppParams.FILTER_NO_SMS_CDMA + BluetoothMapAppParams.FILTER_NO_EMAIL + | BluetoothMapAppParams.FILTER_NO_SMS_CDMA | BluetoothMapAppParams.FILTER_NO_SMS_GSM | BluetoothMapAppParams.FILTER_NO_IM; when(mParams.getFilterMessageType()).thenReturn(onlyMms); @@ -1254,21 +1456,61 @@ public class BluetoothMapContentTest { mCurrentFolder.setFolderId(TEST_ID); mContent.mMsgListingVersion = BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V11; - MatrixCursor mmsCursor = new MatrixCursor(new String[] {BaseColumns._ID, - Telephony.Mms.MESSAGE_BOX, Telephony.Mms.READ, Telephony.Mms.MESSAGE_SIZE, - Telephony.Mms.TEXT_ONLY, Telephony.Mms.DATE, Telephony.Mms.SUBJECT, - Telephony.Mms.THREAD_ID, Telephony.Mms.Addr.ADDRESS, - ContactsContract.Contacts.DISPLAY_NAME, Telephony.Mms.PRIORITY}); - mmsCursor.addRow(new Object[] {TEST_ID, TEST_SENT_NO, TEST_READ_FALSE, TEST_SIZE, - TEST_TEXT_ONLY, TEST_DATE_MMS, TEST_SUBJECT, TEST_THREAD_ID, TEST_PHONE, - TEST_PHONE_NAME, PduHeaders.PRIORITY_HIGH}); - doReturn(mmsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContent.MMS_PROJECTION), any(), any(), any()); - doReturn(mmsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(new String[] {Telephony.Mms.Addr.ADDRESS}), any(), any(), any()); - doReturn(mmsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(new String[] {ContactsContract.Contacts._ID, - ContactsContract.Contacts.DISPLAY_NAME}), any(), any(), any()); + MatrixCursor mmsCursor = + new MatrixCursor( + new String[] { + BaseColumns._ID, + Telephony.Mms.MESSAGE_BOX, + Telephony.Mms.READ, + Telephony.Mms.MESSAGE_SIZE, + Telephony.Mms.TEXT_ONLY, + Telephony.Mms.DATE, + Telephony.Mms.SUBJECT, + Telephony.Mms.THREAD_ID, + Telephony.Mms.Addr.ADDRESS, + ContactsContract.Contacts.DISPLAY_NAME, + Telephony.Mms.PRIORITY + }); + mmsCursor.addRow( + new Object[] { + TEST_ID, + TEST_SENT_NO, + TEST_READ_FALSE, + TEST_SIZE, + TEST_TEXT_ONLY, + TEST_DATE_MMS, + TEST_SUBJECT, + TEST_THREAD_ID, + TEST_PHONE, + TEST_PHONE_NAME, + PduHeaders.PRIORITY_HIGH + }); + doReturn(mmsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), any(), eq(BluetoothMapContent.MMS_PROJECTION), any(), any(), any()); + doReturn(mmsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(new String[] {Telephony.Mms.Addr.ADDRESS}), + any(), + any(), + any()); + doReturn(mmsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq( + new String[] { + ContactsContract.Contacts._ID, + ContactsContract.Contacts.DISPLAY_NAME + }), + any(), + any(), + any()); BluetoothMapMessageListing listing = mContent.msgListing(mCurrentFolder, mParams); assertThat(listing.getCount()).isEqualTo(1); @@ -1291,10 +1533,11 @@ public class BluetoothMapContentTest { @Test public void msgListing_withEmailCursorOnly() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); int onlyEmail = - BluetoothMapAppParams.FILTER_NO_MMS | BluetoothMapAppParams.FILTER_NO_SMS_CDMA + BluetoothMapAppParams.FILTER_NO_MMS + | BluetoothMapAppParams.FILTER_NO_SMS_CDMA | BluetoothMapAppParams.FILTER_NO_SMS_GSM | BluetoothMapAppParams.FILTER_NO_IM; when(mParams.getFilterMessageType()).thenReturn(onlyEmail); @@ -1305,31 +1548,58 @@ public class BluetoothMapContentTest { mCurrentFolder.setFolderId(TEST_ID); mContent.mMsgListingVersion = BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V11; - MatrixCursor emailCursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.DATE, - BluetoothMapContract.MessageColumns.SUBJECT, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.MESSAGE_SIZE, - BluetoothMapContract.MessageColumns.FROM_LIST, - BluetoothMapContract.MessageColumns.TO_LIST, - BluetoothMapContract.MessageColumns.FLAG_ATTACHMENT, - BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, - BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, - BluetoothMapContract.MessageColumns.FLAG_PROTECTED, - BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.DEVILERY_STATE, - BluetoothMapContract.MessageColumns.THREAD_ID, - BluetoothMapContract.MessageColumns.CC_LIST, - BluetoothMapContract.MessageColumns.BCC_LIST, - BluetoothMapContract.MessageColumns.REPLY_TO_LIST}); - emailCursor.addRow(new Object[] {TEST_ID, TEST_DATE_EMAIL, TEST_SUBJECT, TEST_SENT_YES, - TEST_READ_TRUE, TEST_SIZE, TEST_FROM_ADDRESS, TEST_TO_ADDRESS, TEST_ATTACHMENT_TRUE, - 0, TEST_PRIORITY_HIGH, TEST_PROTECTED, 0, TEST_DELIVERY_STATE, - TEST_THREAD_ID, TEST_CC_ADDRESS, TEST_BCC_ADDRESS, TEST_TO_ADDRESS}); - doReturn(emailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_MESSAGE_PROJECTION), any(), any(), any()); + MatrixCursor emailCursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.DATE, + BluetoothMapContract.MessageColumns.SUBJECT, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.MESSAGE_SIZE, + BluetoothMapContract.MessageColumns.FROM_LIST, + BluetoothMapContract.MessageColumns.TO_LIST, + BluetoothMapContract.MessageColumns.FLAG_ATTACHMENT, + BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, + BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, + BluetoothMapContract.MessageColumns.FLAG_PROTECTED, + BluetoothMapContract.MessageColumns.RECEPTION_STATE, + BluetoothMapContract.MessageColumns.DEVILERY_STATE, + BluetoothMapContract.MessageColumns.THREAD_ID, + BluetoothMapContract.MessageColumns.CC_LIST, + BluetoothMapContract.MessageColumns.BCC_LIST, + BluetoothMapContract.MessageColumns.REPLY_TO_LIST + }); + emailCursor.addRow( + new Object[] { + TEST_ID, + TEST_DATE_EMAIL, + TEST_SUBJECT, + TEST_SENT_YES, + TEST_READ_TRUE, + TEST_SIZE, + TEST_FROM_ADDRESS, + TEST_TO_ADDRESS, + TEST_ATTACHMENT_TRUE, + 0, + TEST_PRIORITY_HIGH, + TEST_PROTECTED, + 0, + TEST_DELIVERY_STATE, + TEST_THREAD_ID, + TEST_CC_ADDRESS, + TEST_BCC_ADDRESS, + TEST_TO_ADDRESS + }); + doReturn(emailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_MESSAGE_PROJECTION), + any(), + any(), + any()); BluetoothMapMessageListing listing = mContent.msgListing(mCurrentFolder, mParams); assertThat(listing.getCount()).isEqualTo(1); @@ -1356,10 +1626,13 @@ public class BluetoothMapContentTest { @Test public void msgListing_withImCursorOnly() { - when(mParams.getParameterMask()).thenReturn( - (long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); - int onlyIm = BluetoothMapAppParams.FILTER_NO_MMS | BluetoothMapAppParams.FILTER_NO_SMS_CDMA - | BluetoothMapAppParams.FILTER_NO_SMS_GSM | BluetoothMapAppParams.FILTER_NO_EMAIL; + when(mParams.getParameterMask()) + .thenReturn((long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + int onlyIm = + BluetoothMapAppParams.FILTER_NO_MMS + | BluetoothMapAppParams.FILTER_NO_SMS_CDMA + | BluetoothMapAppParams.FILTER_NO_SMS_GSM + | BluetoothMapAppParams.FILTER_NO_EMAIL; when(mParams.getFilterMessageType()).thenReturn(onlyIm); when(mParams.getMaxListCount()).thenReturn(1); when(mParams.getStartOffset()).thenReturn(0); @@ -1368,35 +1641,71 @@ public class BluetoothMapContentTest { mCurrentFolder.setFolderId(TEST_ID); mContent.mMsgListingVersion = BluetoothMapUtils.MAP_MESSAGE_LISTING_FORMAT_V11; - MatrixCursor imCursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.DATE, - BluetoothMapContract.MessageColumns.SUBJECT, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.MESSAGE_SIZE, - BluetoothMapContract.MessageColumns.FROM_LIST, - BluetoothMapContract.MessageColumns.TO_LIST, - BluetoothMapContract.MessageColumns.FLAG_ATTACHMENT, - BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, - BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, - BluetoothMapContract.MessageColumns.FLAG_PROTECTED, - BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.DEVILERY_STATE, - BluetoothMapContract.MessageColumns.THREAD_ID, - BluetoothMapContract.MessageColumns.THREAD_NAME, - BluetoothMapContract.MessageColumns.ATTACHMENT_MINE_TYPES, - BluetoothMapContract.MessageColumns.BODY, - BluetoothMapContract.ConvoContactColumns.UCI, - BluetoothMapContract.ConvoContactColumns.NAME}); - imCursor.addRow(new Object[] {TEST_ID, TEST_DATE_IM, TEST_SUBJECT, TEST_SENT_NO, - TEST_READ_FALSE, TEST_SIZE, TEST_ID, TEST_TO_ADDRESS, TEST_ATTACHMENT_TRUE, - 0 /*=attachment size*/, TEST_PRIORITY_HIGH, TEST_PROTECTED, 0, TEST_DELIVERY_STATE, - TEST_THREAD_ID, TEST_NAME, TEST_ATTACHMENT_MIME_TYPE, 0, TEST_ADDRESS, TEST_NAME}); - doReturn(imCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION), any(), any(), any()); - doReturn(imCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_CONTACT_PROJECTION), any(), any(), any()); + MatrixCursor imCursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.DATE, + BluetoothMapContract.MessageColumns.SUBJECT, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.MESSAGE_SIZE, + BluetoothMapContract.MessageColumns.FROM_LIST, + BluetoothMapContract.MessageColumns.TO_LIST, + BluetoothMapContract.MessageColumns.FLAG_ATTACHMENT, + BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, + BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, + BluetoothMapContract.MessageColumns.FLAG_PROTECTED, + BluetoothMapContract.MessageColumns.RECEPTION_STATE, + BluetoothMapContract.MessageColumns.DEVILERY_STATE, + BluetoothMapContract.MessageColumns.THREAD_ID, + BluetoothMapContract.MessageColumns.THREAD_NAME, + BluetoothMapContract.MessageColumns.ATTACHMENT_MINE_TYPES, + BluetoothMapContract.MessageColumns.BODY, + BluetoothMapContract.ConvoContactColumns.UCI, + BluetoothMapContract.ConvoContactColumns.NAME + }); + imCursor.addRow( + new Object[] { + TEST_ID, + TEST_DATE_IM, + TEST_SUBJECT, + TEST_SENT_NO, + TEST_READ_FALSE, + TEST_SIZE, + TEST_ID, + TEST_TO_ADDRESS, + TEST_ATTACHMENT_TRUE, + 0 /*=attachment size*/, + TEST_PRIORITY_HIGH, + TEST_PROTECTED, + 0, + TEST_DELIVERY_STATE, + TEST_THREAD_ID, + TEST_NAME, + TEST_ATTACHMENT_MIME_TYPE, + 0, + TEST_ADDRESS, + TEST_NAME + }); + doReturn(imCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION), + any(), + any(), + any()); + doReturn(imCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_CONTACT_PROJECTION), + any(), + any(), + any()); BluetoothMapMessageListing listing = mContent.msgListing(mCurrentFolder, mParams); assertThat(listing.getCount()).isEqualTo(1); @@ -1430,26 +1739,44 @@ public class BluetoothMapContentTest { MatrixCursor smsCursor = new MatrixCursor(new String[] {"Placeholder"}); // Making cursor.getCount() as 1 smsCursor.addRow(new Object[] {1}); - doReturn(smsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContent.SMS_PROJECTION), any(), any(), any()); + doReturn(smsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), any(), eq(BluetoothMapContent.SMS_PROJECTION), any(), any(), any()); MatrixCursor mmsCursor = new MatrixCursor(new String[] {"Placeholder"}); // Making cursor.getCount() as 1 mmsCursor.addRow(new Object[] {1}); - doReturn(mmsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContent.MMS_PROJECTION), any(), any(), any()); + doReturn(mmsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), any(), eq(BluetoothMapContent.MMS_PROJECTION), any(), any(), any()); MatrixCursor emailCursor = new MatrixCursor(new String[] {"Placeholder"}); // Making cursor.getCount() as 1 emailCursor.addRow(new Object[] {1}); - doReturn(emailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_MESSAGE_PROJECTION), any(), any(), any()); + doReturn(emailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_MESSAGE_PROJECTION), + any(), + any(), + any()); MatrixCursor imCursor = new MatrixCursor(new String[] {"Placeholder"}); // Making cursor.getCount() as 1 imCursor.addRow(new Object[] {1}); - doReturn(imCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION), any(), any(), any()); + doReturn(imCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION), + any(), + any(), + any()); assertThat(mContent.msgListingSize(mCurrentFolder, mParams)).isEqualTo(4); } @@ -1465,49 +1792,92 @@ public class BluetoothMapContentTest { MatrixCursor smsCursor = new MatrixCursor(new String[] {"Placeholder"}); // Making cursor.getCount() as 1 smsCursor.addRow(new Object[] {1}); - doReturn(smsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContent.SMS_PROJECTION), any(), any(), any()); + doReturn(smsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), any(), eq(BluetoothMapContent.SMS_PROJECTION), any(), any(), any()); MatrixCursor mmsCursor = new MatrixCursor(new String[] {"Placeholder"}); // Making cursor.getCount() as 1 mmsCursor.addRow(new Object[] {1}); - doReturn(mmsCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContent.MMS_PROJECTION), any(), any(), any()); + doReturn(mmsCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), any(), eq(BluetoothMapContent.MMS_PROJECTION), any(), any(), any()); MatrixCursor emailCursor = new MatrixCursor(new String[] {"Placeholder"}); // Making cursor.getCount() as 1 emailCursor.addRow(new Object[] {1}); - doReturn(emailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_MESSAGE_PROJECTION), any(), any(), any()); + doReturn(emailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_MESSAGE_PROJECTION), + any(), + any(), + any()); MatrixCursor imCursor = new MatrixCursor(new String[] {"Placeholder"}); // Making cursor.getCount() as 1 imCursor.addRow(new Object[] {1}); - doReturn(imCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), - eq(BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION), any(), any(), any()); + doReturn(imCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + eq(BluetoothMapContract.BT_INSTANT_MESSAGE_PROJECTION), + any(), + any(), + any()); assertThat(mContent.msgListingHasUnread(mCurrentFolder, mParams)).isTrue(); } @Test public void extractMmsAddresses_withTypeMmsFrom() { - MatrixCursor addressCursor = new MatrixCursor(new String[] {Telephony.Mms.Addr.ADDRESS, - Telephony.Mms.Addr.TYPE}); + MatrixCursor addressCursor = + new MatrixCursor( + new String[] {Telephony.Mms.Addr.ADDRESS, Telephony.Mms.Addr.TYPE}); addressCursor.addRow(new Object[] {TEST_ADDRESS, BluetoothMapContent.MMS_FROM}); - doReturn(addressCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(Telephony.Mms.Addr.MSG_ID + "=" + TEST_ID), any(), any()); - - MatrixCursor contactCursor = new MatrixCursor(new String[] {ContactsContract.Contacts._ID, - ContactsContract.Contacts.DISPLAY_NAME}); + doReturn(addressCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(Telephony.Mms.Addr.MSG_ID + "=" + TEST_ID), + any(), + any()); + + MatrixCursor contactCursor = + new MatrixCursor( + new String[] { + ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME + }); contactCursor.addRow(new Object[] {TEST_ID_STRING, TEST_NAME}); - doReturn(contactCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"), any(), any()); - - MatrixCursor emailCursor = new MatrixCursor( - new String[]{ContactsContract.CommonDataKinds.Email.ADDRESS}); + doReturn(contactCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"), + any(), + any()); + + MatrixCursor emailCursor = + new MatrixCursor(new String[] {ContactsContract.CommonDataKinds.Email.ADDRESS}); emailCursor.addRow(new Object[] {TEST_EMAIL}); - doReturn(emailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"), any(), any()); + doReturn(emailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"), + any(), + any()); BluetoothMapbMessageMime mime = new BluetoothMapbMessageMime(); mContent.extractMmsAddresses(TEST_ID, mime); @@ -1519,23 +1889,48 @@ public class BluetoothMapContentTest { @Test public void extractMmsAddresses_withTypeMmsTo() { - MatrixCursor addressCursor = new MatrixCursor(new String[] {Telephony.Mms.Addr.ADDRESS, - Telephony.Mms.Addr.TYPE}); + MatrixCursor addressCursor = + new MatrixCursor( + new String[] {Telephony.Mms.Addr.ADDRESS, Telephony.Mms.Addr.TYPE}); addressCursor.addRow(new Object[] {TEST_ADDRESS, BluetoothMapContent.MMS_TO}); - doReturn(addressCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(Telephony.Mms.Addr.MSG_ID + "=" + TEST_ID), any(), any()); - - MatrixCursor contactCursor = new MatrixCursor(new String[] {ContactsContract.Contacts._ID, - ContactsContract.Contacts.DISPLAY_NAME}); + doReturn(addressCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(Telephony.Mms.Addr.MSG_ID + "=" + TEST_ID), + any(), + any()); + + MatrixCursor contactCursor = + new MatrixCursor( + new String[] { + ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME + }); contactCursor.addRow(new Object[] {TEST_ID_STRING, TEST_NAME}); - doReturn(contactCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"), any(), any()); - - MatrixCursor emailCursor = new MatrixCursor( - new String[]{ContactsContract.CommonDataKinds.Email.ADDRESS}); + doReturn(contactCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"), + any(), + any()); + + MatrixCursor emailCursor = + new MatrixCursor(new String[] {ContactsContract.CommonDataKinds.Email.ADDRESS}); emailCursor.addRow(new Object[] {TEST_EMAIL}); - doReturn(emailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"), any(), any()); + doReturn(emailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"), + any(), + any()); BluetoothMapbMessageMime mime = new BluetoothMapbMessageMime(); mContent.extractMmsAddresses(TEST_ID, mime); @@ -1547,23 +1942,48 @@ public class BluetoothMapContentTest { @Test public void extractMmsAddresses_withTypeMmsCc() { - MatrixCursor addressCursor = new MatrixCursor(new String[] {Telephony.Mms.Addr.ADDRESS, - Telephony.Mms.Addr.TYPE}); + MatrixCursor addressCursor = + new MatrixCursor( + new String[] {Telephony.Mms.Addr.ADDRESS, Telephony.Mms.Addr.TYPE}); addressCursor.addRow(new Object[] {TEST_ADDRESS, BluetoothMapContent.MMS_CC}); - doReturn(addressCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(Telephony.Mms.Addr.MSG_ID + "=" + TEST_ID), any(), any()); - - MatrixCursor contactCursor = new MatrixCursor(new String[] {ContactsContract.Contacts._ID, - ContactsContract.Contacts.DISPLAY_NAME}); + doReturn(addressCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(Telephony.Mms.Addr.MSG_ID + "=" + TEST_ID), + any(), + any()); + + MatrixCursor contactCursor = + new MatrixCursor( + new String[] { + ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME + }); contactCursor.addRow(new Object[] {TEST_ID_STRING, TEST_NAME}); - doReturn(contactCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"), any(), any()); - - MatrixCursor emailCursor = new MatrixCursor( - new String[]{ContactsContract.CommonDataKinds.Email.ADDRESS}); + doReturn(contactCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"), + any(), + any()); + + MatrixCursor emailCursor = + new MatrixCursor(new String[] {ContactsContract.CommonDataKinds.Email.ADDRESS}); emailCursor.addRow(new Object[] {TEST_EMAIL}); - doReturn(emailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"), any(), any()); + doReturn(emailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"), + any(), + any()); BluetoothMapbMessageMime mime = new BluetoothMapbMessageMime(); mContent.extractMmsAddresses(TEST_ID, mime); @@ -1575,23 +1995,48 @@ public class BluetoothMapContentTest { @Test public void extractMmsAddresses_withTypeMmsBcc() { - MatrixCursor addressCursor = new MatrixCursor(new String[] {Telephony.Mms.Addr.ADDRESS, - Telephony.Mms.Addr.TYPE}); + MatrixCursor addressCursor = + new MatrixCursor( + new String[] {Telephony.Mms.Addr.ADDRESS, Telephony.Mms.Addr.TYPE}); addressCursor.addRow(new Object[] {TEST_ADDRESS, BluetoothMapContent.MMS_BCC}); - doReturn(addressCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(Telephony.Mms.Addr.MSG_ID + "=" + TEST_ID), any(), any()); - - MatrixCursor contactCursor = new MatrixCursor(new String[] {ContactsContract.Contacts._ID, - ContactsContract.Contacts.DISPLAY_NAME}); + doReturn(addressCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(Telephony.Mms.Addr.MSG_ID + "=" + TEST_ID), + any(), + any()); + + MatrixCursor contactCursor = + new MatrixCursor( + new String[] { + ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME + }); contactCursor.addRow(new Object[] {TEST_ID_STRING, TEST_NAME}); - doReturn(contactCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"), any(), any()); - - MatrixCursor emailCursor = new MatrixCursor( - new String[]{ContactsContract.CommonDataKinds.Email.ADDRESS}); + doReturn(contactCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"), + any(), + any()); + + MatrixCursor emailCursor = + new MatrixCursor(new String[] {ContactsContract.CommonDataKinds.Email.ADDRESS}); emailCursor.addRow(new Object[] {TEST_EMAIL}); - doReturn(emailCursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), - eq(ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"), any(), any()); + doReturn(emailCursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + any(), + any(), + eq(ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"), + any(), + any()); BluetoothMapbMessageMime mime = new BluetoothMapbMessageMime(); mContent.extractMmsAddresses(TEST_ID, mime); @@ -1603,21 +2048,45 @@ public class BluetoothMapContentTest { @Test public void extractMmsParts() { - MatrixCursor cursor = new MatrixCursor( - new String[] {BaseColumns._ID, Telephony.Mms.Part.CONTENT_TYPE, - Telephony.Mms.Part.NAME, Telephony.Mms.Part.CHARSET, - Telephony.Mms.Part.FILENAME, Telephony.Mms.Part.TEXT, - Telephony.Mms.Part._DATA, Telephony.Mms.Part.CONTENT_ID, - Telephony.Mms.Part.CONTENT_LOCATION, - Telephony.Mms.Part.CONTENT_DISPOSITION}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), - eq(Uri.parse(Telephony.Mms.CONTENT_URI + "/" + TEST_ID + "/part")), any(), - eq(Telephony.Mms.Part.MSG_ID + "=" + TEST_ID), any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BaseColumns._ID, + Telephony.Mms.Part.CONTENT_TYPE, + Telephony.Mms.Part.NAME, + Telephony.Mms.Part.CHARSET, + Telephony.Mms.Part.FILENAME, + Telephony.Mms.Part.TEXT, + Telephony.Mms.Part._DATA, + Telephony.Mms.Part.CONTENT_ID, + Telephony.Mms.Part.CONTENT_LOCATION, + Telephony.Mms.Part.CONTENT_DISPOSITION + }); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery( + any(), + eq(Uri.parse(Telephony.Mms.CONTENT_URI + "/" + TEST_ID + "/part")), + any(), + eq(Telephony.Mms.Part.MSG_ID + "=" + TEST_ID), + any(), + any()); String filename = "test_filename"; String location = "test_content_location"; String disposition = "test_content_disposition"; - cursor.addRow(new Object[] {TEST_ID, TEST_ATTACHMENT_MIME_TYPE, TEST_NAME, "test_charset", - filename, TEST_TEXT, 1, TEST_ID_STRING, location, disposition}); + cursor.addRow( + new Object[] { + TEST_ID, + TEST_ATTACHMENT_MIME_TYPE, + TEST_NAME, + "test_charset", + filename, + TEST_TEXT, + 1, + TEST_ID_STRING, + location, + disposition + }); BluetoothMapbMessageMime mime = new BluetoothMapbMessageMime(); mime.setIncludeAttachments(false); @@ -1632,4 +2101,4 @@ public class BluetoothMapContentTest { assertThat(part.mCharsetName).isEqualTo("utf-8"); assertThat(part.mFileName).isEqualTo(filename); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoContactElementTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoContactElementTest.java index 68d0e0d92e8..229a3a5643a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoContactElementTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoContactElementTest.java @@ -56,23 +56,29 @@ public class BluetoothMapConvoContactElementTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private MapContact mMapContact; + @Mock private MapContact mMapContact; @Test public void constructorWithArguments() { BluetoothMapConvoContactElement contactElement = - new BluetoothMapConvoContactElement(TEST_UCI, TEST_NAME, TEST_DISPLAY_NAME, - TEST_PRESENCE_STATUS, TEST_PRESENCE_AVAILABILITY, TEST_LAST_ACTIVITY, - TEST_CHAT_STATE, TEST_PRIORITY, TEST_BT_UID); + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_PRESENCE_STATUS, + TEST_PRESENCE_AVAILABILITY, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE, + TEST_PRIORITY, + TEST_BT_UID); assertThat(contactElement.getContactId()).isEqualTo(TEST_UCI); assertThat(contactElement.getName()).isEqualTo(TEST_NAME); assertThat(contactElement.getDisplayName()).isEqualTo(TEST_DISPLAY_NAME); assertThat(contactElement.getPresenceStatus()).isEqualTo(TEST_PRESENCE_STATUS); assertThat(contactElement.getPresenceAvailability()).isEqualTo(TEST_PRESENCE_AVAILABILITY); - assertThat(contactElement.getLastActivityString()).isEqualTo( - format.format(TEST_LAST_ACTIVITY)); + assertThat(contactElement.getLastActivityString()) + .isEqualTo(format.format(TEST_LAST_ACTIVITY)); assertThat(contactElement.getChatState()).isEqualTo(TEST_CHAT_STATE); assertThat(contactElement.getPriority()).isEqualTo(TEST_PRIORITY); assertThat(contactElement.getBtUid()).isEqualTo(TEST_BT_UID); @@ -109,8 +115,8 @@ public class BluetoothMapConvoContactElementTest { assertThat(contactElement.getDisplayName()).isEqualTo(TEST_DISPLAY_NAME); assertThat(contactElement.getPresenceStatus()).isEqualTo(TEST_PRESENCE_STATUS); assertThat(contactElement.getPresenceAvailability()).isEqualTo(TEST_PRESENCE_AVAILABILITY); - assertThat(contactElement.getLastActivityString()).isEqualTo( - format.format(TEST_LAST_ACTIVITY)); + assertThat(contactElement.getLastActivityString()) + .isEqualTo(format.format(TEST_LAST_ACTIVITY)); assertThat(contactElement.getChatState()).isEqualTo(TEST_CHAT_STATE); assertThat(contactElement.getPriority()).isEqualTo(TEST_PRIORITY); assertThat(contactElement.getBtUid()).isEqualTo(TEST_BT_UID); @@ -118,10 +124,17 @@ public class BluetoothMapConvoContactElementTest { @Test public void encodeToXml_thenDecodeToInstance_returnsCorrectly() throws Exception { - BluetoothMapConvoContactElement contactElement = new - BluetoothMapConvoContactElement(TEST_UCI, TEST_NAME, TEST_DISPLAY_NAME, - TEST_PRESENCE_STATUS, TEST_PRESENCE_AVAILABILITY, TEST_LAST_ACTIVITY, - TEST_CHAT_STATE, TEST_PRIORITY, TEST_BT_UID); + BluetoothMapConvoContactElement contactElement = + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_PRESENCE_STATUS, + TEST_PRESENCE_AVAILABILITY, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE, + TEST_PRIORITY, + TEST_BT_UID); final XmlSerializer serializer = Xml.newSerializer(); final StringWriter writer = new StringWriter(); @@ -146,10 +159,10 @@ public class BluetoothMapConvoContactElementTest { assertThat(contactElementFromXml.getName()).isEqualTo(TEST_NAME); assertThat(contactElementFromXml.getDisplayName()).isEqualTo(TEST_DISPLAY_NAME); assertThat(contactElementFromXml.getPresenceStatus()).isEqualTo(TEST_PRESENCE_STATUS); - assertThat(contactElementFromXml.getPresenceAvailability()).isEqualTo( - TEST_PRESENCE_AVAILABILITY); - assertThat(contactElementFromXml.getLastActivityString()).isEqualTo( - format.format(TEST_LAST_ACTIVITY)); + assertThat(contactElementFromXml.getPresenceAvailability()) + .isEqualTo(TEST_PRESENCE_AVAILABILITY); + assertThat(contactElementFromXml.getLastActivityString()) + .isEqualTo(format.format(TEST_LAST_ACTIVITY)); assertThat(contactElementFromXml.getChatState()).isEqualTo(TEST_CHAT_STATE); assertThat(contactElementFromXml.getPriority()).isEqualTo(TEST_PRIORITY); assertThat(contactElementFromXml.getBtUid()).isEqualTo(TEST_BT_UID); @@ -158,14 +171,28 @@ public class BluetoothMapConvoContactElementTest { @Test public void equalsWithSameValues_returnsTrue() { BluetoothMapConvoContactElement contactElement = - new BluetoothMapConvoContactElement(TEST_UCI, TEST_NAME, TEST_DISPLAY_NAME, - TEST_PRESENCE_STATUS, TEST_PRESENCE_AVAILABILITY, TEST_LAST_ACTIVITY, - TEST_CHAT_STATE, TEST_PRIORITY, TEST_BT_UID); + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_PRESENCE_STATUS, + TEST_PRESENCE_AVAILABILITY, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE, + TEST_PRIORITY, + TEST_BT_UID); BluetoothMapConvoContactElement contactElementEqual = - new BluetoothMapConvoContactElement(TEST_UCI, TEST_NAME, TEST_DISPLAY_NAME, - TEST_PRESENCE_STATUS, TEST_PRESENCE_AVAILABILITY, TEST_LAST_ACTIVITY, - TEST_CHAT_STATE, TEST_PRIORITY, TEST_BT_UID); + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_PRESENCE_STATUS, + TEST_PRESENCE_AVAILABILITY, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE, + TEST_PRIORITY, + TEST_BT_UID); assertThat(contactElement).isEqualTo(contactElementEqual); } @@ -173,14 +200,28 @@ public class BluetoothMapConvoContactElementTest { @Test public void equalsWithDifferentPriority_returnsFalse() { BluetoothMapConvoContactElement contactElement = - new BluetoothMapConvoContactElement(TEST_UCI, TEST_NAME, TEST_DISPLAY_NAME, - TEST_PRESENCE_STATUS, TEST_PRESENCE_AVAILABILITY, TEST_LAST_ACTIVITY, - TEST_CHAT_STATE, TEST_PRIORITY, TEST_BT_UID); + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_PRESENCE_STATUS, + TEST_PRESENCE_AVAILABILITY, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE, + TEST_PRIORITY, + TEST_BT_UID); BluetoothMapConvoContactElement contactElementWithDifferentPriority = - new BluetoothMapConvoContactElement(TEST_UCI, TEST_NAME, TEST_DISPLAY_NAME, - TEST_PRESENCE_STATUS, TEST_PRESENCE_AVAILABILITY, TEST_LAST_ACTIVITY, - TEST_CHAT_STATE, /*priority=*/0, TEST_BT_UID); + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_PRESENCE_STATUS, + TEST_PRESENCE_AVAILABILITY, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE, + /* priority= */ 0, + TEST_BT_UID); assertThat(contactElement).isNotEqualTo(contactElementWithDifferentPriority); } @@ -188,14 +229,28 @@ public class BluetoothMapConvoContactElementTest { @Test public void compareTo_withSameValues_returnsZero() { BluetoothMapConvoContactElement contactElement = - new BluetoothMapConvoContactElement(TEST_UCI, TEST_NAME, TEST_DISPLAY_NAME, - TEST_PRESENCE_STATUS, TEST_PRESENCE_AVAILABILITY, TEST_LAST_ACTIVITY, - TEST_CHAT_STATE, TEST_PRIORITY, TEST_BT_UID); + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_PRESENCE_STATUS, + TEST_PRESENCE_AVAILABILITY, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE, + TEST_PRIORITY, + TEST_BT_UID); BluetoothMapConvoContactElement contactElementSameLastActivity = - new BluetoothMapConvoContactElement(TEST_UCI, TEST_NAME, TEST_DISPLAY_NAME, - TEST_PRESENCE_STATUS, TEST_PRESENCE_AVAILABILITY, TEST_LAST_ACTIVITY, - TEST_CHAT_STATE, TEST_PRIORITY, TEST_BT_UID); + new BluetoothMapConvoContactElement( + TEST_UCI, + TEST_NAME, + TEST_DISPLAY_NAME, + TEST_PRESENCE_STATUS, + TEST_PRESENCE_AVAILABILITY, + TEST_LAST_ACTIVITY, + TEST_CHAT_STATE, + TEST_PRIORITY, + TEST_BT_UID); assertThat(contactElement.compareTo(contactElementSameLastActivity)).isEqualTo(0); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoListingElementTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoListingElementTest.java index 9e971a5ba6e..87739756e67 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoListingElementTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoListingElementTest.java @@ -52,17 +52,31 @@ public class BluetoothMapConvoListingElementTest { private static final String TEST_SMS_MMS_CONTACTS = "test_sms_mms_contacts"; private final BluetoothMapConvoContactElement TEST_CONTACT_ELEMENT_ONE = - new BluetoothMapConvoContactElement("test_uci_one", "test_name_one", - "test_display_name_one", "test_presence_status_one", 2, TEST_LAST_ACTIVITY, 2, - 1, "1111"); + new BluetoothMapConvoContactElement( + "test_uci_one", + "test_name_one", + "test_display_name_one", + "test_presence_status_one", + 2, + TEST_LAST_ACTIVITY, + 2, + 1, + "1111"); private final BluetoothMapConvoContactElement TEST_CONTACT_ELEMENT_TWO = - new BluetoothMapConvoContactElement("test_uci_two", "test_name_two", - "test_display_name_two", "test_presence_status_two", 1, TEST_LAST_ACTIVITY, 1, - 2, "1112"); - - private final List TEST_CONTACTS = new ArrayList<>( - Arrays.asList(TEST_CONTACT_ELEMENT_ONE, TEST_CONTACT_ELEMENT_TWO)); + new BluetoothMapConvoContactElement( + "test_uci_two", + "test_name_two", + "test_display_name_two", + "test_presence_status_two", + 1, + TEST_LAST_ACTIVITY, + 1, + 2, + "1112"); + + private final List TEST_CONTACTS = + new ArrayList<>(Arrays.asList(TEST_CONTACT_ELEMENT_ONE, TEST_CONTACT_ELEMENT_TWO)); private final SignedLongLong signedLongLong = new SignedLongLong(TEST_ID, 0); @@ -95,8 +109,8 @@ public class BluetoothMapConvoListingElementTest { assertThat(mListingElement.getRead()).isEqualTo("READ"); assertThat(mListingElement.getReadBool()).isEqualTo(TEST_READ); assertThat(mListingElement.getConvoId()).isEqualTo(signedLongLong.toHexString()); - assertThat(mListingElement.getCpConvoId()).isEqualTo( - signedLongLong.getLeastSignificantBits()); + assertThat(mListingElement.getCpConvoId()) + .isEqualTo(signedLongLong.getLeastSignificantBits()); assertThat(mListingElement.getFullSummary()).isEqualTo(TEST_SUMMARY); assertThat(mListingElement.getSmsMmsContacts()).isEqualTo(TEST_SMS_MMS_CONTACTS); } @@ -168,8 +182,7 @@ public class BluetoothMapConvoListingElementTest { @Test public void equalsWithDifferentRead_returnsFalse() { - BluetoothMapConvoListingElement - listingElement = new BluetoothMapConvoListingElement(); + BluetoothMapConvoListingElement listingElement = new BluetoothMapConvoListingElement(); BluetoothMapConvoListingElement listingElementWithDifferentRead = new BluetoothMapConvoListingElement(); @@ -180,8 +193,7 @@ public class BluetoothMapConvoListingElementTest { @Test public void compareToWithSameValues_returnsZero() { - BluetoothMapConvoListingElement - listingElement = new BluetoothMapConvoListingElement(); + BluetoothMapConvoListingElement listingElement = new BluetoothMapConvoListingElement(); listingElement.setLastActivity(TEST_LAST_ACTIVITY); BluetoothMapConvoListingElement listingElementSameLastActivity = @@ -190,4 +202,4 @@ public class BluetoothMapConvoListingElementTest { assertThat(listingElement.compareTo(listingElementSameLastActivity)).isEqualTo(0); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoListingTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoListingTest.java index 432506b35c9..f2ae388baf8 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoListingTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapConvoListingTest.java @@ -91,8 +91,8 @@ public class BluetoothMapConvoListingTest { public void sort() { // BluetoothMapConvoListingElements are sorted according to their mLastActivity values mListing.sort(); - assertThat(mListing.getList().get(0).getLastActivity()).isEqualTo( - TEST_LAST_ACTIVITY_LATEST); + assertThat(mListing.getList().get(0).getLastActivity()) + .isEqualTo(TEST_LAST_ACTIVITY_LATEST); } @Test @@ -171,9 +171,9 @@ public class BluetoothMapConvoListingTest { BluetoothMapConvoListing listing = new BluetoothMapConvoListing(); listing.appendFromXml(listingStream); assertThat(listing.getList().size()).isEqualTo(2); - assertThat(listing.getList().get(0).getConvoId()).isEqualTo( - signedLongLongIdOne.toHexString()); - assertThat(listing.getList().get(1).getConvoId()).isEqualTo( - signedLongLongIdTwo.toHexString()); + assertThat(listing.getList().get(0).getConvoId()) + .isEqualTo(signedLongLongIdOne.toHexString()); + assertThat(listing.getList().get(1).getConvoId()) + .isEqualTo(signedLongLongIdTwo.toHexString()); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapFolderElementTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapFolderElementTest.java index d6f7ff9d8b2..0ba98aef33d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapFolderElementTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapFolderElementTest.java @@ -55,7 +55,6 @@ public class BluetoothMapFolderElementTest { private BluetoothMapFolderElement mParentFolderElement; private BluetoothMapFolderElement mTestFolderElement; - @Before public void setUp() throws Exception { mRootFolderElement.setFolderId(TEST_ROOT_FOLDER_ID); @@ -73,7 +72,6 @@ public class BluetoothMapFolderElementTest { mTestFolderElement.setHasImContent(TEST_HAS_IM_CONTENT); } - @Test public void getters() { assertThat(mTestFolderElement.shouldIgnore()).isEqualTo(TEST_IGNORE); @@ -85,8 +83,8 @@ public class BluetoothMapFolderElementTest { @Test public void getFullPath() { - assertThat(mTestFolderElement.getFullPath()).isEqualTo( - String.format("%s/%s", TEST_PARENT_FOLDER_NAME, TEST_FOLDER_NAME)); + assertThat(mTestFolderElement.getFullPath()) + .isEqualTo(String.format("%s/%s", TEST_PARENT_FOLDER_NAME, TEST_FOLDER_NAME)); } @Test @@ -100,12 +98,12 @@ public class BluetoothMapFolderElementTest { mTestFolderElement.addImFolder(TEST_IM_FOLDER_NAME, TEST_IM_FOLDER_ID); mTestFolderElement.addEmailFolder(TEST_EMAIL_FOLDER_NAME, TEST_EMAIL_FOLDER_ID); - assertThat(mTestFolderElement.getSubFolder(TEST_SMS_MMS_FOLDER_NAME).getName()).isEqualTo( - TEST_SMS_MMS_FOLDER_NAME); - assertThat(mTestFolderElement.getSubFolder(TEST_IM_FOLDER_NAME).getName()).isEqualTo( - TEST_IM_FOLDER_NAME); - assertThat(mTestFolderElement.getSubFolder(TEST_EMAIL_FOLDER_NAME).getName()).isEqualTo( - TEST_EMAIL_FOLDER_NAME); + assertThat(mTestFolderElement.getSubFolder(TEST_SMS_MMS_FOLDER_NAME).getName()) + .isEqualTo(TEST_SMS_MMS_FOLDER_NAME); + assertThat(mTestFolderElement.getSubFolder(TEST_IM_FOLDER_NAME).getName()) + .isEqualTo(TEST_IM_FOLDER_NAME); + assertThat(mTestFolderElement.getSubFolder(TEST_EMAIL_FOLDER_NAME).getName()) + .isEqualTo(TEST_EMAIL_FOLDER_NAME); mTestFolderElement.addFolder(TEST_SMS_MMS_FOLDER_NAME); assertThat(mTestFolderElement.getSubFolderCount()).isEqualTo(3); @@ -114,24 +112,26 @@ public class BluetoothMapFolderElementTest { @Test public void getFolderById() { assertThat(mTestFolderElement.getFolderById(TEST_FOLDER_ID)).isEqualTo(mTestFolderElement); - assertThat(mRootFolderElement.getFolderById(TEST_ROOT_FOLDER_ID)).isEqualTo( - mRootFolderElement); + assertThat(mRootFolderElement.getFolderById(TEST_ROOT_FOLDER_ID)) + .isEqualTo(mRootFolderElement); assertThat(BluetoothMapFolderElement.getFolderById(TEST_FOLDER_ID, null)).isNull(); - assertThat(BluetoothMapFolderElement.getFolderById(TEST_PLACEHOLDER_ID, - mTestFolderElement)).isNull(); + assertThat(BluetoothMapFolderElement.getFolderById(TEST_PLACEHOLDER_ID, mTestFolderElement)) + .isNull(); } @Test public void getFolderByName() { mRootFolderElement.addFolder(TEST_TELECOM_FOLDER_NAME); mRootFolderElement.getSubFolder(TEST_TELECOM_FOLDER_NAME).addFolder(TEST_MSG_FOLDER_NAME); - BluetoothMapFolderElement placeholderFolderElement = mRootFolderElement.getSubFolder( - TEST_TELECOM_FOLDER_NAME).getSubFolder(TEST_MSG_FOLDER_NAME).addFolder( - TEST_PLACEHOLDER_FOLDER_NAME); + BluetoothMapFolderElement placeholderFolderElement = + mRootFolderElement + .getSubFolder(TEST_TELECOM_FOLDER_NAME) + .getSubFolder(TEST_MSG_FOLDER_NAME) + .addFolder(TEST_PLACEHOLDER_FOLDER_NAME); assertThat(mRootFolderElement.getFolderByName(TEST_PLACEHOLDER_FOLDER_NAME)).isNull(); placeholderFolderElement.setFolderId(TEST_PLACEHOLDER_ID); - assertThat(mRootFolderElement.getFolderByName(TEST_PLACEHOLDER_FOLDER_NAME)).isEqualTo( - placeholderFolderElement); + assertThat(mRootFolderElement.getFolderByName(TEST_PLACEHOLDER_FOLDER_NAME)) + .isEqualTo(placeholderFolderElement); } @Test @@ -161,11 +161,10 @@ public class BluetoothMapFolderElementTest { mTestFolderElement.addSmsMmsFolder(TEST_SMS_MMS_FOLDER_NAME); folderElementWithDifferentSubFoldersSize.addSmsMmsFolder(TEST_SMS_MMS_FOLDER_NAME); - folderElementWithDifferentSubFoldersSize.addImFolder(TEST_IM_FOLDER_NAME, - TEST_IM_FOLDER_ID); - assertThat( - mTestFolderElement.compareTo(folderElementWithDifferentSubFoldersSize)).isEqualTo( - -1); + folderElementWithDifferentSubFoldersSize.addImFolder( + TEST_IM_FOLDER_NAME, TEST_IM_FOLDER_ID); + assertThat(mTestFolderElement.compareTo(folderElementWithDifferentSubFoldersSize)) + .isEqualTo(-1); } @Test @@ -175,10 +174,10 @@ public class BluetoothMapFolderElementTest { mTestFolderElement.addSmsMmsFolder(TEST_SMS_MMS_FOLDER_NAME); folderElementWithDifferentSubFoldersTree.addSmsMmsFolder(TEST_SMS_MMS_FOLDER_NAME); - folderElementWithDifferentSubFoldersTree.getSubFolder(TEST_SMS_MMS_FOLDER_NAME).addFolder( - TEST_PLACEHOLDER_FOLDER_NAME); - assertThat( - mTestFolderElement.compareTo(folderElementWithDifferentSubFoldersTree)).isEqualTo( - -1); + folderElementWithDifferentSubFoldersTree + .getSubFolder(TEST_SMS_MMS_FOLDER_NAME) + .addFolder(TEST_PLACEHOLDER_FOLDER_NAME); + assertThat(mTestFolderElement.compareTo(folderElementWithDifferentSubFoldersTree)) + .isEqualTo(-1); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMasInstanceTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMasInstanceTest.java index b985cd3a4a3..19dda41311a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMasInstanceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMasInstanceTest.java @@ -51,25 +51,37 @@ public class BluetoothMapMasInstanceTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private Context mContext; - @Mock - private BluetoothMapService mMapService; + @Mock private Context mContext; + @Mock private BluetoothMapService mMapService; @Before public void setUp() { - mAccountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, - TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); + mAccountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); } @Test public void toString_returnsInfo() { - BluetoothMapMasInstance instance = new BluetoothMapMasInstance(mMapService, mContext, - mAccountItem, TEST_MAS_ID, TEST_ENABLE_SMS_MMS); + BluetoothMapMasInstance instance = + new BluetoothMapMasInstance( + mMapService, mContext, mAccountItem, TEST_MAS_ID, TEST_ENABLE_SMS_MMS); - String expected = "MasId: " + TEST_MAS_ID + " Uri:" + mAccountItem.mBase_uri + " SMS/MMS:" - + TEST_ENABLE_SMS_MMS; + String expected = + "MasId: " + + TEST_MAS_ID + + " Uri:" + + mAccountItem.mBase_uri + + " SMS/MMS:" + + TEST_ENABLE_SMS_MMS; assertThat(instance.toString()).isEqualTo(expected); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMessageListingElementTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMessageListingElementTest.java index 77cb343ca98..81fa5b5122a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMessageListingElementTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMessageListingElementTest.java @@ -101,15 +101,15 @@ public class BluetoothMapMessageListingElementTest { assertThat(mMessageListingElement.getHandle()).isEqualTo(TEST_CP_HANDLE); assertThat(mMessageListingElement.getSubject()).isEqualTo(TEST_SUBJECT); assertThat(mMessageListingElement.getDateTime()).isEqualTo(TEST_DATE_TIME); - assertThat(mMessageListingElement.getDateTimeString()).isEqualTo( - format.format(TEST_DATE_TIME)); + assertThat(mMessageListingElement.getDateTimeString()) + .isEqualTo(format.format(TEST_DATE_TIME)); assertThat(mMessageListingElement.getSenderName()).isEqualTo(TEST_SENDER_NAME); assertThat(mMessageListingElement.getSenderAddressing()).isEqualTo(TEST_SENDER_ADDRESSING); - assertThat(mMessageListingElement.getReplyToAddressing()).isEqualTo( - TEST_REPLY_TO_ADDRESSING); + assertThat(mMessageListingElement.getReplyToAddressing()) + .isEqualTo(TEST_REPLY_TO_ADDRESSING); assertThat(mMessageListingElement.getRecipientName()).isEqualTo(TEST_RECIPIENT_NAME); - assertThat(mMessageListingElement.getRecipientAddressing()).isEqualTo( - TEST_RECIPIENT_ADDRESSING); + assertThat(mMessageListingElement.getRecipientAddressing()) + .isEqualTo(TEST_RECIPIENT_ADDRESSING); assertThat(mMessageListingElement.getType()).isEqualTo(TEST_TYPE); assertThat(mMessageListingElement.getSize()).isEqualTo(TEST_SIZE); assertThat(mMessageListingElement.getText()).isEqualTo(TEST_TEXT); @@ -123,8 +123,8 @@ public class BluetoothMapMessageListingElementTest { assertThat(mMessageListingElement.getProtect()).isEqualTo(TEST_PROTECT); assertThat(mMessageListingElement.getFolderType()).isEqualTo(TEST_FOLDER_TYPE); assertThat(mMessageListingElement.getThreadName()).isEqualTo(TEST_THREAD_NAME); - assertThat(mMessageListingElement.getAttachmentMimeTypes()).isEqualTo( - TEST_ATTACHMENT_MIME_TYPES); + assertThat(mMessageListingElement.getAttachmentMimeTypes()) + .isEqualTo(TEST_ATTACHMENT_MIME_TYPES); assertThat(mMessageListingElement.getCursorIndex()).isEqualTo(TEST_CURSOR_INDEX); } @@ -155,14 +155,14 @@ public class BluetoothMapMessageListingElementTest { String attributeName = parser.getAttributeName(i).trim(); String attributeValue = parser.getAttributeValue(i); if (attributeName.equalsIgnoreCase("handle")) { - assertThat(attributeValue).isEqualTo( - BluetoothMapUtils.getMapHandle(TEST_CP_HANDLE, TEST_TYPE)); + assertThat(attributeValue) + .isEqualTo(BluetoothMapUtils.getMapHandle(TEST_CP_HANDLE, TEST_TYPE)); } else if (attributeName.equalsIgnoreCase("datetime")) { - assertThat(attributeValue).isEqualTo( - BluetoothMapUtils.getDateTimeString(TEST_DATE_TIME)); + assertThat(attributeValue) + .isEqualTo(BluetoothMapUtils.getDateTimeString(TEST_DATE_TIME)); } else if (attributeName.equalsIgnoreCase("sender_name")) { - assertThat(attributeValue).isEqualTo( - BluetoothMapUtils.stripInvalidChars(TEST_SENDER_NAME)); + assertThat(attributeValue) + .isEqualTo(BluetoothMapUtils.stripInvalidChars(TEST_SENDER_NAME)); } else if (attributeName.equalsIgnoreCase("sender_addressing")) { assertThat(attributeValue).isEqualTo(TEST_SENDER_ADDRESSING); } else if (attributeName.equalsIgnoreCase("replyto_addressing")) { @@ -194,8 +194,8 @@ public class BluetoothMapMessageListingElementTest { } else if (attributeName.equalsIgnoreCase("protected")) { assertThat(attributeValue).isEqualTo(TEST_PROTECT); } else if (attributeName.equalsIgnoreCase("conversation_id")) { - assertThat(attributeValue).isEqualTo( - BluetoothMapUtils.getMapConvoHandle(TEST_THREAD_ID, TEST_TYPE)); + assertThat(attributeValue) + .isEqualTo(BluetoothMapUtils.getMapConvoHandle(TEST_THREAD_ID, TEST_TYPE)); } else if (attributeName.equalsIgnoreCase("conversation_name")) { assertThat(attributeValue).isEqualTo(TEST_THREAD_NAME); } else if (attributeName.equalsIgnoreCase("folder_type")) { @@ -229,4 +229,4 @@ public class BluetoothMapMessageListingElementTest { elementWithEqualDateTime.setDateTime(TEST_DATE_TIME); assertThat(mMessageListingElement.compareTo(elementWithEqualDateTime)).isEqualTo(0); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMessageListingTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMessageListingTest.java index 51fdb486dd2..7b1a121d2e9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMessageListingTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMessageListingTest.java @@ -126,8 +126,8 @@ public class BluetoothMapMessageListingTest { assertThat(listingToAppend.getList().size()).isEqualTo(2); - final InputStream listingStream = new ByteArrayInputStream( - listingToAppend.encode(false, TEST_VERSION)); + final InputStream listingStream = + new ByteArrayInputStream(listingToAppend.encode(false, TEST_VERSION)); BluetoothMapMessageListing listing = new BluetoothMapMessageListing(); appendFromXml(listingStream, listing); @@ -188,8 +188,10 @@ public class BluetoothMapMessageListingTest { String attributeName = parser.getAttributeName(i).trim(); String attributeValue = parser.getAttributeValue(i); if (attributeName.equalsIgnoreCase("datetime")) { - newElement.setDateTime(LocalDateTime.parse(attributeValue, formatter).toInstant( - ZoneOffset.ofTotalSeconds(0)).toEpochMilli()); + newElement.setDateTime( + LocalDateTime.parse(attributeValue, formatter) + .toInstant(ZoneOffset.ofTotalSeconds(0)) + .toEpochMilli()); } else if (attributeName.equalsIgnoreCase("read")) { newElement.setRead(true, true); } @@ -197,4 +199,4 @@ public class BluetoothMapMessageListingTest { parser.nextTag(); return newElement; } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java index 40503a775f4..19dae89d5d0 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java @@ -71,57 +71,76 @@ public class BluetoothMapObexServerTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private Context mContext; - @Mock - private BluetoothMapService mMapService; - @Mock - private ContentProviderClient mProviderClient; - @Mock - private BluetoothMapContentObserver mObserver; - @Spy - private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); + @Mock private Context mContext; + @Mock private BluetoothMapService mMapService; + @Mock private ContentProviderClient mProviderClient; + @Mock private BluetoothMapContentObserver mObserver; + @Spy private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); @Before public void setUp() throws Exception { BluetoothMethodProxy.setInstanceForTesting(mMapMethodProxy); - doReturn(mProviderClient).when( - mMapMethodProxy).contentResolverAcquireUnstableContentProviderClient(any(), any()); - mAccountItem = BluetoothMapAccountItem.create(TEST_ID, TEST_NAME, TEST_PACKAGE_NAME, - TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, TEST_TYPE, TEST_UCI, TEST_UCI_PREFIX); - mMasInstance = new BluetoothMapMasInstance(mMapService, mContext, - mAccountItem, TEST_MAS_ID, TEST_ENABLE_SMS_MMS); + doReturn(mProviderClient) + .when(mMapMethodProxy) + .contentResolverAcquireUnstableContentProviderClient(any(), any()); + mAccountItem = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + TEST_TYPE, + TEST_UCI, + TEST_UCI_PREFIX); + mMasInstance = + new BluetoothMapMasInstance( + mMapService, mContext, mAccountItem, TEST_MAS_ID, TEST_ENABLE_SMS_MMS); mParams = new BluetoothMapAppParams(); - mObexServer = new BluetoothMapObexServer(null, mContext, mObserver, mMasInstance, - mAccountItem, TEST_ENABLE_SMS_MMS); + mObexServer = + new BluetoothMapObexServer( + null, mContext, mObserver, mMasInstance, mAccountItem, TEST_ENABLE_SMS_MMS); } @Test public void setOwnerStatus_withAccountTypeEmail() throws Exception { doReturn(null).when(mProviderClient).query(any(), any(), any(), any(), any()); - BluetoothMapAccountItem accountItemWithTypeEmail = BluetoothMapAccountItem.create(TEST_ID, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - BluetoothMapUtils.TYPE.EMAIL, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapObexServer obexServer = new BluetoothMapObexServer(null, mContext, mObserver, - mMasInstance, accountItemWithTypeEmail, TEST_ENABLE_SMS_MMS); - - assertThat(obexServer.setOwnerStatus(mParams)).isEqualTo( - ResponseCodes.OBEX_HTTP_UNAVAILABLE); + BluetoothMapAccountItem accountItemWithTypeEmail = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + BluetoothMapUtils.TYPE.EMAIL, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapObexServer obexServer = + new BluetoothMapObexServer( + null, + mContext, + mObserver, + mMasInstance, + accountItemWithTypeEmail, + TEST_ENABLE_SMS_MMS); + + assertThat(obexServer.setOwnerStatus(mParams)) + .isEqualTo(ResponseCodes.OBEX_HTTP_UNAVAILABLE); } @Test public void setOwnerStatus_withAppParamsInvalid() throws Exception { BluetoothMapAppParams params = mock(BluetoothMapAppParams.class); - when(params.getPresenceAvailability()).thenReturn( - BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(params.getPresenceAvailability()) + .thenReturn(BluetoothMapAppParams.INVALID_VALUE_PARAMETER); when(params.getPresenceStatus()).thenReturn(null); - when(params.getLastActivity()).thenReturn( - (long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); + when(params.getLastActivity()) + .thenReturn((long) BluetoothMapAppParams.INVALID_VALUE_PARAMETER); when(params.getChatState()).thenReturn(BluetoothMapAppParams.INVALID_VALUE_PARAMETER); when(params.getChatStateConvoIdString()).thenReturn(null); - assertThat(mObexServer.setOwnerStatus(params)).isEqualTo( - ResponseCodes.OBEX_HTTP_PRECON_FAILED); + assertThat(mObexServer.setOwnerStatus(params)) + .isEqualTo(ResponseCodes.OBEX_HTTP_PRECON_FAILED); } @Test @@ -130,8 +149,7 @@ public class BluetoothMapObexServerTest { Bundle bundle = new Bundle(); when(mProviderClient.call(any(), any(), any())).thenReturn(bundle); - assertThat(mObexServer.setOwnerStatus(mParams)).isEqualTo( - ResponseCodes.OBEX_HTTP_OK); + assertThat(mObexServer.setOwnerStatus(mParams)).isEqualTo(ResponseCodes.OBEX_HTTP_OK); } @Test @@ -139,8 +157,8 @@ public class BluetoothMapObexServerTest { setUpBluetoothMapAppParams(mParams); when(mProviderClient.call(any(), any(), any())).thenReturn(null); - assertThat(mObexServer.setOwnerStatus(mParams)).isEqualTo( - ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED); + assertThat(mObexServer.setOwnerStatus(mParams)) + .isEqualTo(ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED); } @Test @@ -148,8 +166,8 @@ public class BluetoothMapObexServerTest { setUpBluetoothMapAppParams(mParams); doThrow(RemoteException.class).when(mProviderClient).call(any(), any(), any()); - assertThat(mObexServer.setOwnerStatus(mParams)).isEqualTo( - ResponseCodes.OBEX_HTTP_UNAVAILABLE); + assertThat(mObexServer.setOwnerStatus(mParams)) + .isEqualTo(ResponseCodes.OBEX_HTTP_UNAVAILABLE); } @Test @@ -157,8 +175,8 @@ public class BluetoothMapObexServerTest { setUpBluetoothMapAppParams(mParams); doThrow(NullPointerException.class).when(mProviderClient).call(any(), any(), any()); - assertThat(mObexServer.setOwnerStatus(mParams)).isEqualTo( - ResponseCodes.OBEX_HTTP_UNAVAILABLE); + assertThat(mObexServer.setOwnerStatus(mParams)) + .isEqualTo(ResponseCodes.OBEX_HTTP_UNAVAILABLE); } @Test @@ -166,23 +184,32 @@ public class BluetoothMapObexServerTest { setUpBluetoothMapAppParams(mParams); doThrow(IllegalArgumentException.class).when(mProviderClient).call(any(), any(), any()); - assertThat(mObexServer.setOwnerStatus(mParams)).isEqualTo( - ResponseCodes.OBEX_HTTP_UNAVAILABLE); + assertThat(mObexServer.setOwnerStatus(mParams)) + .isEqualTo(ResponseCodes.OBEX_HTTP_UNAVAILABLE); } @Test public void addEmailFolders() throws Exception { - MatrixCursor cursor = new MatrixCursor(new String[]{BluetoothMapContract.FolderColumns.NAME, - BluetoothMapContract.FolderColumns._ID}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.FolderColumns.NAME, + BluetoothMapContract.FolderColumns._ID + }); long parentId = 1; long childId = 2; - cursor.addRow(new Object[]{"test_name", childId}); + cursor.addRow(new Object[] {"test_name", childId}); cursor.moveToFirst(); BluetoothMapFolderElement parentFolder = new BluetoothMapFolderElement("parent", null); parentFolder.setFolderId(parentId); - doReturn(cursor).when(mProviderClient).query(any(), any(), - eq(BluetoothMapContract.FolderColumns.PARENT_FOLDER_ID + " = " + parentId), any(), - any()); + doReturn(cursor) + .when(mProviderClient) + .query( + any(), + any(), + eq(BluetoothMapContract.FolderColumns.PARENT_FOLDER_ID + " = " + parentId), + any(), + any()); mObexServer.addEmailFolders(parentFolder); @@ -191,8 +218,8 @@ public class BluetoothMapObexServerTest { @Test public void setMsgTypeFilterParams_withAccountNull_andOverwriteTrue() throws Exception { - BluetoothMapObexServer obexServer = new BluetoothMapObexServer(null, mContext, mObserver, - mMasInstance, null, false); + BluetoothMapObexServer obexServer = + new BluetoothMapObexServer(null, mContext, mObserver, mMasInstance, null, false); obexServer.setMsgTypeFilterParams(mParams, true); @@ -207,24 +234,51 @@ public class BluetoothMapObexServerTest { @Test public void setMsgTypeFilterParams_withInvalidFilterMessageType() throws Exception { - BluetoothMapAccountItem accountItemWithTypeEmail = BluetoothMapAccountItem.create(TEST_ID, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - BluetoothMapUtils.TYPE.EMAIL, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapObexServer obexServer = new BluetoothMapObexServer(null, mContext, mObserver, - mMasInstance, accountItemWithTypeEmail, TEST_ENABLE_SMS_MMS); + BluetoothMapAccountItem accountItemWithTypeEmail = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + BluetoothMapUtils.TYPE.EMAIL, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapObexServer obexServer = + new BluetoothMapObexServer( + null, + mContext, + mObserver, + mMasInstance, + accountItemWithTypeEmail, + TEST_ENABLE_SMS_MMS); // Passing mParams without any previous settings pass invalid filter message type - assertThrows(IllegalArgumentException.class, + assertThrows( + IllegalArgumentException.class, () -> obexServer.setMsgTypeFilterParams(mParams, false)); } @Test public void setMsgTypeFilterParams_withValidFilterMessageType() throws Exception { - BluetoothMapAccountItem accountItemWithTypeIm = BluetoothMapAccountItem.create(TEST_ID, - TEST_NAME, TEST_PACKAGE_NAME, TEST_PROVIDER_AUTHORITY, TEST_DRAWABLE, - BluetoothMapUtils.TYPE.IM, TEST_UCI, TEST_UCI_PREFIX); - BluetoothMapObexServer obexServer = new BluetoothMapObexServer(null, mContext, mObserver, - mMasInstance, accountItemWithTypeIm, TEST_ENABLE_SMS_MMS); + BluetoothMapAccountItem accountItemWithTypeIm = + BluetoothMapAccountItem.create( + TEST_ID, + TEST_NAME, + TEST_PACKAGE_NAME, + TEST_PROVIDER_AUTHORITY, + TEST_DRAWABLE, + BluetoothMapUtils.TYPE.IM, + TEST_UCI, + TEST_UCI_PREFIX); + BluetoothMapObexServer obexServer = + new BluetoothMapObexServer( + null, + mContext, + mObserver, + mMasInstance, + accountItemWithTypeIm, + TEST_ENABLE_SMS_MMS); int expectedMask = 1; mParams.setFilterMessageType(expectedMask); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java index 64408e89f95..55dbf1a9bf0 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java @@ -40,8 +40,7 @@ public class BluetoothMapServiceBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private BluetoothMapService mService; + @Mock private BluetoothMapService mService; BluetoothDevice mRemoteDevice; diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java index 009d79d494a..a78264d67c5 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java @@ -100,8 +100,10 @@ public class BluetoothMapServiceTest { public void getDevicesMatchingConnectionStates_whenNoDeviceIsConnected_returnsEmptyList() { when(mAdapterService.getBondedDevices()).thenReturn(new BluetoothDevice[] {mRemoteDevice}); - assertThat(mService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})).isEmpty(); + assertThat( + mService.getDevicesMatchingConnectionStates( + new int[] {BluetoothProfile.STATE_CONNECTED})) + .isEmpty(); } @Test @@ -118,8 +120,8 @@ public class BluetoothMapServiceTest { mService.sendConnectCancelMessage(); - verify(handler, timeout(1_000)).messageArrived( - eq(MSG_MAS_CONNECT_CANCEL), anyInt(), anyInt(), any()); + verify(handler, timeout(1_000)) + .messageArrived(eq(MSG_MAS_CONNECT_CANCEL), anyInt(), anyInt(), any()); } @Test @@ -129,8 +131,7 @@ public class BluetoothMapServiceTest { mService.sendConnectTimeoutMessage(); - verify(handler, timeout(1_000)).messageArrived( - eq(USER_TIMEOUT), anyInt(), anyInt(), any()); + verify(handler, timeout(1_000)).messageArrived(eq(USER_TIMEOUT), anyInt(), anyInt(), any()); } @Test @@ -141,8 +142,8 @@ public class BluetoothMapServiceTest { mService.updateMasInstances(action); - verify(handler, timeout(1_000)).messageArrived( - eq(UPDATE_MAS_INSTANCES), eq(action), anyInt(), any()); + verify(handler, timeout(1_000)) + .messageArrived(eq(UPDATE_MAS_INSTANCES), eq(action), anyInt(), any()); } public static class TestableHandler extends Handler { diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSettingsTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSettingsTest.java index f57f1bd0b32..940b59f9a8b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSettingsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSettingsTest.java @@ -92,14 +92,17 @@ public class BluetoothMapSettingsTest { } private void enableActivity(boolean enable) { - int enabledState = enable ? COMPONENT_ENABLED_STATE_ENABLED - : COMPONENT_ENABLED_STATE_DEFAULT; + int enabledState = + enable ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DEFAULT; - mTargetContext.getPackageManager().setApplicationEnabledSetting( - mTargetContext.getPackageName(), enabledState, DONT_KILL_APP); + mTargetContext + .getPackageManager() + .setApplicationEnabledSetting( + mTargetContext.getPackageName(), enabledState, DONT_KILL_APP); ComponentName activityName = new ComponentName(mTargetContext, BluetoothMapSettings.class); - mTargetContext.getPackageManager().setComponentEnabledSetting( - activityName, enabledState, DONT_KILL_APP); + mTargetContext + .getPackageManager() + .setComponentEnabledSetting(activityName, enabledState, DONT_KILL_APP); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSmsPduTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSmsPduTest.java index ab6f9cf4694..c85bb8b5b70 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSmsPduTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSmsPduTest.java @@ -61,22 +61,21 @@ public class BluetoothMapSmsPduTest { private SmsManager mSmsManager = SmsManager.getDefault(); @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private Context mTargetContext; - @Mock - private TelephonyManager mTelephonyManager; + @Mock private Context mTargetContext; + @Mock private TelephonyManager mTelephonyManager; @Before public void setUp() throws Exception { - when(mTargetContext.getSystemServiceName(TelephonyManager.class)).thenReturn( - "TELEPHONY_SERVICE"); + when(mTargetContext.getSystemServiceName(TelephonyManager.class)) + .thenReturn("TELEPHONY_SERVICE"); when(mTargetContext.getSystemService("TELEPHONY_SERVICE")).thenReturn(mTelephonyManager); int[] ted = SmsMessage.calculateLength((CharSequence) TEST_TEXT, false); TEST_ENCODING = ted[3]; TEST_LANGUAGE_TABLE = ted[4]; - TEST_DATA = SmsMessage.getSubmitPdu(null, TEST_DESTINATION_ADDRESS, TEST_TEXT, - false).encodedMessage; + TEST_DATA = + SmsMessage.getSubmitPdu(null, TEST_DESTINATION_ADDRESS, TEST_TEXT, false) + .encodedMessage; } @Test @@ -108,8 +107,9 @@ public class BluetoothMapSmsPduTest { Assume.assumeTrue(mSmsManager.isImsSmsSupported()); when(mTelephonyManager.getCurrentPhoneType()).thenReturn(TelephonyManager.PHONE_TYPE_GSM); - ArrayList pdus = BluetoothMapSmsPdu.getSubmitPdus(mTargetContext, - TEST_TEXT_WITH_TWO_SMS_PARTS, null); + ArrayList pdus = + BluetoothMapSmsPdu.getSubmitPdus( + mTargetContext, TEST_TEXT_WITH_TWO_SMS_PARTS, null); assertThat(pdus.size()).isEqualTo(2); assertThat(pdus.get(0).getType()).isEqualTo(BluetoothMapSmsPdu.SMS_TYPE_GSM); @@ -122,8 +122,8 @@ public class BluetoothMapSmsPduTest { byte[] encodedMessageSms = messageSmsToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageSms); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_NATIVE); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_NATIVE); assertThat(messageParsed).isInstanceOf(BluetoothMapbMessageSms.class); BluetoothMapbMessageSms messageSmsParsed = (BluetoothMapbMessageSms) messageParsed; @@ -149,8 +149,8 @@ public class BluetoothMapSmsPduTest { byte[] encodedMessageSms = messageSmsToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageSms); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_NATIVE); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_NATIVE); assertThat(messageParsed).isInstanceOf(BluetoothMapbMessageSms.class); } @@ -161,8 +161,9 @@ public class BluetoothMapSmsPduTest { Assume.assumeTrue(mSmsManager.isImsSmsSupported()); when(mTelephonyManager.getCurrentPhoneType()).thenReturn(TelephonyManager.PHONE_TYPE_GSM); - ArrayList pdus = BluetoothMapSmsPdu.getDeliverPdus(mTargetContext, TEST_TEXT, - TEST_DESTINATION_ADDRESS, TEST_DATE); + ArrayList pdus = + BluetoothMapSmsPdu.getDeliverPdus( + mTargetContext, TEST_TEXT, TEST_DESTINATION_ADDRESS, TEST_DATE); assertThat(pdus.size()).isEqualTo(1); assertThat(pdus.get(0).getType()).isEqualTo(BluetoothMapSmsPdu.SMS_TYPE_GSM); @@ -176,8 +177,11 @@ public class BluetoothMapSmsPduTest { byte[] encodedMessageSms = messageSmsToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageSms); - assertThrows(IllegalArgumentException.class, () -> BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_NATIVE)); + assertThrows( + IllegalArgumentException.class, + () -> + BluetoothMapbMessage.parse( + inputStream, BluetoothMapAppParams.CHARSET_NATIVE)); } @Test @@ -186,8 +190,9 @@ public class BluetoothMapSmsPduTest { Assume.assumeTrue(mSmsManager.isImsSmsSupported()); when(mTelephonyManager.getCurrentPhoneType()).thenReturn(TelephonyManager.PHONE_TYPE_CDMA); - ArrayList pdus = BluetoothMapSmsPdu.getDeliverPdus(mTargetContext, TEST_TEXT, - TEST_DESTINATION_ADDRESS, TEST_DATE); + ArrayList pdus = + BluetoothMapSmsPdu.getDeliverPdus( + mTargetContext, TEST_TEXT, TEST_DESTINATION_ADDRESS, TEST_DATE); assertThat(pdus.size()).isEqualTo(1); assertThat(pdus.get(0).getType()).isEqualTo(BluetoothMapSmsPdu.SMS_TYPE_CDMA); @@ -201,50 +206,66 @@ public class BluetoothMapSmsPduTest { byte[] encodedMessageSms = messageSmsToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageSms); - assertThrows(IllegalArgumentException.class, () -> BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_NATIVE)); + assertThrows( + IllegalArgumentException.class, + () -> + BluetoothMapbMessage.parse( + inputStream, BluetoothMapAppParams.CHARSET_NATIVE)); } @Test public void getEncodingString() { - SmsPdu smsPduGsm7bitWithLanguageTableZero = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_7BIT, - BluetoothMapSmsPdu.SMS_TYPE_GSM, 0); + SmsPdu smsPduGsm7bitWithLanguageTableZero = + new SmsPdu(TEST_DATA, SmsMessage.ENCODING_7BIT, BluetoothMapSmsPdu.SMS_TYPE_GSM, 0); assertThat(smsPduGsm7bitWithLanguageTableZero.getEncodingString()).isEqualTo("G-7BIT"); - SmsPdu smsPduGsm7bitWithLanguageTableOne = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_7BIT, - BluetoothMapSmsPdu.SMS_TYPE_GSM, 1); + SmsPdu smsPduGsm7bitWithLanguageTableOne = + new SmsPdu(TEST_DATA, SmsMessage.ENCODING_7BIT, BluetoothMapSmsPdu.SMS_TYPE_GSM, 1); assertThat(smsPduGsm7bitWithLanguageTableOne.getEncodingString()).isEqualTo("G-7BITEXT"); - SmsPdu smsPduGsm8bit = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_8BIT, - BluetoothMapSmsPdu.SMS_TYPE_GSM, 0); + SmsPdu smsPduGsm8bit = + new SmsPdu(TEST_DATA, SmsMessage.ENCODING_8BIT, BluetoothMapSmsPdu.SMS_TYPE_GSM, 0); assertThat(smsPduGsm8bit.getEncodingString()).isEqualTo("G-8BIT"); - SmsPdu smsPduGsm16bit = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_16BIT, - BluetoothMapSmsPdu.SMS_TYPE_GSM, 0); + SmsPdu smsPduGsm16bit = + new SmsPdu( + TEST_DATA, SmsMessage.ENCODING_16BIT, BluetoothMapSmsPdu.SMS_TYPE_GSM, 0); assertThat(smsPduGsm16bit.getEncodingString()).isEqualTo("G-16BIT"); - SmsPdu smsPduGsmUnknown = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_UNKNOWN, - BluetoothMapSmsPdu.SMS_TYPE_GSM, 0); + SmsPdu smsPduGsmUnknown = + new SmsPdu( + TEST_DATA, SmsMessage.ENCODING_UNKNOWN, BluetoothMapSmsPdu.SMS_TYPE_GSM, 0); assertThat(smsPduGsmUnknown.getEncodingString()).isEqualTo(""); - SmsPdu smsPduCdma7bit = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_7BIT, - BluetoothMapSmsPdu.SMS_TYPE_CDMA, 0); + SmsPdu smsPduCdma7bit = + new SmsPdu( + TEST_DATA, SmsMessage.ENCODING_7BIT, BluetoothMapSmsPdu.SMS_TYPE_CDMA, 0); assertThat(smsPduCdma7bit.getEncodingString()).isEqualTo("C-7ASCII"); - SmsPdu smsPduCdma8bit = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_8BIT, - BluetoothMapSmsPdu.SMS_TYPE_CDMA, 0); + SmsPdu smsPduCdma8bit = + new SmsPdu( + TEST_DATA, SmsMessage.ENCODING_8BIT, BluetoothMapSmsPdu.SMS_TYPE_CDMA, 0); assertThat(smsPduCdma8bit.getEncodingString()).isEqualTo("C-8BIT"); - SmsPdu smsPduCdma16bit = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_16BIT, - BluetoothMapSmsPdu.SMS_TYPE_CDMA, 0); + SmsPdu smsPduCdma16bit = + new SmsPdu( + TEST_DATA, SmsMessage.ENCODING_16BIT, BluetoothMapSmsPdu.SMS_TYPE_CDMA, 0); assertThat(smsPduCdma16bit.getEncodingString()).isEqualTo("C-UNICODE"); - SmsPdu smsPduCdmaKsc5601 = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_KSC5601, - BluetoothMapSmsPdu.SMS_TYPE_CDMA, 0); + SmsPdu smsPduCdmaKsc5601 = + new SmsPdu( + TEST_DATA, + SmsMessage.ENCODING_KSC5601, + BluetoothMapSmsPdu.SMS_TYPE_CDMA, + 0); assertThat(smsPduCdmaKsc5601.getEncodingString()).isEqualTo("C-KOREAN"); - SmsPdu smsPduCdmaUnknown = new SmsPdu(TEST_DATA, SmsMessage.ENCODING_UNKNOWN, - BluetoothMapSmsPdu.SMS_TYPE_CDMA, 0); + SmsPdu smsPduCdmaUnknown = + new SmsPdu( + TEST_DATA, + SmsMessage.ENCODING_UNKNOWN, + BluetoothMapSmsPdu.SMS_TYPE_CDMA, + 0); assertThat(smsPduCdmaUnknown.getEncodingString()).isEqualTo(""); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapUtilsTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapUtilsTest.java index cf1fb755775..7bc752db8ab 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapUtilsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapUtilsTest.java @@ -57,8 +57,9 @@ public class BluetoothMapUtilsTest { @Test public void printCursor_doesNotCrash() { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.PresenceColumns.LAST_ONLINE, "Name"}); + MatrixCursor cursor = + new MatrixCursor( + new String[] {BluetoothMapContract.PresenceColumns.LAST_ONLINE, "Name"}); cursor.addRow(new Object[] {345345226L, "test_name"}); cursor.moveToFirst(); @@ -67,8 +68,10 @@ public class BluetoothMapUtilsTest { @Test public void stripEncoding_quotedPrintable() { - assertThat(BluetoothMapUtils.stripEncoding("=?UTF-8?Q?" + QUOTED_PRINTABLE_ENCODED_TEXT - + "?=")).isEqualTo(TEXT); + assertThat( + BluetoothMapUtils.stripEncoding( + "=?UTF-8?Q?" + QUOTED_PRINTABLE_ENCODED_TEXT + "?=")) + .isEqualTo(TEXT); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageEmailTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageEmailTest.java index e2a5cb4ffe6..2dab97af354 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageEmailTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageEmailTest.java @@ -52,8 +52,8 @@ public class BluetoothMapbMessageEmailTest { byte[] encodedMessageEmail = messageEmailToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageEmail); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_UTF8); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_UTF8); assertThat(messageParsed).isInstanceOf(BluetoothMapbMessageEmail.class); BluetoothMapbMessageEmail messageEmailParsed = (BluetoothMapbMessageEmail) messageParsed; assertThat(messageEmailParsed.getEmailBody()).isEqualTo(TEST_EMAIL_BODY); @@ -69,10 +69,10 @@ public class BluetoothMapbMessageEmailTest { byte[] encodedMessageEmail = messageEmailToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageEmail); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_UTF8); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_UTF8); assertThat(messageParsed).isInstanceOf(BluetoothMapbMessageEmail.class); BluetoothMapbMessageEmail messageEmailParsed = (BluetoothMapbMessageEmail) messageParsed; assertThat(messageEmailParsed.getEmailBody()).isEqualTo(""); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageMimeTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageMimeTest.java index ac2d9804a6a..8e88a123ea3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageMimeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageMimeTest.java @@ -45,22 +45,23 @@ public class BluetoothMapbMessageMimeTest { private static final boolean TEST_TEXT_ONLY = true; private static final boolean TEST_INCLUDE_ATTACHMENTS = true; - private final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", - Locale.US); + private final SimpleDateFormat format = + new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); private final Date date = new Date(TEST_DATE); - private final ArrayList TEST_FROM = new ArrayList<>( - Arrays.asList(new Rfc822Token("from_name", "from_address", null))); - private final ArrayList TEST_SENDER = new ArrayList<>( - Arrays.asList(new Rfc822Token("sender_name", "sender_address", null))); - private static final ArrayList TEST_TO = new ArrayList<>( - Arrays.asList(new Rfc822Token("to_name", "to_address", null))); - private static final ArrayList TEST_CC = new ArrayList<>( - Arrays.asList(new Rfc822Token("cc_name", "cc_address", null))); - private final ArrayList TEST_BCC = new ArrayList<>( - Arrays.asList(new Rfc822Token("bcc_name", "bcc_address", null))); - private final ArrayList TEST_REPLY_TO = new ArrayList<>( - Arrays.asList(new Rfc822Token("reply_to_name", "reply_to_address", null))); + private final ArrayList TEST_FROM = + new ArrayList<>(Arrays.asList(new Rfc822Token("from_name", "from_address", null))); + private final ArrayList TEST_SENDER = + new ArrayList<>(Arrays.asList(new Rfc822Token("sender_name", "sender_address", null))); + private static final ArrayList TEST_TO = + new ArrayList<>(Arrays.asList(new Rfc822Token("to_name", "to_address", null))); + private static final ArrayList TEST_CC = + new ArrayList<>(Arrays.asList(new Rfc822Token("cc_name", "cc_address", null))); + private final ArrayList TEST_BCC = + new ArrayList<>(Arrays.asList(new Rfc822Token("bcc_name", "bcc_address", null))); + private final ArrayList TEST_REPLY_TO = + new ArrayList<>( + Arrays.asList(new Rfc822Token("reply_to_name", "reply_to_address", null))); private BluetoothMapbMessageMime mMime; @@ -113,7 +114,7 @@ public class BluetoothMapbMessageMimeTest { @Test public void testUpdateCharset() { - mMime.getMimeParts().get(0).mContentType = TEST_CONTENT_TYPE/*="text/plain*/; + mMime.getMimeParts().get(0).mContentType = TEST_CONTENT_TYPE /*="text/plain*/; mMime.updateCharset(); assertThat(mMime.mCharset).isEqualTo("UTF-8"); } @@ -133,8 +134,8 @@ public class BluetoothMapbMessageMimeTest { final String nameToAdd = "name_to_add"; final String addressToAdd = "address_to_add"; mime.addSender(nameToAdd, addressToAdd); - assertThat(mime.getSender().get(0)).isEqualTo( - new Rfc822Token(nameToAdd, addressToAdd, null)); + assertThat(mime.getSender().get(0)) + .isEqualTo(new Rfc822Token(nameToAdd, addressToAdd, null)); } @Test @@ -170,8 +171,8 @@ public class BluetoothMapbMessageMimeTest { final String nameToAdd = "name_to_add"; final String addressToAdd = "address_to_add"; mime.addReplyTo(nameToAdd, addressToAdd); - assertThat(mime.getReplyTo().get(0)).isEqualTo( - new Rfc822Token(nameToAdd, addressToAdd, null)); + assertThat(mime.getReplyTo().get(0)) + .isEqualTo(new Rfc822Token(nameToAdd, addressToAdd, null)); } @Test @@ -187,30 +188,30 @@ public class BluetoothMapbMessageMimeTest { assertThat(mimeToCreateByParsing.getMessageId()).isEqualTo(TEST_MESSAGE_ID); assertThat(mimeToCreateByParsing.getContentType()).isEqualTo(TEST_CONTENT_TYPE); - assertThat(mimeToCreateByParsing.getFrom().get(0).getName()).isEqualTo( - TEST_FROM.get(0).getName()); - assertThat(mimeToCreateByParsing.getFrom().get(0).getAddress()).isEqualTo( - TEST_FROM.get(0).getAddress()); - - assertThat(mimeToCreateByParsing.getTo().get(0).getName()).isEqualTo( - TEST_TO.get(0).getName()); - assertThat(mimeToCreateByParsing.getTo().get(0).getAddress()).isEqualTo( - TEST_TO.get(0).getAddress()); - - assertThat(mimeToCreateByParsing.getCc().get(0).getName()).isEqualTo( - TEST_CC.get(0).getName()); - assertThat(mimeToCreateByParsing.getCc().get(0).getAddress()).isEqualTo( - TEST_CC.get(0).getAddress()); - - assertThat(mimeToCreateByParsing.getBcc().get(0).getName()).isEqualTo( - TEST_BCC.get(0).getName()); - assertThat(mimeToCreateByParsing.getBcc().get(0).getAddress()).isEqualTo( - TEST_BCC.get(0).getAddress()); - - assertThat(mimeToCreateByParsing.getReplyTo().get(0).getName()).isEqualTo( - TEST_REPLY_TO.get(0).getName()); - assertThat(mimeToCreateByParsing.getReplyTo().get(0).getAddress()).isEqualTo( - TEST_REPLY_TO.get(0).getAddress()); + assertThat(mimeToCreateByParsing.getFrom().get(0).getName()) + .isEqualTo(TEST_FROM.get(0).getName()); + assertThat(mimeToCreateByParsing.getFrom().get(0).getAddress()) + .isEqualTo(TEST_FROM.get(0).getAddress()); + + assertThat(mimeToCreateByParsing.getTo().get(0).getName()) + .isEqualTo(TEST_TO.get(0).getName()); + assertThat(mimeToCreateByParsing.getTo().get(0).getAddress()) + .isEqualTo(TEST_TO.get(0).getAddress()); + + assertThat(mimeToCreateByParsing.getCc().get(0).getName()) + .isEqualTo(TEST_CC.get(0).getName()); + assertThat(mimeToCreateByParsing.getCc().get(0).getAddress()) + .isEqualTo(TEST_CC.get(0).getAddress()); + + assertThat(mimeToCreateByParsing.getBcc().get(0).getName()) + .isEqualTo(TEST_BCC.get(0).getName()); + assertThat(mimeToCreateByParsing.getBcc().get(0).getAddress()) + .isEqualTo(TEST_BCC.get(0).getAddress()); + + assertThat(mimeToCreateByParsing.getReplyTo().get(0).getName()) + .isEqualTo(TEST_REPLY_TO.get(0).getName()); + assertThat(mimeToCreateByParsing.getReplyTo().get(0).getAddress()) + .isEqualTo(TEST_REPLY_TO.get(0).getAddress()); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageSmsTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageSmsTest.java index 7a9efe8fa0b..e1e8c20cc12 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageSmsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageSmsTest.java @@ -52,8 +52,8 @@ public class BluetoothMapbMessageSmsTest { // Do not run test if sms is not supported Assume.assumeTrue(mSmsManager.isImsSmsSupported()); mTargetContext = InstrumentationRegistry.getTargetContext(); - TEST_SMS_BODY_PDUS = BluetoothMapSmsPdu.getSubmitPdus(mTargetContext, TEST_MESSAGE, - TEST_ADDRESS); + TEST_SMS_BODY_PDUS = + BluetoothMapSmsPdu.getSubmitPdus(mTargetContext, TEST_MESSAGE, TEST_ADDRESS); } @Test @@ -84,8 +84,8 @@ public class BluetoothMapbMessageSmsTest { byte[] encodedMessageSms = messageSmsToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageSms); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_NATIVE); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_NATIVE); assertThat(messageParsed).isInstanceOf(BluetoothMapbMessageSms.class); BluetoothMapbMessageSms messageSmsParsed = (BluetoothMapbMessageSms) messageParsed; assertThat(messageSmsParsed.getSmsBody()).isEqualTo(TEST_MESSAGE); @@ -101,10 +101,10 @@ public class BluetoothMapbMessageSmsTest { byte[] encodedMessageSms = messageSmsToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageSms); - BluetoothMapbMessage messageParsed = BluetoothMapbMessage.parse(inputStream, - BluetoothMapAppParams.CHARSET_UTF8); + BluetoothMapbMessage messageParsed = + BluetoothMapbMessage.parse(inputStream, BluetoothMapAppParams.CHARSET_UTF8); assertThat(messageParsed).isInstanceOf(BluetoothMapbMessageSms.class); BluetoothMapbMessageSms messageSmsParsed = (BluetoothMapbMessageSms) messageParsed; assertThat(messageSmsParsed.getSmsBody()).isEqualTo(""); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageTest.java index 2bc0e1a5358..299e2d4f46e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageTest.java @@ -43,18 +43,18 @@ public class BluetoothMapbMessageTest { private static final String TEST_FORMATTED_NAME = "test_formatted_name"; private static final String TEST_FIRST_PHONE_NUMBER = "111-1111-1111"; private static final String[] TEST_PHONE_NUMBERS = - new String[]{TEST_FIRST_PHONE_NUMBER, "222-2222-2222"}; + new String[] {TEST_FIRST_PHONE_NUMBER, "222-2222-2222"}; private static final String TEST_FIRST_EMAIL = "testFirst@email.com"; private static final String[] TEST_EMAIL_ADDRESSES = - new String[]{TEST_FIRST_EMAIL, "testSecond@email.com"}; + new String[] {TEST_FIRST_EMAIL, "testSecond@email.com"}; private static final String TEST_FIRST_BT_UCI = "test_first_bt_uci"; private static final String[] TEST_BT_UCIS = - new String[]{TEST_FIRST_BT_UCI, "test_second_bt_uci"}; + new String[] {TEST_FIRST_BT_UCI, "test_second_bt_uci"}; private static final String TEST_FIRST_BT_UID = "1111"; - private static final String[] TEST_BT_UIDS = new String[]{TEST_FIRST_BT_UID, "1112"}; + private static final String[] TEST_BT_UIDS = new String[] {TEST_FIRST_BT_UID, "1112"}; - private static final VCard TEST_VCARD = new VCard(TEST_NAME, TEST_PHONE_NUMBERS, - TEST_EMAIL_ADDRESSES); + private static final VCard TEST_VCARD = + new VCard(TEST_NAME, TEST_PHONE_NUMBERS, TEST_EMAIL_ADDRESSES); @Test public void settersAndGetters() { @@ -85,8 +85,8 @@ public class BluetoothMapbMessageTest { BluetoothMapbMessage messageMime = new BluetoothMapbMessageMime(); messageMime.addOriginator(TEST_NAME, TEST_PHONE_NUMBERS, TEST_EMAIL_ADDRESSES); assertThat(messageMime.getOriginators().get(0).getName()).isEqualTo(TEST_NAME); - assertThat(messageMime.getOriginators().get(0).getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(messageMime.getOriginators().get(0).getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(messageMime.getOriginators().get(0).getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); } @@ -100,22 +100,27 @@ public class BluetoothMapbMessageTest { @Test public void addOriginator_forVCardVersionThree() { BluetoothMapbMessage messageMime = new BluetoothMapbMessageMime(); - messageMime.addOriginator(TEST_NAME, TEST_FORMATTED_NAME, TEST_PHONE_NUMBERS, - TEST_EMAIL_ADDRESSES, TEST_BT_UIDS, TEST_BT_UCIS); + messageMime.addOriginator( + TEST_NAME, + TEST_FORMATTED_NAME, + TEST_PHONE_NUMBERS, + TEST_EMAIL_ADDRESSES, + TEST_BT_UIDS, + TEST_BT_UCIS); assertThat(messageMime.getOriginators().get(0).getName()).isEqualTo(TEST_NAME); - assertThat(messageMime.getOriginators().get(0).getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(messageMime.getOriginators().get(0).getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(messageMime.getOriginators().get(0).getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); - assertThat(messageMime.getOriginators().get(0).getFirstBtUci()).isEqualTo( - TEST_FIRST_BT_UCI); + assertThat(messageMime.getOriginators().get(0).getFirstBtUci()) + .isEqualTo(TEST_FIRST_BT_UCI); } @Test public void addOriginator_forVCardVersionThree_withOnlyBtUcisAndBtUids() { BluetoothMapbMessage messageMime = new BluetoothMapbMessageMime(); messageMime.addOriginator(TEST_BT_UCIS, TEST_BT_UIDS); - assertThat(messageMime.getOriginators().get(0).getFirstBtUci()).isEqualTo( - TEST_FIRST_BT_UCI); + assertThat(messageMime.getOriginators().get(0).getFirstBtUci()) + .isEqualTo(TEST_FIRST_BT_UCI); } @Test @@ -123,19 +128,24 @@ public class BluetoothMapbMessageTest { BluetoothMapbMessage messageMime = new BluetoothMapbMessageMime(); messageMime.addRecipient(TEST_NAME, TEST_PHONE_NUMBERS, TEST_EMAIL_ADDRESSES); assertThat(messageMime.getRecipients().get(0).getName()).isEqualTo(TEST_NAME); - assertThat(messageMime.getRecipients().get(0).getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(messageMime.getRecipients().get(0).getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(messageMime.getRecipients().get(0).getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); } @Test public void addRecipient_forVCardVersionThree() { BluetoothMapbMessage messageMime = new BluetoothMapbMessageMime(); - messageMime.addRecipient(TEST_NAME, TEST_FORMATTED_NAME, TEST_PHONE_NUMBERS, - TEST_EMAIL_ADDRESSES, TEST_BT_UIDS, TEST_BT_UCIS); + messageMime.addRecipient( + TEST_NAME, + TEST_FORMATTED_NAME, + TEST_PHONE_NUMBERS, + TEST_EMAIL_ADDRESSES, + TEST_BT_UIDS, + TEST_BT_UCIS); assertThat(messageMime.getRecipients().get(0).getName()).isEqualTo(TEST_NAME); - assertThat(messageMime.getRecipients().get(0).getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(messageMime.getRecipients().get(0).getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(messageMime.getRecipients().get(0).getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); assertThat(messageMime.getRecipients().get(0).getFirstBtUci()).isEqualTo(TEST_FIRST_BT_UCI); } @@ -155,21 +165,31 @@ public class BluetoothMapbMessageTest { messageMimeToEncode.setType(TEST_TYPE); messageMimeToEncode.setCompleteFolder(TEST_FOLDER); messageMimeToEncode.setEncoding(TEST_ENCODING); - messageMimeToEncode.addOriginator(TEST_NAME, TEST_FORMATTED_NAME, TEST_PHONE_NUMBERS, - TEST_EMAIL_ADDRESSES, TEST_BT_UIDS, TEST_BT_UCIS); - messageMimeToEncode.addRecipient(TEST_NAME, TEST_FORMATTED_NAME, TEST_PHONE_NUMBERS, - TEST_EMAIL_ADDRESSES, TEST_BT_UIDS, TEST_BT_UCIS); + messageMimeToEncode.addOriginator( + TEST_NAME, + TEST_FORMATTED_NAME, + TEST_PHONE_NUMBERS, + TEST_EMAIL_ADDRESSES, + TEST_BT_UIDS, + TEST_BT_UCIS); + messageMimeToEncode.addRecipient( + TEST_NAME, + TEST_FORMATTED_NAME, + TEST_PHONE_NUMBERS, + TEST_EMAIL_ADDRESSES, + TEST_BT_UIDS, + TEST_BT_UCIS); byte[] encodedMessageMime = messageMimeToEncode.encode(); InputStream inputStream = new ByteArrayInputStream(encodedMessageMime); BluetoothMapbMessage messageMimeParsed = BluetoothMapbMessage.parse(inputStream, 1); assertThat(messageMimeParsed.mAppParamCharset).isEqualTo(1); - assertThat(messageMimeParsed.getVersionString()).isEqualTo( - "VERSION:" + TEST_VERSION_STRING); + assertThat(messageMimeParsed.getVersionString()) + .isEqualTo("VERSION:" + TEST_VERSION_STRING); assertThat(messageMimeParsed.getType()).isEqualTo(TEST_TYPE); assertThat(messageMimeParsed.getFolder()).isEqualTo(TEST_FOLDER); assertThat(messageMimeParsed.getRecipients().size()).isEqualTo(1); assertThat(messageMimeParsed.getOriginators().size()).isEqualTo(1); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageVCardTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageVCardTest.java index 8f108f57d21..a44bd9cfda4 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageVCardTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageVCardTest.java @@ -37,55 +37,66 @@ public class BluetoothMapbMessageVCardTest { private static final String TEST_FORMATTED_NAME = "test_formatted_name"; private static final String TEST_FIRST_PHONE_NUMBER = "111-1111-1111"; private static final String[] TEST_PHONE_NUMBERS = - new String[]{TEST_FIRST_PHONE_NUMBER, "222-2222-2222"}; + new String[] {TEST_FIRST_PHONE_NUMBER, "222-2222-2222"}; private static final String TEST_FIRST_EMAIL = "testFirst@email.com"; private static final String[] TEST_EMAIL_ADDRESSES = - new String[]{TEST_FIRST_EMAIL, "testSecond@email.com"}; + new String[] {TEST_FIRST_EMAIL, "testSecond@email.com"}; private static final String TEST_FIRST_BT_UCI = "test_first_bt_uci"; private static final String[] TEST_BT_UCIS = - new String[]{TEST_FIRST_BT_UCI, "test_second_bt_uci"}; + new String[] {TEST_FIRST_BT_UCI, "test_second_bt_uci"}; private static final String TEST_FIRST_BT_UID = "1111"; - private static final String[] TEST_BT_UIDS = new String[]{TEST_FIRST_BT_UID, "1112"}; + private static final String[] TEST_BT_UIDS = new String[] {TEST_FIRST_BT_UID, "1112"}; private static final int TEST_ENV_LEVEL = 1; @Test public void constructor_forVersionTwoPointOne() { VCard vcard = new VCard(TEST_NAME, TEST_PHONE_NUMBERS, TEST_EMAIL_ADDRESSES); assertThat(vcard.getName()).isEqualTo(TEST_NAME); - assertThat(vcard.getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(vcard.getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(vcard.getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); } @Test public void constructor_forVersionTwoPointOne_withEnvLevel() { - VCard vcard = new VCard(TEST_NAME, TEST_PHONE_NUMBERS, TEST_EMAIL_ADDRESSES, - TEST_ENV_LEVEL); + VCard vcard = + new VCard(TEST_NAME, TEST_PHONE_NUMBERS, TEST_EMAIL_ADDRESSES, TEST_ENV_LEVEL); assertThat(vcard.getName()).isEqualTo(TEST_NAME); - assertThat(vcard.getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(vcard.getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(vcard.getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); assertThat(vcard.getEnvLevel()).isEqualTo(TEST_ENV_LEVEL); } @Test public void constructor_forVersionThree() { - VCard vcard = new VCard(TEST_NAME, TEST_FORMATTED_NAME, TEST_PHONE_NUMBERS, - TEST_EMAIL_ADDRESSES, TEST_ENV_LEVEL); + VCard vcard = + new VCard( + TEST_NAME, + TEST_FORMATTED_NAME, + TEST_PHONE_NUMBERS, + TEST_EMAIL_ADDRESSES, + TEST_ENV_LEVEL); assertThat(vcard.getName()).isEqualTo(TEST_NAME); - assertThat(vcard.getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(vcard.getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(vcard.getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); assertThat(vcard.getEnvLevel()).isEqualTo(TEST_ENV_LEVEL); } @Test public void constructor_forVersionThree_withUcis() { - VCard vcard = new VCard(TEST_NAME, TEST_FORMATTED_NAME, TEST_PHONE_NUMBERS, - TEST_EMAIL_ADDRESSES, TEST_BT_UIDS, TEST_BT_UCIS); + VCard vcard = + new VCard( + TEST_NAME, + TEST_FORMATTED_NAME, + TEST_PHONE_NUMBERS, + TEST_EMAIL_ADDRESSES, + TEST_BT_UIDS, + TEST_BT_UCIS); assertThat(vcard.getName()).isEqualTo(TEST_NAME); - assertThat(vcard.getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(vcard.getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(vcard.getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); assertThat(vcard.getFirstBtUci()).isEqualTo(TEST_FIRST_BT_UCI); } @@ -102,8 +113,14 @@ public class BluetoothMapbMessageVCardTest { @Test public void encodeToStringBuilder_thenParseBackToVCard_returnsCorrectly() { - VCard vcardOriginal = new VCard(TEST_NAME, TEST_FORMATTED_NAME, TEST_PHONE_NUMBERS, - TEST_EMAIL_ADDRESSES, TEST_BT_UIDS, TEST_BT_UCIS); + VCard vcardOriginal = + new VCard( + TEST_NAME, + TEST_FORMATTED_NAME, + TEST_PHONE_NUMBERS, + TEST_EMAIL_ADDRESSES, + TEST_BT_UIDS, + TEST_BT_UCIS); StringBuilder stringBuilder = new StringBuilder(); vcardOriginal.encode(stringBuilder); InputStream inputStream = new ByteArrayInputStream(stringBuilder.toString().getBytes()); @@ -111,9 +128,9 @@ public class BluetoothMapbMessageVCardTest { VCard vcardParsed = VCard.parseVcard(new BMsgReader(inputStream), TEST_ENV_LEVEL); assertThat(vcardParsed.getName()).isEqualTo(TEST_NAME); - assertThat(vcardParsed.getFirstPhoneNumber()).isEqualTo( - PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); + assertThat(vcardParsed.getFirstPhoneNumber()) + .isEqualTo(PhoneNumberUtils.stripSeparators(TEST_FIRST_PHONE_NUMBER)); assertThat(vcardParsed.getFirstEmail()).isEqualTo(TEST_FIRST_EMAIL); assertThat(vcardParsed.getEnvLevel()).isEqualTo(TEST_ENV_LEVEL); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/ConvoContactInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/ConvoContactInfoTest.java index 8703e8e12a4..7be1a37d48c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/ConvoContactInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/ConvoContactInfoTest.java @@ -36,18 +36,21 @@ public class ConvoContactInfoTest { public void setConvoColumns() { BluetoothMapContentObserver.ConvoContactInfo info = new BluetoothMapContentObserver.ConvoContactInfo(); - MatrixCursor cursor = new MatrixCursor( - new String[]{BluetoothMapContract.ConvoContactColumns.CONVO_ID, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.CHAT_STATE, - BluetoothMapContract.ConvoContactColumns.UCI, - BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, - BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, - BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, - BluetoothMapContract.ConvoContactColumns.PRIORITY, - BluetoothMapContract.ConvoContactColumns.LAST_ONLINE}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.ConvoContactColumns.CONVO_ID, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.CHAT_STATE, + BluetoothMapContract.ConvoContactColumns.UCI, + BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, + BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, + BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, + BluetoothMapContract.ConvoContactColumns.PRIORITY, + BluetoothMapContract.ConvoContactColumns.LAST_ONLINE + }); info.setConvoColunms(cursor); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/EventTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/EventTest.java index 12bb4386c2b..4ba945ead9e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/EventTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/EventTest.java @@ -68,9 +68,8 @@ public class EventTest { } Context mockContext = mock(Context.class); MockContentResolver mockResolver = new MockContentResolver(); - BluetoothMapContentObserverTest.ExceptionTestProvider - mockProvider = new BluetoothMapContentObserverTest.ExceptionTestProvider( - mockContext); + BluetoothMapContentObserverTest.ExceptionTestProvider mockProvider = + new BluetoothMapContentObserverTest.ExceptionTestProvider(mockContext); mockResolver.addProvider("sms", mockProvider); TelephonyManager mockTelephony = mock(TelephonyManager.class); @@ -90,8 +89,8 @@ public class EventTest { @Test public void constructor() { - BluetoothMapContentObserver.Event event = mObserver.new Event(TEST_EVENT_TYPE, TEST_HANDLE, - TEST_FOLDER, TEST_TYPE); + BluetoothMapContentObserver.Event event = + mObserver.new Event(TEST_EVENT_TYPE, TEST_HANDLE, TEST_FOLDER, TEST_TYPE); assertThat(event.eventType).isEqualTo(TEST_EVENT_TYPE); assertThat(event.handle).isEqualTo(TEST_HANDLE); @@ -100,8 +99,8 @@ public class EventTest { @Test public void constructor_withNullOldFolder() { - BluetoothMapContentObserver.Event event = mObserver.new Event(TEST_EVENT_TYPE, TEST_HANDLE, - TEST_FOLDER, null, TEST_TYPE); + BluetoothMapContentObserver.Event event = + mObserver.new Event(TEST_EVENT_TYPE, TEST_HANDLE, TEST_FOLDER, null, TEST_TYPE); assertThat(event.eventType).isEqualTo(TEST_EVENT_TYPE); assertThat(event.handle).isEqualTo(TEST_HANDLE); @@ -111,8 +110,9 @@ public class EventTest { @Test public void constructor_withNonNullOldFolder() { - BluetoothMapContentObserver.Event event = mObserver.new Event(TEST_EVENT_TYPE, TEST_HANDLE, - TEST_FOLDER, TEST_OLD_FOLDER, TEST_TYPE); + BluetoothMapContentObserver.Event event = + mObserver + .new Event(TEST_EVENT_TYPE, TEST_HANDLE, TEST_FOLDER, TEST_OLD_FOLDER, TEST_TYPE); assertThat(event.eventType).isEqualTo(TEST_EVENT_TYPE); assertThat(event.handle).isEqualTo(TEST_HANDLE); @@ -122,44 +122,73 @@ public class EventTest { @Test public void constructor_forExtendedEventTypeOnePointOne() { - BluetoothMapContentObserver.Event event = mObserver.new Event(TEST_EVENT_TYPE, TEST_HANDLE, - TEST_FOLDER, TEST_TYPE, TEST_DATETIME, TEST_SUBJECT, TEST_SENDER_NAME, - TEST_PRIORITY); + BluetoothMapContentObserver.Event event = + mObserver + .new Event( + TEST_EVENT_TYPE, + TEST_HANDLE, + TEST_FOLDER, + TEST_TYPE, + TEST_DATETIME, + TEST_SUBJECT, + TEST_SENDER_NAME, + TEST_PRIORITY); assertThat(event.eventType).isEqualTo(TEST_EVENT_TYPE); assertThat(event.handle).isEqualTo(TEST_HANDLE); assertThat(event.msgType).isEqualTo(TEST_TYPE); assertThat(event.datetime).isEqualTo(TEST_DATETIME); assertThat(event.subject).isEqualTo(BluetoothMapUtils.stripInvalidChars(TEST_SUBJECT)); - assertThat(event.senderName).isEqualTo( - BluetoothMapUtils.stripInvalidChars(TEST_SENDER_NAME)); + assertThat(event.senderName) + .isEqualTo(BluetoothMapUtils.stripInvalidChars(TEST_SENDER_NAME)); assertThat(event.priority).isEqualTo(TEST_PRIORITY); } @Test public void constructor_forExtendedEventTypeOnePointTwo_withMessageEvents() { - BluetoothMapContentObserver.Event event = mObserver.new Event(TEST_EVENT_TYPE, TEST_HANDLE, - TEST_FOLDER, TEST_TYPE, TEST_DATETIME, TEST_SUBJECT, TEST_SENDER_NAME, - TEST_PRIORITY, TEST_CONVERSATION_ID, TEST_CONVERSATION_NAME); + BluetoothMapContentObserver.Event event = + mObserver + .new Event( + TEST_EVENT_TYPE, + TEST_HANDLE, + TEST_FOLDER, + TEST_TYPE, + TEST_DATETIME, + TEST_SUBJECT, + TEST_SENDER_NAME, + TEST_PRIORITY, + TEST_CONVERSATION_ID, + TEST_CONVERSATION_NAME); assertThat(event.eventType).isEqualTo(TEST_EVENT_TYPE); assertThat(event.handle).isEqualTo(TEST_HANDLE); assertThat(event.msgType).isEqualTo(TEST_TYPE); assertThat(event.datetime).isEqualTo(TEST_DATETIME); assertThat(event.subject).isEqualTo(BluetoothMapUtils.stripInvalidChars(TEST_SUBJECT)); - assertThat(event.senderName).isEqualTo( - BluetoothMapUtils.stripInvalidChars(TEST_SENDER_NAME)); + assertThat(event.senderName) + .isEqualTo(BluetoothMapUtils.stripInvalidChars(TEST_SENDER_NAME)); assertThat(event.priority).isEqualTo(TEST_PRIORITY); assertThat(event.conversationID).isEqualTo(TEST_CONVERSATION_ID); - assertThat(event.conversationName).isEqualTo( - BluetoothMapUtils.stripInvalidChars(TEST_CONVERSATION_NAME)); + assertThat(event.conversationName) + .isEqualTo(BluetoothMapUtils.stripInvalidChars(TEST_CONVERSATION_NAME)); } @Test public void constructor_forExtendedEventTypeOnePointTwo_withConversationEvents() { - BluetoothMapContentObserver.Event event = mObserver.new Event(TEST_EVENT_TYPE, TEST_UCI, - TEST_TYPE, TEST_NAME, TEST_PRIORITY, TEST_LAST_ACTIVITY, TEST_CONVERSATION_ID, - TEST_CONVERSATION_NAME, TEST_PRESENCE_STATE, TEST_PRESENCE_STATUS, TEST_CHAT_STATE); + BluetoothMapContentObserver.Event event = + mObserver + .new Event( + TEST_EVENT_TYPE, + TEST_UCI, + TEST_TYPE, + TEST_NAME, + TEST_PRIORITY, + TEST_LAST_ACTIVITY, + TEST_CONVERSATION_ID, + TEST_CONVERSATION_NAME, + TEST_PRESENCE_STATE, + TEST_PRESENCE_STATUS, + TEST_CHAT_STATE); assertThat(event.eventType).isEqualTo(TEST_EVENT_TYPE); assertThat(event.uci).isEqualTo(TEST_UCI); @@ -168,11 +197,11 @@ public class EventTest { assertThat(event.priority).isEqualTo(TEST_PRIORITY); assertThat(event.datetime).isEqualTo(TEST_LAST_ACTIVITY); assertThat(event.conversationID).isEqualTo(TEST_CONVERSATION_ID); - assertThat(event.conversationName).isEqualTo( - BluetoothMapUtils.stripInvalidChars(TEST_CONVERSATION_NAME)); + assertThat(event.conversationName) + .isEqualTo(BluetoothMapUtils.stripInvalidChars(TEST_CONVERSATION_NAME)); assertThat(event.presenceState).isEqualTo(TEST_PRESENCE_STATE); - assertThat(event.presenceStatus).isEqualTo( - BluetoothMapUtils.stripInvalidChars(TEST_PRESENCE_STATUS)); + assertThat(event.presenceStatus) + .isEqualTo(BluetoothMapUtils.stripInvalidChars(TEST_PRESENCE_STATUS)); assertThat(event.chatState).isEqualTo(TEST_CHAT_STATE); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/FilterInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/FilterInfoTest.java index 3c1a0c0c50e..bb713ae35c5 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/FilterInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/FilterInfoTest.java @@ -44,22 +44,25 @@ public class FilterInfoTest { @Test public void setMessageColumns() { - MatrixCursor cursor = new MatrixCursor(new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.DATE, - BluetoothMapContract.MessageColumns.SUBJECT, - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.FLAG_READ, - BluetoothMapContract.MessageColumns.MESSAGE_SIZE, - BluetoothMapContract.MessageColumns.FROM_LIST, - BluetoothMapContract.MessageColumns.TO_LIST, - BluetoothMapContract.MessageColumns.FLAG_ATTACHMENT, - BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, - BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, - BluetoothMapContract.MessageColumns.FLAG_PROTECTED, - BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.DEVILERY_STATE, - BluetoothMapContract.MessageColumns.THREAD_ID}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns._ID, + BluetoothMapContract.MessageColumns.DATE, + BluetoothMapContract.MessageColumns.SUBJECT, + BluetoothMapContract.MessageColumns.FOLDER_ID, + BluetoothMapContract.MessageColumns.FLAG_READ, + BluetoothMapContract.MessageColumns.MESSAGE_SIZE, + BluetoothMapContract.MessageColumns.FROM_LIST, + BluetoothMapContract.MessageColumns.TO_LIST, + BluetoothMapContract.MessageColumns.FLAG_ATTACHMENT, + BluetoothMapContract.MessageColumns.ATTACHMENT_SIZE, + BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, + BluetoothMapContract.MessageColumns.FLAG_PROTECTED, + BluetoothMapContract.MessageColumns.RECEPTION_STATE, + BluetoothMapContract.MessageColumns.DEVILERY_STATE, + BluetoothMapContract.MessageColumns.THREAD_ID + }); mFilterInfo.setMessageColumns(cursor); @@ -82,10 +85,13 @@ public class FilterInfoTest { @Test public void setEmailMessageColumns() { - MatrixCursor cursor = new MatrixCursor( - new String[] {BluetoothMapContract.MessageColumns.CC_LIST, - BluetoothMapContract.MessageColumns.BCC_LIST, - BluetoothMapContract.MessageColumns.REPLY_TO_LIST}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns.CC_LIST, + BluetoothMapContract.MessageColumns.BCC_LIST, + BluetoothMapContract.MessageColumns.REPLY_TO_LIST + }); mFilterInfo.setEmailMessageColumns(cursor); @@ -96,10 +102,13 @@ public class FilterInfoTest { @Test public void setImMessageColumns() { - MatrixCursor cursor = new MatrixCursor( - new String[] {BluetoothMapContract.MessageColumns.THREAD_NAME, - BluetoothMapContract.MessageColumns.ATTACHMENT_MINE_TYPES, - BluetoothMapContract.MessageColumns.BODY}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.MessageColumns.THREAD_NAME, + BluetoothMapContract.MessageColumns.ATTACHMENT_MINE_TYPES, + BluetoothMapContract.MessageColumns.BODY + }); mFilterInfo.setImMessageColumns(cursor); @@ -110,13 +119,16 @@ public class FilterInfoTest { @Test public void setEmailImConvoColumns() { - MatrixCursor cursor = new MatrixCursor( - new String[] {BluetoothMapContract.ConversationColumns.THREAD_ID, - BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY, - BluetoothMapContract.ConversationColumns.THREAD_NAME, - BluetoothMapContract.ConversationColumns.READ_STATUS, - BluetoothMapContract.ConversationColumns.VERSION_COUNTER, - BluetoothMapContract.ConversationColumns.SUMMARY}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.ConversationColumns.THREAD_ID, + BluetoothMapContract.ConversationColumns.LAST_THREAD_ACTIVITY, + BluetoothMapContract.ConversationColumns.THREAD_NAME, + BluetoothMapContract.ConversationColumns.READ_STATUS, + BluetoothMapContract.ConversationColumns.VERSION_COUNTER, + BluetoothMapContract.ConversationColumns.SUMMARY + }); mFilterInfo.setEmailImConvoColumns(cursor); @@ -130,16 +142,19 @@ public class FilterInfoTest { @Test public void setEmailImConvoContactColumns() { - MatrixCursor cursor = new MatrixCursor( - new String[] {BluetoothMapContract.ConvoContactColumns.X_BT_UID, - BluetoothMapContract.ConvoContactColumns.CHAT_STATE, - BluetoothMapContract.ConvoContactColumns.UCI, - BluetoothMapContract.ConvoContactColumns.NICKNAME, - BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, - BluetoothMapContract.ConvoContactColumns.NAME, - BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, - BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, - BluetoothMapContract.ConvoContactColumns.PRIORITY}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothMapContract.ConvoContactColumns.X_BT_UID, + BluetoothMapContract.ConvoContactColumns.CHAT_STATE, + BluetoothMapContract.ConvoContactColumns.UCI, + BluetoothMapContract.ConvoContactColumns.NICKNAME, + BluetoothMapContract.ConvoContactColumns.LAST_ACTIVE, + BluetoothMapContract.ConvoContactColumns.NAME, + BluetoothMapContract.ConvoContactColumns.PRESENCE_STATE, + BluetoothMapContract.ConvoContactColumns.STATUS_TEXT, + BluetoothMapContract.ConvoContactColumns.PRIORITY + }); mFilterInfo.setEmailImConvoContactColumns(cursor); @@ -156,8 +171,17 @@ public class FilterInfoTest { @Test public void setSmsColumns() { - MatrixCursor cursor = new MatrixCursor(new String[]{BaseColumns._ID, Sms.TYPE, Sms.READ, - Sms.BODY, Sms.ADDRESS, Sms.DATE, Sms.THREAD_ID}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BaseColumns._ID, + Sms.TYPE, + Sms.READ, + Sms.BODY, + Sms.ADDRESS, + Sms.DATE, + Sms.THREAD_ID + }); mFilterInfo.setSmsColumns(cursor); @@ -173,9 +197,18 @@ public class FilterInfoTest { @Test public void setMmsColumns() { - MatrixCursor cursor = new MatrixCursor( - new String[] {BaseColumns._ID, Mms.MESSAGE_BOX, Mms.READ, Mms.MESSAGE_SIZE, - Mms.TEXT_ONLY, Mms.DATE, Mms.SUBJECT, Mms.THREAD_ID}); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BaseColumns._ID, + Mms.MESSAGE_BOX, + Mms.READ, + Mms.MESSAGE_SIZE, + Mms.TEXT_ONLY, + Mms.DATE, + Mms.SUBJECT, + Mms.THREAD_ID + }); mFilterInfo.setMmsColumns(cursor); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/MapContactTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/MapContactTest.java index 9195ead8051..ce5ef8f05f5 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/MapContactTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/MapContactTest.java @@ -52,8 +52,8 @@ public class MapContactTest { public void getXBtUidString_withNonZeroId() { MapContact contact = MapContact.create(TEST_NON_ZERO_ID, TEST_NAME); - assertThat(contact.getXBtUidString()).isEqualTo( - BluetoothMapUtils.getLongLongAsString(TEST_NON_ZERO_ID, 0)); + assertThat(contact.getXBtUidString()) + .isEqualTo(BluetoothMapUtils.getLongLongAsString(TEST_NON_ZERO_ID, 0)); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java index 9e68fa69737..b47d0c465b3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java @@ -33,8 +33,8 @@ public class MsgTest { @Test public void constructor() { - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_ID, - TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); assertThat(msg.id).isEqualTo(TEST_ID); assertThat(msg.folderId).isEqualTo(TEST_FOLDER_ID); @@ -43,8 +43,8 @@ public class MsgTest { @Test public void hashCode_returnsExpectedResult() { - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_ID, - TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); int expected = 31 + (int) (TEST_ID ^ (TEST_ID >>> 32)); assertThat(msg.hashCode()).isEqualTo(expected); @@ -52,24 +52,24 @@ public class MsgTest { @Test public void equals_withSameInstance() { - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_ID, - TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); assertThat(msg.equals(msg)).isTrue(); } @Test public void equals_withNull() { - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_ID, - TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); assertThat(msg).isNotNull(); } @Test public void equals_withDifferentClass() { - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_ID, - TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); String msgOfDifferentClass = "msg_of_different_class"; assertThat(msg).isNotEqualTo(msgOfDifferentClass); @@ -79,20 +79,20 @@ public class MsgTest { public void equals_withDifferentId() { long idOne = 1; long idTwo = 2; - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(idOne, - TEST_FOLDER_ID, TEST_READ_FLAG); - BluetoothMapContentObserver.Msg msgWithDifferentId = new BluetoothMapContentObserver.Msg( - idTwo, TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg(idOne, TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msgWithDifferentId = + new BluetoothMapContentObserver.Msg(idTwo, TEST_FOLDER_ID, TEST_READ_FLAG); assertThat(msg).isNotEqualTo(msgWithDifferentId); } @Test public void equals_withEqualInstance() { - BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(TEST_ID, - TEST_FOLDER_ID, TEST_READ_FLAG); - BluetoothMapContentObserver.Msg msgWithSameId = new BluetoothMapContentObserver.Msg(TEST_ID, - TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msg = + new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msgWithSameId = + new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); assertThat(msg).isEqualTo(msgWithSameId); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/SmsMmsContactsTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/SmsMmsContactsTest.java index 38f9ca46b20..b929fa65bcf 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/SmsMmsContactsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/SmsMmsContactsTest.java @@ -50,10 +50,8 @@ public class SmsMmsContactsTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private ContentResolver mResolver; - @Spy - private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); + @Mock private ContentResolver mResolver; + @Spy private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance(); private SmsMmsContacts mContacts; @@ -70,30 +68,33 @@ public class SmsMmsContactsTest { @Test public void getPhoneNumberUncached_withNonEmptyCursor() { - MatrixCursor cursor = new MatrixCursor(new String[]{"COL_ARRR_ID", "COL_ADDR_ADDR"}); - cursor.addRow(new Object[]{null, TEST_PHONE_NUMBER}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - - assertThat(SmsMmsContacts.getPhoneNumberUncached(mResolver, TEST_ID)).isEqualTo( - TEST_PHONE_NUMBER); + MatrixCursor cursor = new MatrixCursor(new String[] {"COL_ARRR_ID", "COL_ADDR_ADDR"}); + cursor.addRow(new Object[] {null, TEST_PHONE_NUMBER}); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + + assertThat(SmsMmsContacts.getPhoneNumberUncached(mResolver, TEST_ID)) + .isEqualTo(TEST_PHONE_NUMBER); } @Test public void getPhoneNumberUncached_withEmptyCursor() { - MatrixCursor cursor = new MatrixCursor(new String[]{}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = new MatrixCursor(new String[] {}); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); assertThat(SmsMmsContacts.getPhoneNumberUncached(mResolver, TEST_ID)).isNull(); } @Test public void fillPhoneCache() { - MatrixCursor cursor = new MatrixCursor(new String[]{"COL_ADDR_ID", "COL_ADDR_ADDR"}); - cursor.addRow(new Object[]{TEST_ID, TEST_PHONE_NUMBER}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = new MatrixCursor(new String[] {"COL_ADDR_ID", "COL_ADDR_ADDR"}); + cursor.addRow(new Object[] {TEST_ID, TEST_PHONE_NUMBER}); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContacts.fillPhoneCache(mResolver); @@ -102,15 +103,17 @@ public class SmsMmsContactsTest { @Test public void fillPhoneCache_withNonNullPhoneNumbers() { - MatrixCursor cursor = new MatrixCursor(new String[]{"COL_ADDR_ID", "COL_ADDR_ADDR"}); - cursor.addRow(new Object[]{TEST_ID, TEST_PHONE_NUMBER}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = new MatrixCursor(new String[] {"COL_ADDR_ID", "COL_ADDR_ADDR"}); + cursor.addRow(new Object[] {TEST_ID, TEST_PHONE_NUMBER}); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContacts.fillPhoneCache(mResolver); assertThat(mContacts.getPhoneNumber(mResolver, TEST_ID)).isEqualTo(TEST_PHONE_NUMBER); - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); mContacts.fillPhoneCache(mResolver); assertThat(mContacts.getPhoneNumber(mResolver, TEST_ID)).isNull(); @@ -118,10 +121,11 @@ public class SmsMmsContactsTest { @Test public void clearCache() { - MatrixCursor cursor = new MatrixCursor(new String[]{"COL_ADDR_ID", "COL_ADDR_ADDR"}); - cursor.addRow(new Object[]{TEST_ID, TEST_PHONE_NUMBER}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = new MatrixCursor(new String[] {"COL_ADDR_ID", "COL_ADDR_ADDR"}); + cursor.addRow(new Object[] {TEST_ID, TEST_PHONE_NUMBER}); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); MapContact contact = MapContact.create(TEST_ID, TEST_PHONE); mContacts.mNames.put(TEST_PHONE, contact); @@ -129,37 +133,47 @@ public class SmsMmsContactsTest { assertThat(mContacts.getPhoneNumber(mResolver, TEST_ID)).isEqualTo(TEST_PHONE_NUMBER); mContacts.clearCache(); - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); assertThat(mContacts.mNames).isEmpty(); assertThat(mContacts.getPhoneNumber(mResolver, TEST_ID)).isEqualTo(null); } @Test public void getContactNameFromPhone_withNonNullCursor() { - MatrixCursor cursor = new MatrixCursor(new String[]{"COL_CONTACT_ID", "COL_CONTACT_NAME"}); - cursor.addRow(new Object[]{TEST_ID, TEST_NAME}); - doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + MatrixCursor cursor = new MatrixCursor(new String[] {"COL_CONTACT_ID", "COL_CONTACT_NAME"}); + cursor.addRow(new Object[] {TEST_ID, TEST_NAME}); + doReturn(cursor) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); MapContact expected = MapContact.create(TEST_ID, TEST_NAME); - assertThat(mContacts.getContactNameFromPhone(TEST_PHONE, mResolver, - TEST_CONTACT_NAME_FILTER).toString()).isEqualTo(expected.toString()); + assertThat( + mContacts + .getContactNameFromPhone( + TEST_PHONE, mResolver, TEST_CONTACT_NAME_FILTER) + .toString()) + .isEqualTo(expected.toString()); } @Test public void getContactNameFromPhone_withNullCursor() { - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); - - assertThat(mContacts.getContactNameFromPhone(TEST_PHONE, mResolver, - TEST_CONTACT_NAME_FILTER)).isNull(); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); + + assertThat( + mContacts.getContactNameFromPhone( + TEST_PHONE, mResolver, TEST_CONTACT_NAME_FILTER)) + .isNull(); } @Test public void getContactNameFromPhone_withNoParameterForContactNameFilter() { - doReturn(null).when(mMapMethodProxy).contentResolverQuery(any(), any(), any(), any(), - any(), any()); + doReturn(null) + .when(mMapMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); assertThat(mContacts.getContactNameFromPhone(TEST_PHONE, mResolver)).isNull(); } @@ -170,8 +184,10 @@ public class SmsMmsContactsTest { MapContact contact = MapContact.create(zeroId, TEST_PHONE); mContacts.mNames.put(TEST_PHONE, contact); - assertThat(mContacts.getContactNameFromPhone(TEST_PHONE, mResolver, - TEST_CONTACT_NAME_FILTER)).isNull(); + assertThat( + mContacts.getContactNameFromPhone( + TEST_PHONE, mResolver, TEST_CONTACT_NAME_FILTER)) + .isNull(); } @Test @@ -179,8 +195,8 @@ public class SmsMmsContactsTest { MapContact contact = MapContact.create(TEST_ID, TEST_PHONE); mContacts.mNames.put(TEST_PHONE, contact); - assertThat(mContacts.getContactNameFromPhone(TEST_PHONE, mResolver, null)).isEqualTo( - contact); + assertThat(mContacts.getContactNameFromPhone(TEST_PHONE, mResolver, null)) + .isEqualTo(contact); } @Test @@ -189,7 +205,7 @@ public class SmsMmsContactsTest { mContacts.mNames.put(TEST_PHONE, contact); String nonMatchingFilter = "non_matching_filter"; - assertThat(mContacts.getContactNameFromPhone(TEST_PHONE, mResolver, - nonMatchingFilter)).isNull(); + assertThat(mContacts.getContactNameFromPhone(TEST_PHONE, mResolver, nonMatchingFilter)) + .isNull(); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapContractTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapContractTest.java index 0a34f886e62..c808bca43b9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapContractTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapContractTest.java @@ -35,8 +35,8 @@ public class BluetoothMapContractTest { @Test public void testBuildAccountUri() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + BluetoothMapContract.TABLE_ACCOUNT; + final String expectedUriString = + "content://" + TEST_AUTHORITY + "/" + BluetoothMapContract.TABLE_ACCOUNT; Uri result = BluetoothMapContract.buildAccountUri(TEST_AUTHORITY); assertThat(result.toString()).isEqualTo(expectedUriString); @@ -44,8 +44,13 @@ public class BluetoothMapContractTest { @Test public void testBuildAccountUriWithId() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + BluetoothMapContract.TABLE_ACCOUNT + "/" + ACCOUNT_ID; + final String expectedUriString = + "content://" + + TEST_AUTHORITY + + "/" + + BluetoothMapContract.TABLE_ACCOUNT + + "/" + + ACCOUNT_ID; Uri result = BluetoothMapContract.buildAccountUriwithId(TEST_AUTHORITY, ACCOUNT_ID); assertThat(result.toString()).isEqualTo(expectedUriString); @@ -53,8 +58,8 @@ public class BluetoothMapContractTest { @Test public void testBuildMessageUri() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + BluetoothMapContract.TABLE_MESSAGE; + final String expectedUriString = + "content://" + TEST_AUTHORITY + "/" + BluetoothMapContract.TABLE_MESSAGE; Uri result = BluetoothMapContract.buildMessageUri(TEST_AUTHORITY); assertThat(result.toString()).isEqualTo(expectedUriString); @@ -62,8 +67,13 @@ public class BluetoothMapContractTest { @Test public void testBuildMessageUri_withAccountId() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + ACCOUNT_ID + "/" + BluetoothMapContract.TABLE_MESSAGE; + final String expectedUriString = + "content://" + + TEST_AUTHORITY + + "/" + + ACCOUNT_ID + + "/" + + BluetoothMapContract.TABLE_MESSAGE; Uri result = BluetoothMapContract.buildMessageUri(TEST_AUTHORITY, ACCOUNT_ID); assertThat(result.toString()).isEqualTo(expectedUriString); @@ -71,18 +81,30 @@ public class BluetoothMapContractTest { @Test public void testBuildMessageUriWithId() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + ACCOUNT_ID + "/" + BluetoothMapContract.TABLE_MESSAGE + "/" + MESSAGE_ID; - - Uri result = BluetoothMapContract.buildMessageUriWithId( - TEST_AUTHORITY, ACCOUNT_ID, MESSAGE_ID); + final String expectedUriString = + "content://" + + TEST_AUTHORITY + + "/" + + ACCOUNT_ID + + "/" + + BluetoothMapContract.TABLE_MESSAGE + + "/" + + MESSAGE_ID; + + Uri result = + BluetoothMapContract.buildMessageUriWithId(TEST_AUTHORITY, ACCOUNT_ID, MESSAGE_ID); assertThat(result.toString()).isEqualTo(expectedUriString); } @Test public void testBuildFolderUri() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + ACCOUNT_ID + "/" + BluetoothMapContract.TABLE_FOLDER; + final String expectedUriString = + "content://" + + TEST_AUTHORITY + + "/" + + ACCOUNT_ID + + "/" + + BluetoothMapContract.TABLE_FOLDER; Uri result = BluetoothMapContract.buildFolderUri(TEST_AUTHORITY, ACCOUNT_ID); assertThat(result.toString()).isEqualTo(expectedUriString); @@ -90,8 +112,13 @@ public class BluetoothMapContractTest { @Test public void testBuildConversationUri() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + ACCOUNT_ID + "/" + BluetoothMapContract.TABLE_CONVERSATION; + final String expectedUriString = + "content://" + + TEST_AUTHORITY + + "/" + + ACCOUNT_ID + + "/" + + BluetoothMapContract.TABLE_CONVERSATION; Uri result = BluetoothMapContract.buildConversationUri(TEST_AUTHORITY, ACCOUNT_ID); assertThat(result.toString()).isEqualTo(expectedUriString); @@ -99,8 +126,8 @@ public class BluetoothMapContractTest { @Test public void testBuildConvoContactsUri() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + BluetoothMapContract.TABLE_CONVOCONTACT; + final String expectedUriString = + "content://" + TEST_AUTHORITY + "/" + BluetoothMapContract.TABLE_CONVOCONTACT; Uri result = BluetoothMapContract.buildConvoContactsUri(TEST_AUTHORITY); assertThat(result.toString()).isEqualTo(expectedUriString); @@ -108,8 +135,13 @@ public class BluetoothMapContractTest { @Test public void testBuildConvoContactsUri_withAccountId() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + ACCOUNT_ID + "/" + BluetoothMapContract.TABLE_CONVOCONTACT; + final String expectedUriString = + "content://" + + TEST_AUTHORITY + + "/" + + ACCOUNT_ID + + "/" + + BluetoothMapContract.TABLE_CONVOCONTACT; Uri result = BluetoothMapContract.buildConvoContactsUri(TEST_AUTHORITY, ACCOUNT_ID); assertThat(result.toString()).isEqualTo(expectedUriString); @@ -117,11 +149,19 @@ public class BluetoothMapContractTest { @Test public void testBuildConvoContactsUriWithId() { - final String expectedUriString = "content://" + TEST_AUTHORITY + "/" - + ACCOUNT_ID + "/" + BluetoothMapContract.TABLE_CONVOCONTACT + "/" + CONTACT_ID; - - Uri result = BluetoothMapContract.buildConvoContactsUriWithId( - TEST_AUTHORITY, ACCOUNT_ID, CONTACT_ID); + final String expectedUriString = + "content://" + + TEST_AUTHORITY + + "/" + + ACCOUNT_ID + + "/" + + BluetoothMapContract.TABLE_CONVOCONTACT + + "/" + + CONTACT_ID; + + Uri result = + BluetoothMapContract.buildConvoContactsUriWithId( + TEST_AUTHORITY, ACCOUNT_ID, CONTACT_ID); assertThat(result.toString()).isEqualTo(expectedUriString); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapEmailProviderTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapEmailProviderTest.java index c109dcceb49..a31d416d1e1 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapEmailProviderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapEmailProviderTest.java @@ -59,8 +59,7 @@ public class BluetoothMapEmailProviderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Spy - private BluetoothMapEmailProvider mProvider = new TestBluetoothMapEmailProvider(); + @Spy private BluetoothMapEmailProvider mProvider = new TestBluetoothMapEmailProvider(); @Before public void setUp() throws Exception { @@ -73,8 +72,7 @@ public class BluetoothMapEmailProviderTest { providerInfo.authority = AUTHORITY; providerInfo.exported = false; - assertThrows(SecurityException.class, - () -> mProvider.attachInfo(mContext, providerInfo)); + assertThrows(SecurityException.class, () -> mProvider.attachInfo(mContext, providerInfo)); } @Test @@ -84,8 +82,7 @@ public class BluetoothMapEmailProviderTest { providerInfo.exported = true; providerInfo.writePermission = "some.random.permission"; - assertThrows(SecurityException.class, - () -> mProvider.attachInfo(mContext, providerInfo)); + assertThrows(SecurityException.class, () -> mProvider.attachInfo(mContext, providerInfo)); } @Test @@ -105,7 +102,7 @@ public class BluetoothMapEmailProviderTest { @Test public void getType() throws Exception { try { - mProvider.getType(/*uri=*/ null); + mProvider.getType(/* uri= */ null); } catch (Exception e) { assertWithMessage("Exception should not happen.").fail(); } @@ -113,38 +110,46 @@ public class BluetoothMapEmailProviderTest { @Test public void delete_whenTableNameIsWrong() throws Exception { - Uri uriWithWrongTable = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath("some_random_table_name") - .appendPath(MESSAGE_ID) - .build(); + Uri uriWithWrongTable = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath("some_random_table_name") + .appendPath(MESSAGE_ID) + .build(); // No rows are impacted. - assertThat(mProvider.delete(uriWithWrongTable, /*where=*/null, /*selectionArgs=*/null)) + assertThat( + mProvider.delete( + uriWithWrongTable, /* where= */ null, /* selectionArgs= */ null)) .isEqualTo(0); } @Test public void delete_success() throws Exception { - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .appendPath(MESSAGE_ID) - .build(); - - mProvider.delete(messageUri, /*where=*/null, /*selectionArgs=*/null); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .appendPath(MESSAGE_ID) + .build(); + + mProvider.delete(messageUri, /* where= */ null, /* selectionArgs= */ null); verify(mProvider).deleteMessage(ACCOUNT_ID, MESSAGE_ID); } @Test public void insert_whenFolderIdIsNull() throws Exception { - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .build(); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .build(); // ContentValues doses not have folder ID. ContentValues values = new ContentValues(); @@ -153,11 +158,13 @@ public class BluetoothMapEmailProviderTest { @Test public void insert_whenTableNameIsWrong() throws Exception { - Uri uriWithWrongTable = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath("some_random_table_name") - .build(); + Uri uriWithWrongTable = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath("some_random_table_name") + .build(); ContentValues values = new ContentValues(); values.put(BluetoothMapContract.MessageColumns.FOLDER_ID, Long.parseLong(FOLDER_ID)); @@ -166,11 +173,13 @@ public class BluetoothMapEmailProviderTest { @Test public void insert_success() throws Exception { - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .build(); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .build(); ContentValues values = new ContentValues(); values.put(BluetoothMapContract.MessageColumns.FOLDER_ID, Long.parseLong(FOLDER_ID)); @@ -187,13 +196,19 @@ public class BluetoothMapEmailProviderTest { providerInfo.writePermission = android.Manifest.permission.BLUETOOTH_MAP; mProvider.attachInfo(mContext, providerInfo); - Uri accountUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(BluetoothMapContract.TABLE_ACCOUNT) - .build(); - - mProvider.query(accountUri, /*projection=*/ null, /*selection=*/ null, - /*selectionArgs=*/ null, /*sortOrder=*/ null); + Uri accountUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(BluetoothMapContract.TABLE_ACCOUNT) + .build(); + + mProvider.query( + accountUri, + /* projection= */ null, + /* selection= */ null, + /* selectionArgs= */ null, + /* sortOrder= */ null); verify(mProvider).queryAccount(any(), any(), any(), any()); } @@ -205,14 +220,20 @@ public class BluetoothMapEmailProviderTest { providerInfo.writePermission = android.Manifest.permission.BLUETOOTH_MAP; mProvider.attachInfo(mContext, providerInfo); - Uri folderUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_FOLDER) - .build(); - - mProvider.query(folderUri, /*projection=*/ null, /*selection=*/ null, - /*selectionArgs=*/ null, /*sortOrder=*/ null); + Uri folderUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_FOLDER) + .build(); + + mProvider.query( + folderUri, + /* projection= */ null, + /* selection= */ null, + /* selectionArgs= */ null, + /* sortOrder= */ null); verify(mProvider).queryFolder(eq(ACCOUNT_ID), any(), any(), any(), any()); } @@ -224,82 +245,109 @@ public class BluetoothMapEmailProviderTest { providerInfo.writePermission = android.Manifest.permission.BLUETOOTH_MAP; mProvider.attachInfo(mContext, providerInfo); - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .build(); - - mProvider.query(messageUri, /*projection=*/ null, /*selection=*/ null, - /*selectionArgs=*/ null, /*sortOrder=*/ null); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .build(); + + mProvider.query( + messageUri, + /* projection= */ null, + /* selection= */ null, + /* selectionArgs= */ null, + /* sortOrder= */ null); verify(mProvider).queryMessage(eq(ACCOUNT_ID), any(), any(), any(), any()); } @Test public void update_whenTableIsNull() { - Uri uriWithoutTable = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .build(); + Uri uriWithoutTable = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .build(); ContentValues values = new ContentValues(); - assertThrows(IllegalArgumentException.class, - () -> mProvider.update(uriWithoutTable, values, /*selection=*/ null, - /*selectionArgs=*/ null)); + assertThrows( + IllegalArgumentException.class, + () -> + mProvider.update( + uriWithoutTable, + values, + /* selection= */ null, + /* selectionArgs= */ null)); } @Test public void update_whenSelectionIsNotNull() { - Uri uriWithTable = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_ACCOUNT) - .build(); + Uri uriWithTable = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_ACCOUNT) + .build(); ContentValues values = new ContentValues(); String nonNullSelection = "id = 1234"; - assertThrows(IllegalArgumentException.class, - () -> mProvider.update(uriWithTable, values, nonNullSelection, - /*selectionArgs=*/ null)); + assertThrows( + IllegalArgumentException.class, + () -> + mProvider.update( + uriWithTable, values, nonNullSelection, /* selectionArgs= */ null)); } @Test public void update_forAccountUri_success() { - Uri accountUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_ACCOUNT) - .build(); + Uri accountUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_ACCOUNT) + .build(); ContentValues values = new ContentValues(); final int flagValue = 1; values.put(BluetoothMapContract.AccountColumns._ID, ACCOUNT_ID); values.put(BluetoothMapContract.AccountColumns.FLAG_EXPOSE, flagValue); - mProvider.update(accountUri, values, /*selection=*/ null, /*selectionArgs=*/ null); + mProvider.update(accountUri, values, /* selection= */ null, /* selectionArgs= */ null); verify(mProvider).updateAccount(ACCOUNT_ID, flagValue); } @Test public void update_forFolderUri() { - Uri folderUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_FOLDER) - .build(); - - assertThat(mProvider.update( - folderUri, /*values=*/ null, /*selection=*/ null, /*selectionArgs=*/ null)) + Uri folderUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_FOLDER) + .build(); + + assertThat( + mProvider.update( + folderUri, + /* values= */ null, + /* selection= */ null, + /* selectionArgs= */ null)) .isEqualTo(0); } @Test public void update_forMessageUri_success() { - Uri accountUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .build(); + Uri accountUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .build(); ContentValues values = new ContentValues(); final boolean flagRead = true; @@ -307,15 +355,19 @@ public class BluetoothMapEmailProviderTest { values.put(BluetoothMapContract.MessageColumns.FOLDER_ID, Long.parseLong(FOLDER_ID)); values.put(BluetoothMapContract.MessageColumns.FLAG_READ, flagRead); - mProvider.update(accountUri, values, /*selection=*/ null, /*selectionArgs=*/ null); - verify(mProvider).updateMessage( - ACCOUNT_ID, Long.parseLong(MESSAGE_ID), Long.parseLong(FOLDER_ID), flagRead); + mProvider.update(accountUri, values, /* selection= */ null, /* selectionArgs= */ null); + verify(mProvider) + .updateMessage( + ACCOUNT_ID, + Long.parseLong(MESSAGE_ID), + Long.parseLong(FOLDER_ID), + flagRead); } @Test public void call_whenMethodIsWrong() { String method = "some_random_method"; - assertThat(mProvider.call(method, /*arg=*/ null, /*extras=*/ null)).isNull(); + assertThat(mProvider.call(method, /* arg= */ null, /* extras= */ null)).isNull(); } @Test @@ -323,7 +375,9 @@ public class BluetoothMapEmailProviderTest { Bundle extras = new Bundle(); extras.putLong(BluetoothMapContract.EXTRA_UPDATE_FOLDER_ID, 12345); - assertThat(mProvider.call(BluetoothMapContract.METHOD_UPDATE_FOLDER, /*arg=*/ null, extras)) + assertThat( + mProvider.call( + BluetoothMapContract.METHOD_UPDATE_FOLDER, /* arg= */ null, extras)) .isNull(); } @@ -332,7 +386,9 @@ public class BluetoothMapEmailProviderTest { Bundle extras = new Bundle(); extras.putLong(BluetoothMapContract.EXTRA_UPDATE_ACCOUNT_ID, 12345); - assertThat(mProvider.call(BluetoothMapContract.METHOD_UPDATE_FOLDER, /*arg=*/ null, extras)) + assertThat( + mProvider.call( + BluetoothMapContract.METHOD_UPDATE_FOLDER, /* arg= */ null, extras)) .isNull(); } @@ -342,7 +398,7 @@ public class BluetoothMapEmailProviderTest { extras.putLong(BluetoothMapContract.EXTRA_UPDATE_ACCOUNT_ID, Long.parseLong(ACCOUNT_ID)); extras.putLong(BluetoothMapContract.EXTRA_UPDATE_FOLDER_ID, Long.parseLong(FOLDER_ID)); - mProvider.call(BluetoothMapContract.METHOD_UPDATE_FOLDER, /*arg=*/ null, extras); + mProvider.call(BluetoothMapContract.METHOD_UPDATE_FOLDER, /* arg= */ null, extras); verify(mProvider).syncFolder(Long.parseLong(ACCOUNT_ID), Long.parseLong(FOLDER_ID)); } @@ -357,32 +413,39 @@ public class BluetoothMapEmailProviderTest { @Test public void getAccountId_whenNotEnoughPathSegments() { - Uri uri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .build(); - - assertThrows(IllegalArgumentException.class, - () -> BluetoothMapEmailProvider.getAccountId(uri)); + Uri uri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .build(); + + assertThrows( + IllegalArgumentException.class, () -> BluetoothMapEmailProvider.getAccountId(uri)); } @Test public void getAccountId_success() { - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .appendPath(MESSAGE_ID) - .build(); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .appendPath(MESSAGE_ID) + .build(); assertThat(BluetoothMapEmailProvider.getAccountId(messageUri)).isEqualTo(ACCOUNT_ID); } public static class TestBluetoothMapEmailProvider extends BluetoothMapEmailProvider { @Override - protected void WriteMessageToStream(long accountId, long messageId, - boolean includeAttachment, boolean download, FileOutputStream out) - throws IOException { - } + protected void WriteMessageToStream( + long accountId, + long messageId, + boolean includeAttachment, + boolean download, + FileOutputStream out) + throws IOException {} @Override protected Uri getContentUri() { @@ -390,9 +453,8 @@ public class BluetoothMapEmailProviderTest { } @Override - protected void UpdateMimeMessageFromStream(FileInputStream input, long accountId, - long messageId) throws IOException { - } + protected void UpdateMimeMessageFromStream( + FileInputStream input, long accountId, long messageId) throws IOException {} @Override protected int deleteMessage(String accountId, String messageId) { @@ -405,20 +467,28 @@ public class BluetoothMapEmailProviderTest { } @Override - protected Cursor queryAccount(String[] projection, String selection, String[] selectionArgs, - String sortOrder) { + protected Cursor queryAccount( + String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; } @Override - protected Cursor queryFolder(String accountId, String[] projection, String selection, - String[] selectionArgs, String sortOrder) { + protected Cursor queryFolder( + String accountId, + String[] projection, + String selection, + String[] selectionArgs, + String sortOrder) { return null; } @Override - protected Cursor queryMessage(String accountId, String[] projection, String selection, - String[] selectionArgs, String sortOrder) { + protected Cursor queryMessage( + String accountId, + String[] projection, + String selection, + String[] selectionArgs, + String sortOrder) { return null; } @@ -428,8 +498,8 @@ public class BluetoothMapEmailProviderTest { } @Override - protected int updateMessage(String accountId, Long messageId, Long folderId, - Boolean flagRead) { + protected int updateMessage( + String accountId, Long messageId, Long folderId, Boolean flagRead) { return 0; } @@ -442,6 +512,6 @@ public class BluetoothMapEmailProviderTest { public boolean onCreate() { return true; } - }; - + } + ; } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapIMProviderTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapIMProviderTest.java index cae58764919..f01fe54a968 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapIMProviderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapIMProviderTest.java @@ -70,8 +70,7 @@ public class BluetoothMapIMProviderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Spy - private BluetoothMapIMProvider mProvider = new TestBluetoothMapIMProvider(); + @Spy private BluetoothMapIMProvider mProvider = new TestBluetoothMapIMProvider(); @Before public void setUp() throws Exception { @@ -84,8 +83,7 @@ public class BluetoothMapIMProviderTest { providerInfo.authority = AUTHORITY; providerInfo.exported = false; - assertThrows(SecurityException.class, - () -> mProvider.attachInfo(mContext, providerInfo)); + assertThrows(SecurityException.class, () -> mProvider.attachInfo(mContext, providerInfo)); } @Test @@ -95,8 +93,7 @@ public class BluetoothMapIMProviderTest { providerInfo.exported = true; providerInfo.writePermission = "some.random.permission"; - assertThrows(SecurityException.class, - () -> mProvider.attachInfo(mContext, providerInfo)); + assertThrows(SecurityException.class, () -> mProvider.attachInfo(mContext, providerInfo)); } @Test @@ -116,7 +113,7 @@ public class BluetoothMapIMProviderTest { @Test public void getType() throws Exception { try { - mProvider.getType(/*uri=*/ null); + mProvider.getType(/* uri= */ null); } catch (Exception e) { assertWithMessage("Exception should not happen.").fail(); } @@ -124,38 +121,46 @@ public class BluetoothMapIMProviderTest { @Test public void delete_whenTableNameIsWrong() throws Exception { - Uri uriWithWrongTable = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath("some_random_table_name") - .appendPath(MESSAGE_ID) - .build(); + Uri uriWithWrongTable = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath("some_random_table_name") + .appendPath(MESSAGE_ID) + .build(); // No rows are impacted. - assertThat(mProvider.delete(uriWithWrongTable, /*where=*/null, /*selectionArgs=*/null)) + assertThat( + mProvider.delete( + uriWithWrongTable, /* where= */ null, /* selectionArgs= */ null)) .isEqualTo(0); } @Test public void delete_success() throws Exception { - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .appendPath(MESSAGE_ID) - .build(); - - mProvider.delete(messageUri, /*where=*/null, /*selectionArgs=*/null); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .appendPath(MESSAGE_ID) + .build(); + + mProvider.delete(messageUri, /* where= */ null, /* selectionArgs= */ null); verify(mProvider).deleteMessage(ACCOUNT_ID, MESSAGE_ID); } @Test public void insert_whenTableNameIsWrong() throws Exception { - Uri uriWithWrongTable = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath("some_random_table_name") - .build(); + Uri uriWithWrongTable = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath("some_random_table_name") + .build(); ContentValues values = new ContentValues(); values.put(BluetoothMapContract.MessageColumns.FOLDER_ID, Long.parseLong(FOLDER_ID)); @@ -164,11 +169,13 @@ public class BluetoothMapIMProviderTest { @Test public void insert_success() throws Exception { - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .build(); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .build(); ContentValues values = new ContentValues(); values.put(BluetoothMapContract.MessageColumns.FOLDER_ID, Long.parseLong(FOLDER_ID)); @@ -185,13 +192,19 @@ public class BluetoothMapIMProviderTest { providerInfo.writePermission = android.Manifest.permission.BLUETOOTH_MAP; mProvider.attachInfo(mContext, providerInfo); - Uri accountUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(BluetoothMapContract.TABLE_ACCOUNT) - .build(); - - mProvider.query(accountUri, /*projection=*/ null, /*selection=*/ null, - /*selectionArgs=*/ null, /*sortOrder=*/ null); + Uri accountUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(BluetoothMapContract.TABLE_ACCOUNT) + .build(); + + mProvider.query( + accountUri, + /* projection= */ null, + /* selection= */ null, + /* selectionArgs= */ null, + /* sortOrder= */ null); verify(mProvider).queryAccount(any(), any(), any(), any()); } @@ -203,14 +216,20 @@ public class BluetoothMapIMProviderTest { providerInfo.writePermission = android.Manifest.permission.BLUETOOTH_MAP; mProvider.attachInfo(mContext, providerInfo); - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .build(); - - mProvider.query(messageUri, /*projection=*/ null, /*selection=*/ null, - /*selectionArgs=*/ null, /*sortOrder=*/ null); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .build(); + + mProvider.query( + messageUri, + /* projection= */ null, + /* selection= */ null, + /* selectionArgs= */ null, + /* sortOrder= */ null); verify(mProvider).queryMessage(eq(ACCOUNT_ID), any(), any(), any(), any()); } @@ -228,26 +247,41 @@ public class BluetoothMapIMProviderTest { final long periodBegin = 10; final String searchString = "sample_search_query"; - Uri conversationUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_CONVERSATION) - .appendQueryParameter(BluetoothMapContract.FILTER_ORIGINATOR_SUBSTRING, - searchString) - .appendQueryParameter(BluetoothMapContract.FILTER_PERIOD_BEGIN, - Long.toString(periodBegin)) - .appendQueryParameter(BluetoothMapContract.FILTER_PERIOD_END, - Long.toString(periodEnd)) - .appendQueryParameter(BluetoothMapContract.FILTER_READ_STATUS, - Boolean.toString(read)) - .appendQueryParameter(BluetoothMapContract.FILTER_THREAD_ID, - Long.toString(threadId)) - .build(); - - mProvider.query(conversationUri, /*projection=*/ null, /*selection=*/ null, - /*selectionArgs=*/ null, /*sortOrder=*/ null); - verify(mProvider).queryConversation(eq(ACCOUNT_ID), eq(threadId), eq(read), eq(periodEnd), - eq(periodBegin), eq(searchString), any(), any()); + Uri conversationUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_CONVERSATION) + .appendQueryParameter( + BluetoothMapContract.FILTER_ORIGINATOR_SUBSTRING, searchString) + .appendQueryParameter( + BluetoothMapContract.FILTER_PERIOD_BEGIN, + Long.toString(periodBegin)) + .appendQueryParameter( + BluetoothMapContract.FILTER_PERIOD_END, Long.toString(periodEnd)) + .appendQueryParameter( + BluetoothMapContract.FILTER_READ_STATUS, Boolean.toString(read)) + .appendQueryParameter( + BluetoothMapContract.FILTER_THREAD_ID, Long.toString(threadId)) + .build(); + + mProvider.query( + conversationUri, + /* projection= */ null, + /* selection= */ null, + /* selectionArgs= */ null, + /* sortOrder= */ null); + verify(mProvider) + .queryConversation( + eq(ACCOUNT_ID), + eq(threadId), + eq(read), + eq(periodEnd), + eq(periodBegin), + eq(searchString), + any(), + any()); } @Test @@ -258,108 +292,147 @@ public class BluetoothMapIMProviderTest { providerInfo.writePermission = android.Manifest.permission.BLUETOOTH_MAP; mProvider.attachInfo(mContext, providerInfo); - Uri convoContactUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_CONVOCONTACT) - .build(); - - mProvider.query(convoContactUri, /*projection=*/ null, /*selection=*/ null, - /*selectionArgs=*/ null, /*sortOrder=*/ null); + Uri convoContactUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_CONVOCONTACT) + .build(); + + mProvider.query( + convoContactUri, + /* projection= */ null, + /* selection= */ null, + /* selectionArgs= */ null, + /* sortOrder= */ null); verify(mProvider).queryConvoContact(eq(ACCOUNT_ID), any(), any(), any(), any(), any()); } @Test public void update_whenTableIsNull() { - Uri uriWithoutTable = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .build(); + Uri uriWithoutTable = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .build(); ContentValues values = new ContentValues(); - assertThrows(IllegalArgumentException.class, - () -> mProvider.update(uriWithoutTable, values, /*selection=*/ null, - /*selectionArgs=*/ null)); + assertThrows( + IllegalArgumentException.class, + () -> + mProvider.update( + uriWithoutTable, + values, + /* selection= */ null, + /* selectionArgs= */ null)); } @Test public void update_whenSelectionIsNotNull() { - Uri uriWithTable = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_ACCOUNT) - .build(); + Uri uriWithTable = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_ACCOUNT) + .build(); ContentValues values = new ContentValues(); String nonNullSelection = "id = 1234"; - assertThrows(IllegalArgumentException.class, - () -> mProvider.update(uriWithTable, values, nonNullSelection, - /*selectionArgs=*/ null)); + assertThrows( + IllegalArgumentException.class, + () -> + mProvider.update( + uriWithTable, values, nonNullSelection, /* selectionArgs= */ null)); } @Test public void update_forAccountUri_success() { - Uri accountUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_ACCOUNT) - .build(); + Uri accountUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_ACCOUNT) + .build(); ContentValues values = new ContentValues(); final int flagValue = 1; values.put(BluetoothMapContract.AccountColumns._ID, ACCOUNT_ID); values.put(BluetoothMapContract.AccountColumns.FLAG_EXPOSE, flagValue); - mProvider.update(accountUri, values, /*selection=*/ null, /*selectionArgs=*/ null); + mProvider.update(accountUri, values, /* selection= */ null, /* selectionArgs= */ null); verify(mProvider).updateAccount(ACCOUNT_ID, flagValue); } @Test public void update_forFolderUri() { - Uri folderUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_FOLDER) - .build(); - - assertThat(mProvider.update( - folderUri, /*values=*/ null, /*selection=*/ null, /*selectionArgs=*/ null)) + Uri folderUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_FOLDER) + .build(); + + assertThat( + mProvider.update( + folderUri, + /* values= */ null, + /* selection= */ null, + /* selectionArgs= */ null)) .isEqualTo(0); } @Test public void update_forConversationUri() { - Uri folderUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_CONVERSATION) - .build(); - - assertThat(mProvider.update( - folderUri, /*values=*/ null, /*selection=*/ null, /*selectionArgs=*/ null)) + Uri folderUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_CONVERSATION) + .build(); + + assertThat( + mProvider.update( + folderUri, + /* values= */ null, + /* selection= */ null, + /* selectionArgs= */ null)) .isEqualTo(0); } @Test public void update_forConvoContactUri() { - Uri folderUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_CONVOCONTACT) - .build(); - - assertThat(mProvider.update( - folderUri, /*values=*/ null, /*selection=*/ null, /*selectionArgs=*/ null)) + Uri folderUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_CONVOCONTACT) + .build(); + + assertThat( + mProvider.update( + folderUri, + /* values= */ null, + /* selection= */ null, + /* selectionArgs= */ null)) .isEqualTo(0); } @Test public void update_forMessageUri_success() { - Uri accountUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .build(); + Uri accountUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .build(); ContentValues values = new ContentValues(); final boolean flagRead = true; @@ -367,15 +440,19 @@ public class BluetoothMapIMProviderTest { values.put(BluetoothMapContract.MessageColumns.FOLDER_ID, Long.parseLong(FOLDER_ID)); values.put(BluetoothMapContract.MessageColumns.FLAG_READ, flagRead); - mProvider.update(accountUri, values, /*selection=*/ null, /*selectionArgs=*/ null); - verify(mProvider).updateMessage( - ACCOUNT_ID, Long.parseLong(MESSAGE_ID), Long.parseLong(FOLDER_ID), flagRead); + mProvider.update(accountUri, values, /* selection= */ null, /* selectionArgs= */ null); + verify(mProvider) + .updateMessage( + ACCOUNT_ID, + Long.parseLong(MESSAGE_ID), + Long.parseLong(FOLDER_ID), + flagRead); } @Test public void call_whenMethodIsWrong() { String method = "some_random_method"; - assertThat(mProvider.call(method, /*arg=*/ null, /*extras=*/ null)).isNull(); + assertThat(mProvider.call(method, /* arg= */ null, /* extras= */ null)).isNull(); } @Test @@ -383,7 +460,9 @@ public class BluetoothMapIMProviderTest { Bundle extras = new Bundle(); extras.putLong(BluetoothMapContract.EXTRA_UPDATE_FOLDER_ID, 12345); - assertThat(mProvider.call(BluetoothMapContract.METHOD_UPDATE_FOLDER, /*arg=*/ null, extras)) + assertThat( + mProvider.call( + BluetoothMapContract.METHOD_UPDATE_FOLDER, /* arg= */ null, extras)) .isNull(); } @@ -392,7 +471,9 @@ public class BluetoothMapIMProviderTest { Bundle extras = new Bundle(); extras.putLong(BluetoothMapContract.EXTRA_UPDATE_ACCOUNT_ID, 12345); - assertThat(mProvider.call(BluetoothMapContract.METHOD_UPDATE_FOLDER, /*arg=*/ null, extras)) + assertThat( + mProvider.call( + BluetoothMapContract.METHOD_UPDATE_FOLDER, /* arg= */ null, extras)) .isNull(); } @@ -402,7 +483,7 @@ public class BluetoothMapIMProviderTest { extras.putLong(BluetoothMapContract.EXTRA_UPDATE_ACCOUNT_ID, Long.parseLong(ACCOUNT_ID)); extras.putLong(BluetoothMapContract.EXTRA_UPDATE_FOLDER_ID, Long.parseLong(FOLDER_ID)); - mProvider.call(BluetoothMapContract.METHOD_UPDATE_FOLDER, /*arg=*/ null, extras); + mProvider.call(BluetoothMapContract.METHOD_UPDATE_FOLDER, /* arg= */ null, extras); verify(mProvider).syncFolder(Long.parseLong(ACCOUNT_ID), Long.parseLong(FOLDER_ID)); } @@ -421,9 +502,9 @@ public class BluetoothMapIMProviderTest { extras.putInt(BluetoothMapContract.EXTRA_CHAT_STATE, chatState); extras.putString(BluetoothMapContract.EXTRA_CONVERSATION_ID, convoId); - mProvider.call(BluetoothMapContract.METHOD_SET_OWNER_STATUS, /*arg=*/ null, extras); - verify(mProvider).setOwnerStatus(presenceState, presenceStatus, lastActive, chatState, - convoId); + mProvider.call(BluetoothMapContract.METHOD_SET_OWNER_STATUS, /* arg= */ null, extras); + verify(mProvider) + .setOwnerStatus(presenceState, presenceStatus, lastActive, chatState, convoId); } @Test @@ -433,7 +514,7 @@ public class BluetoothMapIMProviderTest { Bundle extras = new Bundle(); extras.putBoolean(BluetoothMapContract.EXTRA_BLUETOOTH_STATE, state); - mProvider.call(BluetoothMapContract.METHOD_SET_BLUETOOTH_STATE, /*arg=*/ null, extras); + mProvider.call(BluetoothMapContract.METHOD_SET_BLUETOOTH_STATE, /* arg= */ null, extras); verify(mProvider).setBluetoothStatus(state); } @@ -448,22 +529,26 @@ public class BluetoothMapIMProviderTest { @Test public void getAccountId_whenNotEnoughPathSegments() { - Uri uri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .build(); + Uri uri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .build(); - assertThrows(IllegalArgumentException.class, - () -> BluetoothMapEmailProvider.getAccountId(uri)); + assertThrows( + IllegalArgumentException.class, () -> BluetoothMapEmailProvider.getAccountId(uri)); } @Test public void getAccountId_success() { - Uri messageUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) - .authority(AUTHORITY) - .appendPath(ACCOUNT_ID) - .appendPath(BluetoothMapContract.TABLE_MESSAGE) - .appendPath(MESSAGE_ID) - .build(); + Uri messageUri = + new Uri.Builder() + .scheme(ContentResolver.SCHEME_CONTENT) + .authority(AUTHORITY) + .appendPath(ACCOUNT_ID) + .appendPath(BluetoothMapContract.TABLE_MESSAGE) + .appendPath(MESSAGE_ID) + .build(); assertThat(BluetoothMapEmailProvider.getAccountId(messageUri)).isEqualTo(ACCOUNT_ID); } @@ -508,7 +593,7 @@ public class BluetoothMapIMProviderTest { Uri expectedUri; expectedUri = BluetoothMapContract.buildConvoContactsUri(AUTHORITY); - mProvider.onContactChanged(null,null); + mProvider.onContactChanged(null, null); verify(resolver).notifyChange(expectedUri, null); Mockito.clearInvocations(resolver); @@ -519,8 +604,8 @@ public class BluetoothMapIMProviderTest { Mockito.clearInvocations(resolver); String contactId = "23623"; - expectedUri = BluetoothMapContract.buildConvoContactsUriWithId( - AUTHORITY, accountId, contactId); + expectedUri = + BluetoothMapContract.buildConvoContactsUriWithId(AUTHORITY, accountId, contactId); mProvider.onContactChanged(accountId, contactId); verify(resolver).notifyChange(expectedUri, null); } @@ -551,8 +636,7 @@ public class BluetoothMapIMProviderTest { Mockito.clearInvocations(resolver); String messageId = "23623"; - expectedUri = BluetoothMapContract.buildMessageUriWithId( - AUTHORITY, accountId, messageId); + expectedUri = BluetoothMapContract.buildMessageUriWithId(AUTHORITY, accountId, messageId); mProvider.onMessageChanged(accountId, messageId); verify(resolver).notifyChange(expectedUri, null); } @@ -581,10 +665,19 @@ public class BluetoothMapIMProviderTest { String convertedKey = "test_converted_key"; keyMap.put(key, convertedKey); - Object[] valuesToTest = new Object[] { - null, true, (byte) 0x01, new byte[] {0x01, 0x02}, - 0.01, 0.01f, 123, 12345L, (short) 10, "testString" - }; + Object[] valuesToTest = + new Object[] { + null, + true, + (byte) 0x01, + new byte[] {0x01, 0x02}, + 0.01, + 0.01f, + 123, + 12345L, + (short) 10, + "testString" + }; for (Object value : valuesToTest) { Log.d(TAG, "value=" + value); @@ -619,27 +712,42 @@ public class BluetoothMapIMProviderTest { } @Override - protected Cursor queryAccount(String[] projection, String selection, String[] selectionArgs, - String sortOrder) { + protected Cursor queryAccount( + String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; } @Override - protected Cursor queryMessage(String accountId, String[] projection, String selection, - String[] selectionArgs, String sortOrder) { + protected Cursor queryMessage( + String accountId, + String[] projection, + String selection, + String[] selectionArgs, + String sortOrder) { return null; } @Override - protected Cursor queryConversation(String accountId, Long threadId, Boolean read, - Long periodEnd, Long periodBegin, String searchString, String[] projection, + protected Cursor queryConversation( + String accountId, + Long threadId, + Boolean read, + Long periodEnd, + Long periodBegin, + String searchString, + String[] projection, String sortOrder) { return null; } @Override - protected Cursor queryConvoContact(String accountId, Long contactId, String[] projection, - String selection, String[] selectionArgs, String sortOrder) { + protected Cursor queryConvoContact( + String accountId, + Long contactId, + String[] projection, + String selection, + String[] selectionArgs, + String sortOrder) { return null; } @@ -649,8 +757,8 @@ public class BluetoothMapIMProviderTest { } @Override - protected int updateMessage(String accountId, Long messageId, Long folderId, - Boolean flagRead) { + protected int updateMessage( + String accountId, Long messageId, Long folderId, Boolean flagRead) { return 0; } @@ -660,8 +768,12 @@ public class BluetoothMapIMProviderTest { } @Override - protected int setOwnerStatus(int presenceState, String presenceStatus, long lastActive, - int chatState, String convoId) { + protected int setOwnerStatus( + int presenceState, + String presenceStatus, + long lastActive, + int chatState, + String convoId) { return 0; } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/BmessageTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/BmessageTest.java index c7d011ae3f0..2da0f14a2dc 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/BmessageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/BmessageTest.java @@ -31,31 +31,31 @@ public class BmessageTest { private static final String TAG = BmessageTest.class.getSimpleName(); private static final String SIMPLE_MMS_MESSAGE = "BEGIN:BMSG\r\nVERSION:1.0\r\nSTATUS:READ\r\nTYPE:MMS\r\nFOLDER:null\r\nBEGIN:BENV\r\n" - + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" - + "BEGIN:BBODY\r\nLENGTH:39\r\nBEGIN:MSG\r\nThis is a new msg\r\nEND:MSG\r\n" - + "END:BBODY\r\nEND:BENV\r\nEND:BMSG\r\n"; + + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" + + "BEGIN:BBODY\r\nLENGTH:39\r\nBEGIN:MSG\r\nThis is a new msg\r\nEND:MSG\r\n" + + "END:BBODY\r\nEND:BENV\r\nEND:BMSG\r\n"; private static final String NO_END_MESSAGE = "BEGIN:BMSG\r\nVERSION:1.0\r\nSTATUS:READ\r\nTYPE:MMS\r\nFOLDER:null\r\nBEGIN:BENV\r\n" - + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" - + "BEGIN:BBODY\r\nLENGTH:39\r\nBEGIN:MSG\r\nThis is a new msg\r\n"; + + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" + + "BEGIN:BBODY\r\nLENGTH:39\r\nBEGIN:MSG\r\nThis is a new msg\r\n"; private static final String WRONG_LENGTH_MESSAGE = "BEGIN:BMSG\r\nVERSION:1.0\r\nSTATUS:READ\r\nTYPE:MMS\r\nFOLDER:null\r\nBEGIN:BENV\r\n" - + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" - + "BEGIN:BBODY\r\nLENGTH:200\r\nBEGIN:MSG\r\nThis is a new msg\r\nEND:MSG\r\n" - + "END:BBODY\r\nEND:BENV\r\nEND:BMSG\r\n"; + + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" + + "BEGIN:BBODY\r\nLENGTH:200\r\nBEGIN:MSG\r\nThis is a new msg\r\nEND:MSG\r\n" + + "END:BBODY\r\nEND:BENV\r\nEND:BMSG\r\n"; private static final String NO_BODY_MESSAGE = "BEGIN:BMSG\r\nVERSION:1.0\r\nSTATUS:READ\r\nTYPE:MMS\r\nFOLDER:null\r\nBEGIN:BENV\r\n" - + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" - + "BEGIN:BBODY\r\nLENGTH:\r\n"; + + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" + + "BEGIN:BBODY\r\nLENGTH:\r\n"; private static final String NEGATIVE_LENGTH_MESSAGE = "BEGIN:BMSG\r\nVERSION:1.0\r\nSTATUS:READ\r\nTYPE:MMS\r\nFOLDER:null\r\nBEGIN:BENV\r\n" - + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" - + "BEGIN:BBODY\r\nLENGTH:-1\r\nBEGIN:MSG\r\nThis is a new msg\r\nEND:MSG\r\n" - + "END:BBODY\r\nEND:BENV\r\nEND:BMSG\r\n"; + + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" + + "BEGIN:BBODY\r\nLENGTH:-1\r\nBEGIN:MSG\r\nThis is a new msg\r\nEND:MSG\r\n" + + "END:BBODY\r\nEND:BENV\r\nEND:BMSG\r\n"; @Test public void testNormalMessages() { diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/EventReportTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/EventReportTest.java index 51ee03b870b..3c355e1ad1c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/EventReportTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/EventReportTest.java @@ -102,8 +102,8 @@ public class EventReportTest { assertThat(report.getType()).isEqualTo(type); assertThat(report.getDateTime()).isEqualTo(dateTime); - assertThat(report.getTimestamp()).isEqualTo( - new ObexTime(dateTime).getInstant().toEpochMilli()); + assertThat(report.getTimestamp()) + .isEqualTo(new ObexTime(dateTime).getInstant().toEpochMilli()); assertThat(report.getHandle()).isEqualTo(handle); assertThat(report.getFolder()).isEqualTo(folder); assertThat(report.getOldFolder()).isEqualTo(oldFolder); diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java index e731a2b2a38..48bbc7f9642 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java @@ -88,7 +88,6 @@ public class MapClientContentTest { private static final boolean MESSAGE_SEEN = true; private static final boolean MESSAGE_NOT_SEEN = false; - private VCardEntry mOriginator; private ArgumentCaptor mUriArgument = ArgumentCaptor.forClass(Uri.class); @@ -97,26 +96,19 @@ public class MapClientContentTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private AdapterService mAdapterService; - @Mock - private DatabaseManager mDatabaseManager; - @Mock - private MapClientService mMockMapClientService; - @Mock - private Context mMockContext; - @Mock - private MapClientContent.Callbacks mCallbacks; + @Mock private AdapterService mAdapterService; + @Mock private DatabaseManager mDatabaseManager; + @Mock private MapClientService mMockMapClientService; + @Mock private Context mMockContext; + @Mock private MapClientContent.Callbacks mCallbacks; private MockContentResolver mMockContentResolver; private FakeContentProvider mMockSmsContentProvider; private FakeContentProvider mMockMmsContentProvider; private FakeContentProvider mMockThreadContentProvider; - @Mock - private SubscriptionManager mMockSubscriptionManager; - @Mock - private SubscriptionInfo mMockSubscription; + @Mock private SubscriptionManager mMockSubscriptionManager; + @Mock private SubscriptionInfo mMockSubscription; @Before public void setUp() throws Exception { @@ -144,49 +136,54 @@ public class MapClientContentTest { } @After - public void tearDown() throws Exception { - } + public void tearDown() throws Exception {} - /** - * Test that everything initializes correctly with an empty content provider - */ + /** Test that everything initializes correctly with an empty content provider */ @Test public void testCreateMapClientContent() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - verify(mMockSubscriptionManager).addSubscriptionInfoRecord(any(), any(), anyInt(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + verify(mMockSubscriptionManager) + .addSubscriptionInfoRecord( + any(), + any(), + anyInt(), + eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); Assert.assertEquals(0, mMockSmsContentProvider.mContentValues.size()); } - /** - * Test that a dirty database gets cleaned at startup. - */ + /** Test that a dirty database gets cleaned at startup. */ @Test public void testCleanDirtyDatabase() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); - verify(mMockSubscriptionManager).addSubscriptionInfoRecord(any(), any(), anyInt(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + mMapClientContent.storeMessage( + mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); + verify(mMockSubscriptionManager) + .addSubscriptionInfoRecord( + any(), + any(), + anyInt(), + eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); Assert.assertEquals(1, mMockSmsContentProvider.mContentValues.size()); mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); Assert.assertEquals(0, mMockSmsContentProvider.mContentValues.size()); } - /** - * Test inserting 2 SMS messages and then clearing out the database. - */ + /** Test inserting 2 SMS messages and then clearing out the database. */ @Test public void testStoreTwoSMS() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); - verify(mMockSubscriptionManager).addSubscriptionInfoRecord(any(), any(), anyInt(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + mMapClientContent.storeMessage( + mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); + verify(mMockSubscriptionManager) + .addSubscriptionInfoRecord( + any(), + any(), + anyInt(), + eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); Assert.assertEquals(1, mMockSmsContentProvider.mContentValues.size()); - mMapClientContent.storeMessage(mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); Assert.assertEquals(2, mMockSmsContentProvider.mContentValues.size()); Assert.assertEquals(0, mMockMmsContentProvider.mContentValues.size()); @@ -195,60 +192,66 @@ public class MapClientContentTest { Assert.assertEquals(0, mMockThreadContentProvider.mContentValues.size()); } - /** - * Test inserting 2 MMS messages and then clearing out the database. - */ + /** Test inserting 2 MMS messages and then clearing out the database. */ @Test public void testStoreTwoMMS() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); - verify(mMockSubscriptionManager).addSubscriptionInfoRecord(any(), any(), anyInt(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); + verify(mMockSubscriptionManager) + .addSubscriptionInfoRecord( + any(), + any(), + anyInt(), + eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); Assert.assertEquals(1, mMockMmsContentProvider.mContentValues.size()); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); Assert.assertEquals(2, mMockMmsContentProvider.mContentValues.size()); mMapClientContent.cleanUp(); Assert.assertEquals(0, mMockMmsContentProvider.mContentValues.size()); } - /** - * Test that SMS and MMS messages end up in their respective databases. - */ + /** Test that SMS and MMS messages end up in their respective databases. */ @Test public void testStoreOneSMSOneMMS() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); - verify(mMockSubscriptionManager).addSubscriptionInfoRecord(any(), any(), anyInt(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); + verify(mMockSubscriptionManager) + .addSubscriptionInfoRecord( + any(), + any(), + anyInt(), + eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); Assert.assertEquals(1, mMockMmsContentProvider.mContentValues.size()); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage2Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage2Handle, mTestMessage1Timestamp, MESSAGE_SEEN); Assert.assertEquals(2, mMockMmsContentProvider.mContentValues.size()); mMapClientContent.cleanUp(); Assert.assertEquals(0, mMockMmsContentProvider.mContentValues.size()); } - /** - * Test read status changed - */ + /** Test read status changed */ @Test public void testReadStatusChanged() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); - verify(mMockSubscriptionManager).addSubscriptionInfoRecord(any(), any(), anyInt(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); + verify(mMockSubscriptionManager) + .addSubscriptionInfoRecord( + any(), + any(), + anyInt(), + eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); Assert.assertEquals(1, mMockMmsContentProvider.mContentValues.size()); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); Assert.assertEquals(2, mMockMmsContentProvider.mContentValues.size()); mMapClientContent.markRead(mTestMessage1Handle); @@ -260,102 +263,94 @@ public class MapClientContentTest { /** * Test read status changed in local provider * - * Insert a message, and notify the observer about a change - * The cursor is configured to return messages marked as read - * Verify that the local change is observed and propagated to the remote + *

Insert a message, and notify the observer about a change The cursor is configured to + * return messages marked as read Verify that the local change is observed and propagated to the + * remote */ @Test public void testLocalReadStatusChanged() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); Assert.assertEquals(1, mMockMmsContentProvider.mContentValues.size()); mMapClientContent.mContentObserver.onChange(false); - verify(mCallbacks).onMessageStatusChanged(eq(mTestMessage1Handle), - eq(BluetoothMapClient.READ)); + verify(mCallbacks) + .onMessageStatusChanged(eq(mTestMessage1Handle), eq(BluetoothMapClient.READ)); } - /** - * Test if seen status is set to true in database for SMS - */ - @Test - public void testStoreSmsMessageWithSeenTrue_smsWrittenWithSeenTrue() { + /** Test if seen status is set to true in database for SMS */ + @Test + public void testStoreSmsMessageWithSeenTrue_smsWrittenWithSeenTrue() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); assertThat(mMockSmsContentProvider.mContentValues.size()).isEqualTo(1); ContentValues storedSMS = (ContentValues) mMockSmsContentProvider.mContentValues.values().toArray()[0]; assertThat(storedSMS.get(Sms.SEEN)).isEqualTo(MESSAGE_SEEN); + } - } - - /** - * Test if seen status is set to false in database for SMS - */ - @Test - public void testStoreSmsMessageWithSeenFalse_smsWrittenWithSeenFalse() { + /** Test if seen status is set to false in database for SMS */ + @Test + public void testStoreSmsMessageWithSeenFalse_smsWrittenWithSeenFalse() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_NOT_SEEN); + mMapClientContent.storeMessage( + mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_NOT_SEEN); assertThat(mMockSmsContentProvider.mContentValues.size()).isEqualTo(1); ContentValues storedSMS = (ContentValues) mMockSmsContentProvider.mContentValues.values().toArray()[0]; assertThat(storedSMS.get(Sms.SEEN)).isEqualTo(MESSAGE_NOT_SEEN); + } - } - - /** - * Test if seen status is set to true in database for MMS - */ - @Test - public void testStoreMmsMessageWithSeenTrue_mmsWrittenWithSeenTrue() { + /** Test if seen status is set to true in database for MMS */ + @Test + public void testStoreMmsMessageWithSeenTrue_mmsWrittenWithSeenTrue() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); assertThat(mMockMmsContentProvider.mContentValues.size()).isEqualTo(1); ContentValues storedMMS = (ContentValues) mMockMmsContentProvider.mContentValues.values().toArray()[0]; assertThat(storedMMS.get(Mms.SEEN)).isEqualTo(MESSAGE_SEEN); + } - } - - /** - * Test if seen status is set to false in database for MMS - */ - @Test - public void testStoreMmsMessageWithSeenFalse_mmsWrittenWithSeenFalse() { + /** Test if seen status is set to false in database for MMS */ + @Test + public void testStoreMmsMessageWithSeenFalse_mmsWrittenWithSeenFalse() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_NOT_SEEN); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_NOT_SEEN); assertThat(mMockMmsContentProvider.mContentValues.size()).isEqualTo(1); ContentValues storedMMS = (ContentValues) mMockMmsContentProvider.mContentValues.values().toArray()[0]; assertThat(storedMMS.get(Mms.SEEN)).isEqualTo(MESSAGE_NOT_SEEN); - - } + } /** * Test remote message deleted * - * Add a message to the database Simulate the message getting - * deleted on the phone Verify that the message is deleted locally + *

Add a message to the database Simulate the message getting deleted on the phone Verify + * that the message is deleted locally */ @Test public void testMessageDeleted() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); - verify(mMockSubscriptionManager).addSubscriptionInfoRecord(any(), any(), anyInt(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + mMapClientContent.storeMessage( + mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); + verify(mMockSubscriptionManager) + .addSubscriptionInfoRecord( + any(), + any(), + anyInt(), + eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); Assert.assertEquals(1, mMockSmsContentProvider.mContentValues.size()); // attempt to delete an invalid handle, nothing should be removed. mMapClientContent.deleteMessage(mTestMessage2Handle); @@ -369,32 +364,34 @@ public class MapClientContentTest { /** * Test read status changed in local provider * - * Insert a message, manually remove it and notify the observer about a change - * Verify that the local change is observed and propagated to the remote + *

Insert a message, manually remove it and notify the observer about a change Verify that + * the local change is observed and propagated to the remote */ @Test public void testLocalMessageDeleted() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - mMapClientContent.storeMessage(mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); - verify(mMockSubscriptionManager).addSubscriptionInfoRecord(any(), any(), anyInt(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + mMapClientContent.storeMessage( + mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); + verify(mMockSubscriptionManager) + .addSubscriptionInfoRecord( + any(), + any(), + anyInt(), + eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); Assert.assertEquals(1, mMockSmsContentProvider.mContentValues.size()); mMockSmsContentProvider.mContentValues.clear(); mMapClientContent.mContentObserver.onChange(false); - verify(mCallbacks).onMessageStatusChanged(eq(mTestMessage1Handle), - eq(BluetoothMapClient.DELETED)); + verify(mCallbacks) + .onMessageStatusChanged(eq(mTestMessage1Handle), eq(BluetoothMapClient.DELETED)); } /** - * Preconditions: - * - Create new {@link MapClientContent}, own phone number not initialized yet. + * Preconditions: - Create new {@link MapClientContent}, own phone number not initialized yet. * - * Actions: - * - Invoke {@link MapClientContent#setRemoteDeviceOwnNumber} with a non-null number. + *

Actions: - Invoke {@link MapClientContent#setRemoteDeviceOwnNumber} with a non-null + * number. * - * Outcome: - * - {@link MapClientContent#mPhoneNumber} should now store the number. + *

Outcome: - {@link MapClientContent#mPhoneNumber} should now store the number. */ @Test public void testSetRemoteDeviceOwnNumber() { @@ -407,9 +404,7 @@ public class MapClientContentTest { assertThat(mMapClientContent.mPhoneNumber).isEqualTo(testNumber); } - /** - * Test to validate that some poorly formatted messages don't crash. - */ + /** Test to validate that some poorly formatted messages don't crash. */ @Test public void testStoreBadMessage() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); @@ -417,15 +412,15 @@ public class MapClientContentTest { mTestMessage1.setBodyContent("HelloWorld"); mTestMessage1.setType(Bmessage.Type.SMS_GSM); mTestMessage1.setFolder("telecom/msg/sent"); - mMapClientContent.storeMessage(mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage1, mTestMessage1Handle, mTestMessage1Timestamp, MESSAGE_SEEN); mTestMessage2 = new Bmessage(); mTestMessage2.setBodyContent("HelloWorld"); mTestMessage2.setType(Bmessage.Type.MMS); mTestMessage2.setFolder("telecom/msg/inbox"); - mMapClientContent.storeMessage(mTestMessage2, mTestMessage2Handle, mTestMessage1Timestamp, - MESSAGE_SEEN); + mMapClientContent.storeMessage( + mTestMessage2, mTestMessage2Handle, mTestMessage1Timestamp, MESSAGE_SEEN); } /** @@ -435,14 +430,13 @@ public class MapClientContentTest { @Test public void testCleanUpRemoteException() { mMapClientContent = new MapClientContent(mMockContext, mCallbacks, mTestDevice); - doThrow(java.lang.NullPointerException.class).when(mMockSubscriptionManager) + doThrow(java.lang.NullPointerException.class) + .when(mMockSubscriptionManager) .removeSubscriptionInfoRecord(any(), anyInt()); mMapClientContent.cleanUp(); } - /** - * Test to validate old subscriptions are removed at startup. - */ + /** Test to validate old subscriptions are removed at startup. */ @Test public void testCleanUpAtStartup() { MapClientContent.clearAllContent(mMockContext); @@ -451,17 +445,15 @@ public class MapClientContentTest { when(mMockSubscription.getSubscriptionType()) .thenReturn(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM); MapClientContent.clearAllContent(mMockContext); - verify(mMockSubscriptionManager).removeSubscriptionInfoRecord(any(), - eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); + verify(mMockSubscriptionManager) + .removeSubscriptionInfoRecord( + any(), eq(SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM)); } - /** - * Test to validate that cleaning content does not crash when no subscription are available. - */ + /** Test to validate that cleaning content does not crash when no subscription are available. */ @Test public void testCleanUpWithNoSubscriptions() { - when(mMockSubscriptionManager.getActiveSubscriptionInfoList()) - .thenReturn(null); + when(mMockSubscriptionManager.getActiveSubscriptionInfoList()).thenReturn(null); MapClientContent.clearAllContent(mMockContext); } @@ -547,6 +539,7 @@ public class MapClientContentTest { public class FakeContentProvider extends MockContentProvider { Map mContentValues = new HashMap<>(); + FakeContentProvider(Context context) { super(context); } @@ -567,7 +560,7 @@ public class MapClientContentTest { Log.i(TAG, "URI = " + uri); if (uri.equals(Mms.Inbox.CONTENT_URI)) uri = Mms.CONTENT_URI; Uri returnUri = Uri.withAppendedPath(uri, String.valueOf(mContentValues.size() + 1)); - //only store top level message parts + // only store top level message parts if (uri.equals(Sms.Inbox.CONTENT_URI) || uri.equals(Mms.CONTENT_URI)) { Log.i(TAG, "adding content" + values); mContentValues.put(returnUri, values); @@ -577,7 +570,11 @@ public class MapClientContentTest { } @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + public Cursor query( + Uri uri, + String[] projection, + String selection, + String[] selectionArgs, String sortOrder) { Cursor cursor = Mockito.mock(Cursor.class); diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java index e9e4fb7014b..01c5d0c26bc 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java @@ -15,7 +15,6 @@ */ package com.android.bluetooth.mapclient; - import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothAdapter; @@ -41,8 +40,7 @@ public class MapClientServiceBinderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private MapClientService mService; + @Mock private MapClientService mService; BluetoothDevice mRemoteDevice; @@ -141,4 +139,4 @@ public class MapClientServiceBinderTest { public void cleanUp_doesNotCrash() { mBinder.cleanup(); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java index c24df8b84d3..b327a6b5f70 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java @@ -123,7 +123,8 @@ public class MapClientServiceTest { public void setConnectionPolicy() { int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; when(mDatabaseManager.setProfileConnectionPolicy( - mRemoteDevice, BluetoothProfile.MAP_CLIENT, connectionPolicy)).thenReturn(true); + mRemoteDevice, BluetoothProfile.MAP_CLIENT, connectionPolicy)) + .thenReturn(true); assertThat(mService.setConnectionPolicy(mRemoteDevice, connectionPolicy)).isTrue(); } @@ -132,7 +133,8 @@ public class MapClientServiceTest { public void getConnectionPolicy() { int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; when(mDatabaseManager.getProfileConnectionPolicy( - mRemoteDevice, BluetoothProfile.MAP_CLIENT)).thenReturn(connectionPolicy); + mRemoteDevice, BluetoothProfile.MAP_CLIENT)) + .thenReturn(connectionPolicy); assertThat(mService.getConnectionPolicy(mRemoteDevice)).isEqualTo(connectionPolicy); } @@ -141,7 +143,8 @@ public class MapClientServiceTest { public void connect_whenPolicyIsForbidden_returnsFalse() { int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; when(mDatabaseManager.getProfileConnectionPolicy( - mRemoteDevice, BluetoothProfile.MAP_CLIENT)).thenReturn(connectionPolicy); + mRemoteDevice, BluetoothProfile.MAP_CLIENT)) + .thenReturn(connectionPolicy); assertThat(mService.connect(mRemoteDevice)).isFalse(); } @@ -150,7 +153,8 @@ public class MapClientServiceTest { public void connect_whenPolicyIsAllowed_returnsTrue() { int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; when(mDatabaseManager.getProfileConnectionPolicy( - mRemoteDevice, BluetoothProfile.MAP_CLIENT)).thenReturn(connectionPolicy); + mRemoteDevice, BluetoothProfile.MAP_CLIENT)) + .thenReturn(connectionPolicy); assertThat(mService.connect(mRemoteDevice)).isTrue(); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java index 2c18e366ff5..d7145d1e588 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java @@ -16,7 +16,6 @@ package com.android.bluetooth.mapclient; - import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.eq; @@ -118,8 +117,7 @@ public class MapClientStateMachineTest { private VCardEntry mOriginator; - @Rule - public final ServiceTestRule mServiceRule = new ServiceTestRule(); + @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule(); private BluetoothAdapter mAdapter; private MceStateMachine mMceStateMachine = null; private BluetoothDevice mTestDevice; @@ -128,43 +126,31 @@ public class MapClientStateMachineTest { private ArgumentCaptor mIntentArgument = ArgumentCaptor.forClass(Intent.class); @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private AdapterService mAdapterService; - @Mock - private DatabaseManager mDatabaseManager; - @Mock - private MapClientService mMockMapClientService; - @Mock - private MapClientContent mMockDatabase; + @Mock private AdapterService mAdapterService; + @Mock private DatabaseManager mDatabaseManager; + @Mock private MapClientService mMockMapClientService; + @Mock private MapClientContent mMockDatabase; private MockContentResolver mMockContentResolver; private MockSmsContentProvider mMockContentProvider; - @Mock - private TelephonyManager mMockTelephonyManager; + @Mock private TelephonyManager mMockTelephonyManager; - @Mock - private MasClient mMockMasClient; + @Mock private MasClient mMockMasClient; - @Mock - private RequestPushMessage mMockRequestPushMessage; + @Mock private RequestPushMessage mMockRequestPushMessage; - @Mock - private SubscriptionManager mMockSubscriptionManager; + @Mock private SubscriptionManager mMockSubscriptionManager; private static final String TEST_OWN_PHONE_NUMBER = "555-1234"; - @Mock - private RequestGetMessagesListingForOwnNumber mMockRequestOwnNumberCompletedWithNumber; - @Mock - private RequestGetMessagesListingForOwnNumber mMockRequestOwnNumberIncompleteSearch; - @Mock - private RequestGetMessage mMockRequestGetMessage; - @Mock - private RequestGetMessagesListing mMockRequestGetMessagesListing; + @Mock private RequestGetMessagesListingForOwnNumber mMockRequestOwnNumberCompletedWithNumber; + @Mock private RequestGetMessagesListingForOwnNumber mMockRequestOwnNumberIncompleteSearch; + @Mock private RequestGetMessage mMockRequestGetMessage; + @Mock private RequestGetMessagesListing mMockRequestGetMessagesListing; private static final Correspondence GET_FOLDER_NAME = Correspondence.transforming( - MapClientStateMachineTest::getFolderNameFromRequestGetMessagesListing, - "has folder name of"); + MapClientStateMachineTest::getFolderNameFromRequestGetMessagesListing, + "has folder name of"); private static final String ACTION_MESSAGE_SENT = "com.android.bluetooth.mapclient.MapClientStateMachineTest.action.MESSAGE_SENT"; @@ -229,8 +215,9 @@ public class MapClientStateMachineTest { mTestDevice = mAdapter.getRemoteDevice("00:01:02:03:04:05"); when(mMockMasClient.makeRequest(any(Request.class))).thenReturn(true); - mMceStateMachine = new MceStateMachine(mMockMapClientService, mTestDevice, mMockMasClient, - mMockDatabase); + mMceStateMachine = + new MceStateMachine( + mMockMapClientService, mTestDevice, mMockMasClient, mMockDatabase); TestUtils.waitForLooperToFinishScheduledTask(mMceStateMachine.getHandler().getLooper()); Assert.assertNotNull(mMceStateMachine); if (Looper.myLooper() == null) { @@ -239,8 +226,8 @@ public class MapClientStateMachineTest { mHandler = new Handler(); when(mMockRequestOwnNumberCompletedWithNumber.isSearchCompleted()).thenReturn(true); - when(mMockRequestOwnNumberCompletedWithNumber.getOwnNumber()).thenReturn( - TEST_OWN_PHONE_NUMBER); + when(mMockRequestOwnNumberCompletedWithNumber.getOwnNumber()) + .thenReturn(TEST_OWN_PHONE_NUMBER); when(mMockRequestOwnNumberIncompleteSearch.isSearchCompleted()).thenReturn(false); when(mMockRequestOwnNumberIncompleteSearch.getOwnNumber()).thenReturn(null); @@ -249,8 +236,8 @@ public class MapClientStateMachineTest { when(mMockRequestGetMessage.getMessage()).thenReturn(mTestIncomingSmsBmessage); when(mMockRequestGetMessage.getHandle()).thenReturn(mTestMessageSmsHandle); - when(mMockMapClientService.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn( - mMockTelephonyManager); + when(mMockMapClientService.getSystemService(Context.TELEPHONY_SERVICE)) + .thenReturn(mMockTelephonyManager); when(mMockTelephonyManager.isSmsCapable()).thenReturn(false); // Set up receiver for 'Sent' and 'Delivered' PendingIntents @@ -274,9 +261,7 @@ public class MapClientStateMachineTest { mTargetContext.unregisterReceiver(mSentDeliveryReceiver); } - /** - * Test that default state is STATE_CONNECTING - */ + /** Test that default state is STATE_CONNECTING */ @Test public void testDefaultConnectingState() { Log.i(TAG, "in testDefaultConnectingState"); @@ -297,16 +282,15 @@ public class MapClientStateMachineTest { // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_DISCONNECTED - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, mMceStateMachine.getState()); } - /** - * Test transition from STATE_CONNECTING --> (receive MSG_MAS_CONNECTED) --> STATE_CONNECTED - */ + /** Test transition from STATE_CONNECTING --> (receive MSG_MAS_CONNECTED) --> STATE_CONNECTED */ @Test public void testStateTransitionFromConnectingToConnected() { Log.i(TAG, "in testStateTransitionFromConnectingToConnected"); @@ -318,10 +302,11 @@ public class MapClientStateMachineTest { // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); } @@ -340,25 +325,25 @@ public class MapClientStateMachineTest { // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_DISCONNECTED); mMceStateMachine.sendMessage(msg); - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(4)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(4)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, mMceStateMachine.getState()); } - /** - * Test receiving an empty event report - */ + /** Test receiving an empty event report */ @Test public void testReceiveEmptyEvent() { setupSdpRecordReceipt(); @@ -368,10 +353,11 @@ public class MapClientStateMachineTest { // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); // Send an empty notification event, verify the mMceStateMachine is still connected @@ -380,9 +366,7 @@ public class MapClientStateMachineTest { Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); } - /** - * Test set message status - */ + /** Test set message status */ @Test public void testSetMessageStatus() { setupSdpRecordReceipt(); @@ -392,48 +376,50 @@ public class MapClientStateMachineTest { // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); Assert.assertTrue( mMceStateMachine.setMessageStatus("123456789AB", BluetoothMapClient.READ)); } - /** - * Test disconnect - */ + /** Test disconnect */ @Test public void testDisconnect() { setupSdpRecordReceipt(); - doAnswer(invocation -> { - mMceStateMachine.sendMessage(MceStateMachine.MSG_MAS_DISCONNECTED); - return null; - }).when(mMockMasClient).shutdown(); + doAnswer( + invocation -> { + mMceStateMachine.sendMessage(MceStateMachine.MSG_MAS_DISCONNECTED); + return null; + }) + .when(mMockMasClient) + .shutdown(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); mMceStateMachine.disconnect(); - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(4)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(4)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, mMceStateMachine.getState()); } - /** - * Test disconnect timeout - */ + /** Test disconnect timeout */ @Test public void testDisconnectTimeout() { setupSdpRecordReceipt(); @@ -443,29 +429,30 @@ public class MapClientStateMachineTest { // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); mMceStateMachine.disconnect(); - verify(mMockMapClientService, - after(DISCONNECT_TIMEOUT / 2).times(3)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, after(DISCONNECT_TIMEOUT / 2).times(3)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTING, mMceStateMachine.getState()); - verify(mMockMapClientService, - timeout(DISCONNECT_TIMEOUT).times(4)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(DISCONNECT_TIMEOUT).times(4)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, mMceStateMachine.getState()); } - /** - * Test sending a message to a phone - */ + /** Test sending a message to a phone */ @Test public void testSendSMSMessageToPhone() { setupSdpRecordReceipt(); @@ -483,9 +470,7 @@ public class MapClientStateMachineTest { .makeRequest(any(RequestPushMessage.class)); } - /** - * Test sending a message to an email - */ + /** Test sending a message to an email */ @Test public void testSendSMSMessageToEmail() { setupSdpRecordReceipt(); @@ -503,9 +488,7 @@ public class MapClientStateMachineTest { .makeRequest(any(RequestPushMessage.class)); } - /** - * Test message sent successfully - */ + /** Test message sent successfully */ @Test public void testSMSMessageSent() { setupSdpRecordReceipt(); @@ -518,40 +501,46 @@ public class MapClientStateMachineTest { new RequestPushMessage(FOLDER_SENT, mTestIncomingSmsBmessage, null, false, false); when(mMockRequestPushMessage.getMsgHandle()).thenReturn(mTestMessageSmsHandle); when(mMockRequestPushMessage.getBMsg()).thenReturn(mTestIncomingSmsBmessage); - Message msgSent = Message.obtain(mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestPushMessage); + Message msgSent = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestPushMessage); mMceStateMachine.sendMessage(msgSent); TestUtils.waitForLooperToFinishScheduledTask(mMceStateMachine.getHandler().getLooper()); - verify(mMockDatabase, times(1)).storeMessage(eq(mTestIncomingSmsBmessage), - eq(mTestMessageSmsHandle), any(), eq(MESSAGE_SEEN)); + verify(mMockDatabase, times(1)) + .storeMessage( + eq(mTestIncomingSmsBmessage), + eq(mTestMessageSmsHandle), + any(), + eq(MESSAGE_SEEN)); } /** - * Preconditions: - * - In {@code STATE_CONNECTED}. - * - {@code MSG_SEARCH_OWN_NUMBER_TIMEOUT} has been set. - * - Next stage of connection process has NOT begun, i.e.: - * - Request for Notification Registration not sent - * - Request for MessageListing of SENT folder not sent - * - Request for MessageListing of INBOX folder not sent + * Preconditions: - In {@code STATE_CONNECTED}. - {@code MSG_SEARCH_OWN_NUMBER_TIMEOUT} has been + * set. - Next stage of connection process has NOT begun, i.e.: - Request for Notification + * Registration not sent - Request for MessageListing of SENT folder not sent - Request for + * MessageListing of INBOX folder not sent */ private void testGetOwnNumber_setup() { testStateTransitionFromConnectingToConnected(); - verify(mMockMasClient, after(ASYNC_CALL_TIMEOUT_MILLIS).never()).makeRequest( - any(RequestSetNotificationRegistration.class)); + verify(mMockMasClient, after(ASYNC_CALL_TIMEOUT_MILLIS).never()) + .makeRequest(any(RequestSetNotificationRegistration.class)); verify(mMockMasClient, never()).makeRequest(any(RequestGetMessagesListing.class)); - assertThat(mMceStateMachine.getHandler().hasMessages( - MceStateMachine.MSG_SEARCH_OWN_NUMBER_TIMEOUT)).isTrue(); + assertThat( + mMceStateMachine + .getHandler() + .hasMessages(MceStateMachine.MSG_SEARCH_OWN_NUMBER_TIMEOUT)) + .isTrue(); } /** * Assert whether the next stage of connection process has begun, i.e., whether the following - * {@link Request} are sent or not: - * - Request for Notification Registration, - * - Request for MessageListing of SENT folder (to start downloading), - * - Request for MessageListing of INBOX folder (to start downloading). + * {@link Request} are sent or not: - Request for Notification Registration, - Request for + * MessageListing of SENT folder (to start downloading), - Request for MessageListing of INBOX + * folder (to start downloading). */ private void testGetOwnNumber_assertNextStageStarted(boolean hasStarted) { if (hasStarted) { @@ -564,167 +553,187 @@ public class MapClientStateMachineTest { // {@link Request} subtypes; not all of them will be {@link // RequestGetMessagesListing}. List capturedRequests = requestCaptor.getAllValues(); - assertThat(capturedRequests).comparingElementsUsing(GET_FOLDER_NAME).contains( - MceStateMachine.FOLDER_INBOX); - assertThat(capturedRequests).comparingElementsUsing(GET_FOLDER_NAME).contains( - MceStateMachine.FOLDER_SENT); + assertThat(capturedRequests) + .comparingElementsUsing(GET_FOLDER_NAME) + .contains(MceStateMachine.FOLDER_INBOX); + assertThat(capturedRequests) + .comparingElementsUsing(GET_FOLDER_NAME) + .contains(MceStateMachine.FOLDER_SENT); } else { - verify(mMockMasClient, never()).makeRequest( - any(RequestSetNotificationRegistration.class)); + verify(mMockMasClient, never()) + .makeRequest(any(RequestSetNotificationRegistration.class)); verify(mMockMasClient, never()).makeRequest(any(RequestGetMessagesListing.class)); } } /** - * Preconditions: - * - See {@link testGetOwnNumber_setup}. + * Preconditions: - See {@link testGetOwnNumber_setup}. * - * Actions: - * - Send a {@code MSG_MAS_REQUEST_COMPLETED} with a {@link - * RequestGetMessagesListingForOwnNumber} object that has completed its search. + *

Actions: - Send a {@code MSG_MAS_REQUEST_COMPLETED} with a {@link + * RequestGetMessagesListingForOwnNumber} object that has completed its search. * - * Outcome: - * - {@code MSG_SEARCH_OWN_NUMBER_TIMEOUT} has been cancelled. - * - Next stage of connection process has begun, i.e.: - * - Request for Notification Registration is made. - * - Request for MessageListing of SENT folder is made (to start downloading). - * - Request for MessageListing of INBOX folder is made (to start downloading). + *

Outcome: - {@code MSG_SEARCH_OWN_NUMBER_TIMEOUT} has been cancelled. - Next stage of + * connection process has begun, i.e.: - Request for Notification Registration is made. - + * Request for MessageListing of SENT folder is made (to start downloading). - Request for + * MessageListing of INBOX folder is made (to start downloading). */ @Test public void testGetOwnNumberCompleted() { testGetOwnNumber_setup(); - Message requestCompletedMsg = Message.obtain(mHandler, - MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestOwnNumberCompletedWithNumber); + Message requestCompletedMsg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestOwnNumberCompletedWithNumber); mMceStateMachine.sendMessage(requestCompletedMsg); - verify(mMockMasClient, after(ASYNC_CALL_TIMEOUT_MILLIS).never()).makeRequest( - eq(mMockRequestOwnNumberCompletedWithNumber)); - assertThat(mMceStateMachine.getHandler().hasMessages( - MceStateMachine.MSG_SEARCH_OWN_NUMBER_TIMEOUT)).isFalse(); + verify(mMockMasClient, after(ASYNC_CALL_TIMEOUT_MILLIS).never()) + .makeRequest(eq(mMockRequestOwnNumberCompletedWithNumber)); + assertThat( + mMceStateMachine + .getHandler() + .hasMessages(MceStateMachine.MSG_SEARCH_OWN_NUMBER_TIMEOUT)) + .isFalse(); testGetOwnNumber_assertNextStageStarted(true); } /** - * Preconditions: - * - See {@link testGetOwnNumber_setup}. + * Preconditions: - See {@link testGetOwnNumber_setup}. * - * Actions: - * - Send a {@code MSG_SEARCH_OWN_NUMBER_TIMEOUT}. + *

Actions: - Send a {@code MSG_SEARCH_OWN_NUMBER_TIMEOUT}. * - * Outcome: - * - {@link MasClient#abortRequest} invoked on a {@link RequestGetMessagesListingForOwnNumber}. - * - Any existing {@code MSG_MAS_REQUEST_COMPLETED} (corresponding to a - * {@link RequestGetMessagesListingForOwnNumber}) has been dropped. - * - Next stage of connection process has begun, i.e.: - * - Request for Notification Registration is made. - * - Request for MessageListing of SENT folder is made (to start downloading). - * - Request for MessageListing of INBOX folder is made (to start downloading). + *

Outcome: - {@link MasClient#abortRequest} invoked on a {@link + * RequestGetMessagesListingForOwnNumber}. - Any existing {@code MSG_MAS_REQUEST_COMPLETED} + * (corresponding to a {@link RequestGetMessagesListingForOwnNumber}) has been dropped. - Next + * stage of connection process has begun, i.e.: - Request for Notification Registration is made. + * - Request for MessageListing of SENT folder is made (to start downloading). - Request for + * MessageListing of INBOX folder is made (to start downloading). */ @Test public void testGetOwnNumberTimedOut() { testGetOwnNumber_setup(); - Message timeoutMsg = Message.obtain(mHandler, - MceStateMachine.MSG_SEARCH_OWN_NUMBER_TIMEOUT, - mMockRequestOwnNumberIncompleteSearch); + Message timeoutMsg = + Message.obtain( + mHandler, + MceStateMachine.MSG_SEARCH_OWN_NUMBER_TIMEOUT, + mMockRequestOwnNumberIncompleteSearch); mMceStateMachine.sendMessage(timeoutMsg); - verify(mMockMasClient, after(ASYNC_CALL_TIMEOUT_MILLIS)).abortRequest( - mMockRequestOwnNumberIncompleteSearch); - assertThat(mMceStateMachine.getHandler().hasMessages( - MceStateMachine.MSG_MAS_REQUEST_COMPLETED)).isFalse(); + verify(mMockMasClient, after(ASYNC_CALL_TIMEOUT_MILLIS)) + .abortRequest(mMockRequestOwnNumberIncompleteSearch); + assertThat( + mMceStateMachine + .getHandler() + .hasMessages(MceStateMachine.MSG_MAS_REQUEST_COMPLETED)) + .isFalse(); testGetOwnNumber_assertNextStageStarted(true); } /** - * Preconditions: - * - See {@link testGetOwnNumber_setup}. + * Preconditions: - See {@link testGetOwnNumber_setup}. * - * Actions: - * - Send a {@code MSG_MAS_REQUEST_COMPLETED} with a {@link - * RequestGetMessagesListingForOwnNumber} object that has not completed its search. + *

Actions: - Send a {@code MSG_MAS_REQUEST_COMPLETED} with a {@link + * RequestGetMessagesListingForOwnNumber} object that has not completed its search. * - * Outcome: - * - {@link Request} made to continue searching for own number (using existing/same - * {@link Request}). - * - {@code MSG_SEARCH_OWN_NUMBER_TIMEOUT} has not been cancelled. - * - Next stage of connection process has not begun, i.e.: - * - No Request for Notification Registration, - * - No Request for MessageListing of SENT folder is made (to start downloading), - * - No Request for MessageListing of INBOX folder is made (to start downloading). + *

Outcome: - {@link Request} made to continue searching for own number (using existing/same + * {@link Request}). - {@code MSG_SEARCH_OWN_NUMBER_TIMEOUT} has not been cancelled. - Next + * stage of connection process has not begun, i.e.: - No Request for Notification Registration, + * - No Request for MessageListing of SENT folder is made (to start downloading), - No Request + * for MessageListing of INBOX folder is made (to start downloading). */ @Test public void testGetOwnNumberIncomplete() { testGetOwnNumber_setup(); - Message requestIncompleteMsg = Message.obtain(mHandler, - MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestOwnNumberIncompleteSearch); + Message requestIncompleteMsg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestOwnNumberIncompleteSearch); mMceStateMachine.sendMessage(requestIncompleteMsg); - verify(mMockMasClient, after(ASYNC_CALL_TIMEOUT_MILLIS)).makeRequest( - eq(mMockRequestOwnNumberIncompleteSearch)); - assertThat(mMceStateMachine.getHandler().hasMessages( - MceStateMachine.MSG_SEARCH_OWN_NUMBER_TIMEOUT)).isTrue(); + verify(mMockMasClient, after(ASYNC_CALL_TIMEOUT_MILLIS)) + .makeRequest(eq(mMockRequestOwnNumberIncompleteSearch)); + assertThat( + mMceStateMachine + .getHandler() + .hasMessages(MceStateMachine.MSG_SEARCH_OWN_NUMBER_TIMEOUT)) + .isTrue(); testGetOwnNumber_assertNextStageStarted(false); } - /** - * Test seen status set for new SMS - */ - @Test - public void testReceivedNewSms_messageStoredAsUnseen() { + /** Test seen status set for new SMS */ + @Test + public void testReceivedNewSms_messageStoredAsUnseen() { setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); - //verifying that state machine is in the Connected state - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + // verifying that state machine is in the Connected state + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); String dateTime = new ObexTime(Instant.now()).toString(); - EventReport event = createNewEventReport("NewMessage", dateTime, mTestMessageSmsHandle, - "telecom/msg/inbox", null, "SMS_GSM"); + EventReport event = + createNewEventReport( + "NewMessage", + dateTime, + mTestMessageSmsHandle, + "telecom/msg/inbox", + null, + "SMS_GSM"); mMceStateMachine.receiveEvent(event); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockMasClient, times(1)).makeRequest - (any(RequestGetMessage.class)); + verify(mMockMasClient, times(1)).makeRequest(any(RequestGetMessage.class)); - msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestGetMessage); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestGetMessage); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockDatabase, times(1)).storeMessage(eq(mTestIncomingSmsBmessage), - eq(mTestMessageSmsHandle), any(), eq(MESSAGE_NOT_SEEN)); - } + verify(mMockDatabase, times(1)) + .storeMessage( + eq(mTestIncomingSmsBmessage), + eq(mTestMessageSmsHandle), + any(), + eq(MESSAGE_NOT_SEEN)); + } - /** - * Test seen status set for new MMS - */ - @Test - public void testReceivedNewMms_messageStoredAsUnseen() { + /** Test seen status set for new MMS */ + @Test + public void testReceivedNewMms_messageStoredAsUnseen() { setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); - //verifying that state machine is in the Connected state - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + // verifying that state machine is in the Connected state + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); String dateTime = new ObexTime(Instant.now()).toString(); - EventReport event = createNewEventReport("NewMessage", dateTime, mTestMessageMmsHandle, - "telecom/msg/inbox", null, "MMS"); + EventReport event = + createNewEventReport( + "NewMessage", + dateTime, + mTestMessageMmsHandle, + "telecom/msg/inbox", + null, + "MMS"); when(mMockRequestGetMessage.getMessage()).thenReturn(mTestIncomingMmsBmessage); when(mMockRequestGetMessage.getHandle()).thenReturn(mTestMessageMmsHandle); @@ -732,81 +741,91 @@ public class MapClientStateMachineTest { mMceStateMachine.receiveEvent(event); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockMasClient, times(1)).makeRequest - (any(RequestGetMessage.class)); + verify(mMockMasClient, times(1)).makeRequest(any(RequestGetMessage.class)); - msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestGetMessage); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestGetMessage); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockDatabase, times(1)).storeMessage(eq(mTestIncomingMmsBmessage), - eq(mTestMessageMmsHandle), any(), eq(MESSAGE_NOT_SEEN)); - } + verify(mMockDatabase, times(1)) + .storeMessage( + eq(mTestIncomingMmsBmessage), + eq(mTestMessageMmsHandle), + any(), + eq(MESSAGE_NOT_SEEN)); + } - /** - * Test seen status set in database on initial download - */ - @Test - public void testDownloadExistingSms_messageStoredAsSeen() { + /** Test seen status set in database on initial download */ + @Test + public void testDownloadExistingSms_messageStoredAsSeen() { setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); - com.android.bluetooth.mapclient.Message testMessageListingSms = createNewMessage("SMS_GSM", - mTestMessageSmsHandle); + com.android.bluetooth.mapclient.Message testMessageListingSms = + createNewMessage("SMS_GSM", mTestMessageSmsHandle); ArrayList messageListSms = new ArrayList<>(); messageListSms.add(testMessageListingSms); when(mMockRequestGetMessagesListing.getList()).thenReturn(messageListSms); - msg = Message.obtain(mHandler, MceStateMachine.MSG_GET_MESSAGE_LISTING, - MceStateMachine.FOLDER_INBOX); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_GET_MESSAGE_LISTING, + MceStateMachine.FOLDER_INBOX); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockMasClient, times(1)).makeRequest(any( - RequestGetMessagesListing.class)); + verify(mMockMasClient, times(1)).makeRequest(any(RequestGetMessagesListing.class)); - msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestGetMessagesListing); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestGetMessagesListing); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockMasClient, times(1)).makeRequest(any( - RequestGetMessage.class)); + verify(mMockMasClient, times(1)).makeRequest(any(RequestGetMessage.class)); - msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestGetMessage); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestGetMessage); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockDatabase, times(1)).storeMessage(any(), any(), - any(), eq(MESSAGE_SEEN)); - } + verify(mMockDatabase, times(1)).storeMessage(any(), any(), any(), eq(MESSAGE_SEEN)); + } - /** - * Test seen status set in database on initial download - */ - @Test - public void testDownloadExistingMms_messageStoredAsSeen() { + /** Test seen status set in database on initial download */ + @Test + public void testDownloadExistingMms_messageStoredAsSeen() { setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); - com.android.bluetooth.mapclient.Message testMessageListingMms = createNewMessage("MMS", - mTestMessageMmsHandle); + com.android.bluetooth.mapclient.Message testMessageListingMms = + createNewMessage("MMS", mTestMessageMmsHandle); ArrayList messageListMms = new ArrayList<>(); messageListMms.add(testMessageListingMms); @@ -814,59 +833,69 @@ public class MapClientStateMachineTest { when(mMockRequestGetMessage.getHandle()).thenReturn(mTestMessageMmsHandle); when(mMockRequestGetMessagesListing.getList()).thenReturn(messageListMms); - msg = Message.obtain(mHandler, MceStateMachine.MSG_GET_MESSAGE_LISTING, - MceStateMachine.FOLDER_INBOX); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_GET_MESSAGE_LISTING, + MceStateMachine.FOLDER_INBOX); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockMasClient, times(1)).makeRequest(any( - RequestGetMessagesListing.class)); + verify(mMockMasClient, times(1)).makeRequest(any(RequestGetMessagesListing.class)); - msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestGetMessagesListing); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestGetMessagesListing); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockMasClient, times(1)).makeRequest(any( - RequestGetMessage.class)); + verify(mMockMasClient, times(1)).makeRequest(any(RequestGetMessage.class)); - msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestGetMessage); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestGetMessage); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockDatabase, times(1)).storeMessage(any(), any(), - any(), eq(MESSAGE_SEEN)); - } + verify(mMockDatabase, times(1)).storeMessage(any(), any(), any(), eq(MESSAGE_SEEN)); + } - /** - * Test receiving a new message notification. - */ + /** Test receiving a new message notification. */ @Test public void testReceiveNewMessageNotification() { setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); // Receive a new message notification. String dateTime = new ObexTime(Instant.now()).toString(); - EventReport event = createNewEventReport("NewMessage", dateTime, mTestMessageSmsHandle, - "telecom/msg/inbox", null, "SMS_GSM"); + EventReport event = + createNewEventReport( + "NewMessage", + dateTime, + mTestMessageSmsHandle, + "telecom/msg/inbox", + null, + "SMS_GSM"); Message notificationMessage = - Message.obtain(mHandler, MceStateMachine.MSG_NOTIFICATION, (Object)event); + Message.obtain(mHandler, MceStateMachine.MSG_NOTIFICATION, (Object) event); mMceStateMachine.getCurrentState().processMessage(notificationMessage); - verify(mMockMasClient, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) - .makeRequest(any(RequestGetMessage.class)); + verify(mMockMasClient, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) + .makeRequest(any(RequestGetMessage.class)); MceStateMachine.MessageMetadata messageMetadata = mMceStateMachine.mMessages.get(mTestMessageSmsHandle); @@ -882,42 +911,51 @@ public class MapClientStateMachineTest { Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); - //verifying that state machine is in the Connected state - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + // verifying that state machine is in the Connected state + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); String dateTime = new ObexTime(Instant.now()).toString(); - EventReport event = createNewEventReport("NewMessage", dateTime, mTestMessageSmsHandle, - "telecom/msg/inbox", null, "SMS_GSM"); + EventReport event = + createNewEventReport( + "NewMessage", + dateTime, + mTestMessageSmsHandle, + "telecom/msg/inbox", + null, + "SMS_GSM"); mMceStateMachine.receiveEvent(event); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockMasClient, times(1)).makeRequest - (any(RequestGetMessage.class)); + verify(mMockMasClient, times(1)).makeRequest(any(RequestGetMessage.class)); - msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, - mMockRequestGetMessage); + msg = + Message.obtain( + mHandler, + MceStateMachine.MSG_MAS_REQUEST_COMPLETED, + mMockRequestGetMessage); mMceStateMachine.sendMessage(msg); TestUtils.waitForLooperToBeIdle(mMceStateMachine.getHandler().getLooper()); - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)).sendBroadcast( - mIntentArgument.capture(), - eq(android.Manifest.permission.RECEIVE_SMS)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) + .sendBroadcast( + mIntentArgument.capture(), eq(android.Manifest.permission.RECEIVE_SMS)); Assert.assertNull(mIntentArgument.getValue().getPackage()); } @Test public void testSdpBusyWhileConnecting_sdpRetried() { // Perform first part of MAP connection logic. - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mMceStateMachine.getState()); // Send SDP Failed with status "busy" @@ -931,20 +969,22 @@ public class MapClientStateMachineTest { mMceStateMachine.sendMessage(msg); // Verify we move into the connected state - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); } @Test public void testSdpBusyWhileConnectingAndRetryResultsReceivedAfterTimeout_resultsIgnored() { // Perform first part of MAP connection logic. - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mMceStateMachine.getState()); // Send SDP Failed with status "busy" @@ -956,13 +996,13 @@ public class MapClientStateMachineTest { mMceStateMachine.sendMessage(msg); // Verify we move into the disconnecting state - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTING); - // Send successful SDP record, then send MAS Client connected SdpMasRecord record = new SdpMasRecord(1, 1, 1, 1, 1, 1, "MasRecord"); mMceStateMachine.sendSdpResult(MceStateMachine.SDP_SUCCESS, record); @@ -974,52 +1014,53 @@ public class MapClientStateMachineTest { @Test public void testSdpFailedWithNoRecordWhileConnecting_deviceDisconnected() { // Perform first part of MAP connection logic. - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mMceStateMachine.getState()); // Send SDP process success with no record found mMceStateMachine.sendSdpResult(MceStateMachine.SDP_SUCCESS, null); // Verify we move into the disconnecting state - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTING); } @Test public void testSdpOrganicFailure_deviceDisconnected() { // Perform first part of MAP connection logic. - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mMceStateMachine.getState()); // Send SDP Failed entirely mMceStateMachine.sendSdpResult(MceStateMachine.SDP_FAILED, null); - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTING); } /** - * Preconditions: - * - In {@code STATE_CONNECTED}. + * Preconditions: - In {@code STATE_CONNECTED}. * - * Actions: - * - {@link #sendMapMessage} with 'Sent' {@link PendingIntents}. - * - {@link #receiveEvent} of type {@link SENDING_SUCCESS}. + *

Actions: - {@link #sendMapMessage} with 'Sent' {@link PendingIntents}. - {@link + * #receiveEvent} of type {@link SENDING_SUCCESS}. * - * Outcome: - * - SENT_STATUS Intent was broadcast with 'Success' result code. + *

Outcome: - SENT_STATUS Intent was broadcast with 'Success' result code. */ @Test public void testSendMapMessageSentPendingIntent_notifyStatusSuccess() { @@ -1032,15 +1073,12 @@ public class MapClientStateMachineTest { } /** - * Preconditions: - * - In {@code STATE_CONNECTED}. + * Preconditions: - In {@code STATE_CONNECTED}. * - * Actions: - * - {@link #sendMapMessage} with 'Delivery' {@link PendingIntents}. - * - {@link #receiveEvent} of type {@link DELIVERY_SUCCESS}. + *

Actions: - {@link #sendMapMessage} with 'Delivery' {@link PendingIntents}. - {@link + * #receiveEvent} of type {@link DELIVERY_SUCCESS}. * - * Outcome: - * - DELIVERY_STATUS Intent was broadcast with 'Success' result code. + *

Outcome: - DELIVERY_STATUS Intent was broadcast with 'Success' result code. */ @Test public void testSendMapMessageDeliveryPendingIntent_notifyStatusSuccess() { @@ -1053,16 +1091,13 @@ public class MapClientStateMachineTest { } /** - * Preconditions: - * - In {@code STATE_CONNECTED}. + * Preconditions: - In {@code STATE_CONNECTED}. * - * Actions: - * - {@link #sendMapMessage} with 'null' {@link PendingIntents}. - * - {@link #receiveEvent} of type {@link SENDING_SUCCESS}. - * - {@link #receiveEvent} of type {@link DELIVERY_SUCCESS}. + *

Actions: - {@link #sendMapMessage} with 'null' {@link PendingIntents}. - {@link + * #receiveEvent} of type {@link SENDING_SUCCESS}. - {@link #receiveEvent} of type {@link + * DELIVERY_SUCCESS}. * - * Outcome: - * - No Intent was broadcast. + *

Outcome: - No Intent was broadcast. */ @Test public void testSendMapMessageNullPendingIntent_noNotifyStatus() { @@ -1073,15 +1108,12 @@ public class MapClientStateMachineTest { } /** - * Preconditions: - * - In {@code STATE_CONNECTED}. + * Preconditions: - In {@code STATE_CONNECTED}. * - * Actions: - * - {@link #sendMapMessage} with 'Sent' {@link PendingIntents}. - * - {@link #receiveEvent} of type {@link SENDING_FAILURE}. + *

Actions: - {@link #sendMapMessage} with 'Sent' {@link PendingIntents}. - {@link + * #receiveEvent} of type {@link SENDING_FAILURE}. * - * Outcome: - * - SENT_STATUS Intent was broadcast with 'Failure' result code. + *

Outcome: - SENT_STATUS Intent was broadcast with 'Failure' result code. */ @Test public void testSendMapMessageSentPendingIntent_notifyStatusFailure() { @@ -1095,15 +1127,12 @@ public class MapClientStateMachineTest { } /** - * Preconditions: - * - In {@code STATE_CONNECTED}. + * Preconditions: - In {@code STATE_CONNECTED}. * - * Actions: - * - {@link #sendMapMessage} with 'Delivery' {@link PendingIntents}. - * - {@link #receiveEvent} of type {@link DELIVERY_FAILURE}. + *

Actions: - {@link #sendMapMessage} with 'Delivery' {@link PendingIntents}. - {@link + * #receiveEvent} of type {@link DELIVERY_FAILURE}. * - * Outcome: - * - DELIVERY_STATUS Intent was broadcast with 'Failure' result code. + *

Outcome: - DELIVERY_STATUS Intent was broadcast with 'Failure' result code. */ @Test public void testSendMapMessageDeliveryPendingIntent_notifyStatusFailure() { @@ -1117,8 +1146,8 @@ public class MapClientStateMachineTest { } /** - * @param action corresponding to the {@link PendingIntent} you want to create/register for - * when pushing a MAP message, e.g., for 'Sent' or 'Delivery' status. + * @param action corresponding to the {@link PendingIntent} you want to create/register for when + * pushing a MAP message, e.g., for 'Sent' or 'Delivery' status. * @param type the EventReport type of the new notification, e.g., 'Sent'/'Delivery' * 'Success'/'Failure'. */ @@ -1200,10 +1229,11 @@ public class MapClientStateMachineTest { private void setupSdpRecordReceipt() { // Perform first part of MAP connection logic. - verify(mMockMapClientService, - timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)).sendBroadcastMultiplePermissions( - mIntentArgument.capture(), any(String[].class), - any(BroadcastOptions.class)); + verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)) + .sendBroadcastMultiplePermissions( + mIntentArgument.capture(), + any(String[].class), + any(BroadcastOptions.class)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mMceStateMachine.getState()); // Setup receipt of SDP record @@ -1227,7 +1257,11 @@ public class MapClientStateMachineTest { } @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + public Cursor query( + Uri uri, + String[] projection, + String selection, + String[] selectionArgs, String sortOrder) { Cursor cursor = Mockito.mock(Cursor.class); @@ -1240,8 +1274,7 @@ public class MapClientStateMachineTest { } } - private static String getFolderNameFromRequestGetMessagesListing( - Request request) { + private static String getFolderNameFromRequestGetMessagesListing(Request request) { Log.d(TAG, "getFolderName, Request type=" + request); String folderName = null; if (request instanceof RequestGetMessagesListing) { @@ -1256,21 +1289,26 @@ public class MapClientStateMachineTest { } // create new Messages from given input - com.android.bluetooth.mapclient.Message createNewMessage(String mType, String mHandle){ + com.android.bluetooth.mapclient.Message createNewMessage(String mType, String mHandle) { HashMap attrs = new HashMap(); attrs.put("type", mType); attrs.put("handle", mHandle); attrs.put("datetime", "20230223T160000"); - com.android.bluetooth.mapclient.Message message = new com.android.bluetooth.mapclient. - Message(attrs); + com.android.bluetooth.mapclient.Message message = + new com.android.bluetooth.mapclient.Message(attrs); return message; } - EventReport createNewEventReport(String mType, String mDateTime, String mHandle, String mFolder, - String mOldFolder, String mMsgType){ + EventReport createNewEventReport( + String mType, + String mDateTime, + String mHandle, + String mFolder, + String mOldFolder, + String mMsgType) { HashMap attrs = new HashMap(); @@ -1284,10 +1322,9 @@ public class MapClientStateMachineTest { EventReport event = new EventReport(attrs); return event; - } - //create new Bmessages for testing + // create new Bmessages for testing void createTestMessages() { mOriginator = new VCardEntry(); VCardProperty property = new VCardProperty(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java index e36a25ab8de..04ed3e5d408 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java @@ -64,7 +64,6 @@ public class MapClientTest { @Mock private MnsService mMockMnsService; @Mock private DatabaseManager mDatabaseManager; - @Before public void setUp() throws Exception { mTargetContext = InstrumentationRegistry.getTargetContext(); @@ -108,9 +107,7 @@ public class MapClientTest { Assert.assertNotNull(MapClientService.getMapClientService()); } - /** - * Test connection of one device. - */ + /** Test connection of one device. */ @Test public void testConnect() { // make sure there is no statemachine already defined for this device @@ -134,9 +131,7 @@ public class MapClientTest { Assert.assertNull(mService.getInstanceMap().get(device)); } - /** - * Test that a PRIORITY_OFF device is not connected to - */ + /** Test that a PRIORITY_OFF device is not connected to */ @Test public void testConnectPriorityOffDevice() { // make sure there is no statemachine already defined for this device @@ -153,9 +148,7 @@ public class MapClientTest { Assert.assertNull(map.get(device)); } - /** - * Test connecting MAXIMUM_CONNECTED_DEVICES devices. - */ + /** Test connecting MAXIMUM_CONNECTED_DEVICES devices. */ @Test public void testConnectMaxDevices() { // Create bluetoothdevice & mock statemachine objects to be used in this test @@ -188,9 +181,7 @@ public class MapClientTest { Assert.assertFalse(mService.connect(last)); } - /** - * Test calling connect via Binder - */ + /** Test calling connect via Binder */ @Test public void testConnectViaBinder() { BluetoothDevice device = makeBluetoothDevice("11:11:11:11:11:11"); diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MnsObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MnsObexServerTest.java index a60c16e7946..1ed12863975 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MnsObexServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MnsObexServerTest.java @@ -47,8 +47,7 @@ public class MnsObexServerTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - MceStateMachine mStateMachine; + @Mock MceStateMachine mStateMachine; MnsObexServer mServer; @@ -59,7 +58,7 @@ public class MnsObexServerTest { @Test public void onConnect_whenUuidIsWrong() { - byte[] wrongUuid = new byte[]{}; + byte[] wrongUuid = new byte[] {}; HeaderSet request = new HeaderSet(); request.setHeader(HeaderSet.TARGET, wrongUuid); HeaderSet reply = new HeaderSet(); @@ -115,14 +114,15 @@ public class MnsObexServerTest { xml.append(" old_folder=\"test_old_folder\"\n"); xml.append(" msg_type=\"MMS\"\n"); xml.append("/>\n"); - DataInputStream stream = new DataInputStream( - new ByteArrayInputStream(xml.toString().getBytes())); - - byte[] applicationParameter = new byte[] { - Request.OAP_TAGID_MAS_INSTANCE_ID, - 1, // length in byte - (byte) 55 - }; + DataInputStream stream = + new DataInputStream(new ByteArrayInputStream(xml.toString().getBytes())); + + byte[] applicationParameter = + new byte[] { + Request.OAP_TAGID_MAS_INSTANCE_ID, + 1, // length in byte + (byte) 55 + }; HeaderSet headerSet = new HeaderSet(); headerSet.setHeader(HeaderSet.TYPE, MnsObexServer.TYPE); diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/ObexTimeTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/ObexTimeTest.java index 5841064eda0..0d6760716f8 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/ObexTimeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/ObexTimeTest.java @@ -74,26 +74,30 @@ public class ObexTimeTest { "Parsed instant must match expected", VALID_INSTANT_LOCAL_TZ, timestamp.getInstant()); - Assert.assertEquals("Parsed date must match expected", - VALID_DATE_LOCAL_TZ, timestamp.getTime()); + Assert.assertEquals( + "Parsed date must match expected", VALID_DATE_LOCAL_TZ, timestamp.getTime()); } @Test public void createWithValidDateTimeStringWithPosOffset_TimestampCorrect() { ObexTime timestamp = new ObexTime(VALID_TIME_STRING_WITH_OFFSET_POS); - Assert.assertEquals("Parsed instant must match expected", VALID_INSTANT_WITH_OFFSET_POS, + Assert.assertEquals( + "Parsed instant must match expected", + VALID_INSTANT_WITH_OFFSET_POS, timestamp.getInstant()); - Assert.assertEquals("Parsed date must match expected", - VALID_DATE_WITH_OFFSET_POS, timestamp.getTime()); + Assert.assertEquals( + "Parsed date must match expected", VALID_DATE_WITH_OFFSET_POS, timestamp.getTime()); } @Test public void createWithValidDateTimeStringWithNegOffset_TimestampCorrect() { ObexTime timestamp = new ObexTime(VALID_TIME_STRING_WITH_OFFSET_NEG); - Assert.assertEquals("Parsed instant must match expected", VALID_INSTANT_WITH_OFFSET_NEG, + Assert.assertEquals( + "Parsed instant must match expected", + VALID_INSTANT_WITH_OFFSET_NEG, timestamp.getInstant()); - Assert.assertEquals("Parsed date must match expected", - VALID_DATE_WITH_OFFSET_NEG, timestamp.getTime()); + Assert.assertEquals( + "Parsed date must match expected", VALID_DATE_WITH_OFFSET_NEG, timestamp.getTime()); } @Test @@ -103,16 +107,20 @@ public class ObexTimeTest { "ObexTime created with a date must return the expected instant", VALID_INSTANT_LOCAL_TZ, timestamp.getInstant()); - Assert.assertEquals("ObexTime created with a date must return the same date", - VALID_DATE_LOCAL_TZ, timestamp.getTime()); + Assert.assertEquals( + "ObexTime created with a date must return the same date", + VALID_DATE_LOCAL_TZ, + timestamp.getTime()); } @SuppressWarnings("JavaUtilDate") @Test public void createWithValidInstant_TimestampCorrect() { ObexTime timestamp = new ObexTime(VALID_INSTANT); - Assert.assertEquals("ObexTime created with a instant must return the same instant", - VALID_INSTANT, timestamp.getInstant()); + Assert.assertEquals( + "ObexTime created with a instant must return the same instant", + VALID_INSTANT, + timestamp.getInstant()); Assert.assertEquals( "ObexTime created with a instant must return the expected date", VALID_DATE, @@ -122,28 +130,34 @@ public class ObexTimeTest { @Test public void printValidTime_TimestampMatchesInput() { ObexTime timestamp = new ObexTime(VALID_TIME_STRING); - Assert.assertEquals("Timestamp as a string must match the input string", VALID_TIME_STRING, + Assert.assertEquals( + "Timestamp as a string must match the input string", + VALID_TIME_STRING, timestamp.toString()); } @Test public void createWithInvalidDelimiterString_TimestampIsNull() { ObexTime timestamp = new ObexTime(INVALID_TIME_STRING_BAD_DELIMITER); - Assert.assertEquals("Parsed timestamp was invalid and must result in a null object", null, + Assert.assertEquals( + "Parsed timestamp was invalid and must result in a null object", + null, timestamp.getTime()); } @Test public void createWithInvalidOffsetString_TimestampIsNull() { ObexTime timestamp = new ObexTime(INVALID_TIME_STRING_OFFSET_EXTRA_DIGITS); - Assert.assertEquals("Parsed timestamp was invalid and must result in a null object", null, + Assert.assertEquals( + "Parsed timestamp was invalid and must result in a null object", + null, timestamp.getTime()); } @Test public void printInvalidTime_ReturnsNull() { ObexTime timestamp = new ObexTime(INVALID_TIME_STRING_BAD_DELIMITER); - Assert.assertEquals("Invalid timestamps must return null for toString()", null, - timestamp.toString()); + Assert.assertEquals( + "Invalid timestamps must return null for toString()", null, timestamp.toString()); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/RequestGetMessagesListingForOwnNumberTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/RequestGetMessagesListingForOwnNumberTest.java index c314d614cd0..0f94753e3ef 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/RequestGetMessagesListingForOwnNumberTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/RequestGetMessagesListingForOwnNumberTest.java @@ -72,12 +72,15 @@ public class RequestGetMessagesListingForOwnNumberTest { * @param fillerElements - placeholder elements to fill up the folder. * @param targetElement - the element of interest that contains the info you want. * @param position - the index in the folder where {@code targetElement} is to be inserted. - * If {@code -1} or otherwise outside range, {@code folder} will not - * contain {@code targetElement}. + * If {@code -1} or otherwise outside range, {@code folder} will not contain {@code + * targetElement}. */ - public void createMessageFolder(String folder, int size, + public void createMessageFolder( + String folder, + int size, BluetoothMapMessageListingElement fillerElements, - BluetoothMapMessageListingElement targetElement, int position) { + BluetoothMapMessageListingElement targetElement, + int position) { List list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(fillerElements); @@ -93,30 +96,41 @@ public class RequestGetMessagesListingForOwnNumberTest { } } - public InputStream getMessageListingAsInputStream(String folder, int offset, int maxCount, - byte msgTypeFilter) { + public InputStream getMessageListingAsInputStream( + String folder, int offset, int maxCount, byte msgTypeFilter) { List folderElements = mFolders.get(folder); BluetoothMapMessageListing requestedListing = new BluetoothMapMessageListing(); if (folderElements != null - && offset >= 0 && offset < LIST_START_OFFSET_UPPER_LIMIT - && maxCount >= 0 && maxCount < MAX_LIST_COUNT_UPPER_LIMIT) { + && offset >= 0 + && offset < LIST_START_OFFSET_UPPER_LIMIT + && maxCount >= 0 + && maxCount < MAX_LIST_COUNT_UPPER_LIMIT) { int msgCount = 0; - for (int i = offset; i < folderElements.size() && msgCount < maxCount; i++ ) { + for (int i = offset; i < folderElements.size() && msgCount < maxCount; i++) { BluetoothMapMessageListingElement element = folderElements.get(i); byte msgType = listingElementGetType(element); if ((msgTypeFilter & msgType) > 0) { requestedListing.add(element); msgCount += 1; } - Log.d(TAG, "getMessageListingAsInputStream: i=" + i + ", msgCount=" + msgCount - + ", msgType=" + msgType + ", msgTypeFilter=" + msgTypeFilter); + Log.d( + TAG, + "getMessageListingAsInputStream: i=" + + i + + ", msgCount=" + + msgCount + + ", msgType=" + + msgType + + ", msgTypeFilter=" + + msgTypeFilter); } } byte[] encodedListing = null; try { - encodedListing = requestedListing.encode(TEST_INCLUDE_THREAD_ID_ENCODE, - TEST_MSG_LISTING_OBJ_VERSION); + encodedListing = + requestedListing.encode( + TEST_INCLUDE_THREAD_ID_ENCODE, TEST_MSG_LISTING_OBJ_VERSION); } catch (Exception e) { assertWithMessage("Cannot encode MessageListing: " + e.getMessage()).fail(); } @@ -127,24 +141,22 @@ public class RequestGetMessagesListingForOwnNumberTest { } /** - * Map Client uses bytes to represent message types (e.g., MMS, SMS, Email) (c.f. - * {@link MessagesFilter}). However, Map Server (i.e., - * {@link BluetoothMapMessageListingElement}) uses enum to represent types (c.f., - * {@link BluetoothMapUtils}). Instead, we'll be abusing - * {@link BluetoothMapMessageListingElement#mAttachmentSize} to store Map Client's type, - * since it's otherwise unused in the tests. + * Map Client uses bytes to represent message types (e.g., MMS, SMS, Email) (c.f. {@link + * MessagesFilter}). However, Map Server (i.e., {@link BluetoothMapMessageListingElement}) uses + * enum to represent types (c.f., {@link BluetoothMapUtils}). Instead, we'll be abusing {@link + * BluetoothMapMessageListingElement#mAttachmentSize} to store Map Client's type, since it's + * otherwise unused in the tests. */ static void listingElementSetType(BluetoothMapMessageListingElement element, byte type) { element.setAttachmentSize(type); } /** - * Map Client uses bytes to represent message types (e.g., MMS, SMS, Email) (c.f. - * {@link MessagesFilter}). However, Map Server (i.e., - * {@link BluetoothMapMessageListingElement}) uses enum to represent types (c.f., - * {@link BluetoothMapUtils}). Instead, we'll be abusing - * {@link BluetoothMapMessageListingElement#mAttachmentSize} to store Map Client's type, - * since it's otherwise unused in the tests. + * Map Client uses bytes to represent message types (e.g., MMS, SMS, Email) (c.f. {@link + * MessagesFilter}). However, Map Server (i.e., {@link BluetoothMapMessageListingElement}) uses + * enum to represent types (c.f., {@link BluetoothMapUtils}). Instead, we'll be abusing {@link + * BluetoothMapMessageListingElement#mAttachmentSize} to store Map Client's type, since it's + * otherwise unused in the tests. */ static byte listingElementGetType(BluetoothMapMessageListingElement element) { return (byte) element.getAttachmentSize(); @@ -153,8 +165,7 @@ public class RequestGetMessagesListingForOwnNumberTest { @Before public void setUp() { // Override the MAX_LIST_COUNT upper limit to speed up tests - RequestGetMessagesListingForOwnNumber.sMaxListCountUpperLimit = - MAX_LIST_COUNT_UPPER_LIMIT; + RequestGetMessagesListingForOwnNumber.sMaxListCountUpperLimit = MAX_LIST_COUNT_UPPER_LIMIT; // Override the START_OFFSET upper limit to speed up tests RequestGetMessagesListingForOwnNumber.sListStartOffsetUpperLimit = LIST_START_OFFSET_UPPER_LIMIT; @@ -175,59 +186,74 @@ public class RequestGetMessagesListingForOwnNumberTest { listingElementSetType(mSMSWithoutOwnNumber, MessagesFilter.MESSAGE_TYPE_SMS_GSM); } - private String testGetOwnNumberBase(int sizeSentFolder, int sizeInboxFolder, - int positionSentFolder, int positionInboxFolder, + private String testGetOwnNumberBase( + int sizeSentFolder, + int sizeInboxFolder, + int positionSentFolder, + int positionInboxFolder, BluetoothMapMessageListingElement targetElement) { FakeMessageFoldersForListing folders = new FakeMessageFoldersForListing(); - folders.createMessageFolder(MceStateMachine.FOLDER_SENT, sizeSentFolder, - mSMSWithoutOwnNumber, targetElement, positionSentFolder); - folders.createMessageFolder(MceStateMachine.FOLDER_INBOX, sizeInboxFolder, - mSMSWithoutOwnNumber, targetElement, positionInboxFolder); + folders.createMessageFolder( + MceStateMachine.FOLDER_SENT, + sizeSentFolder, + mSMSWithoutOwnNumber, + targetElement, + positionSentFolder); + folders.createMessageFolder( + MceStateMachine.FOLDER_INBOX, + sizeInboxFolder, + mSMSWithoutOwnNumber, + targetElement, + positionInboxFolder); RequestGetMessagesListingForOwnNumber newRequest = new RequestGetMessagesListingForOwnNumber(); - for (int i = 0; !newRequest.isSearchCompleted() && i < MAX_ITERATIONS; i ++) { + for (int i = 0; !newRequest.isSearchCompleted() && i < MAX_ITERATIONS; i++) { String folderName = null; try { folderName = (String) newRequest.mHeaderSet.getHeader(HeaderSet.NAME); } catch (Exception e) { - assertWithMessage("Cannot obtain folder name from Request's HeaderSet: " - + e.getMessage()).fail(); + assertWithMessage( + "Cannot obtain folder name from Request's HeaderSet: " + + e.getMessage()) + .fail(); } ObexAppParameters oap = ObexAppParameters.fromHeaderSet(newRequest.mHeaderSet); byte filterMessageType = oap.getByte(Request.OAP_TAGID_FILTER_MESSAGE_TYPE); int maxListCount = (int) oap.getShort(Request.OAP_TAGID_MAX_LIST_COUNT); int startOffset = (int) oap.getShort(Request.OAP_TAGID_START_OFFSET); - Log.d(TAG, String.format("testBase: filter=%b, count=%b, offset=%b", - oap.exists(Request.OAP_TAGID_FILTER_MESSAGE_TYPE), - oap.exists(Request.OAP_TAGID_MAX_LIST_COUNT), - oap.exists(Request.OAP_TAGID_START_OFFSET))); - - Log.d(TAG, String.format( - "testBase: [i=%d] folder=%s, maxCount=%d, offset=%d, filterMessageType=%02X", - i, folderName, maxListCount, startOffset, filterMessageType)); + Log.d( + TAG, + String.format( + "testBase: filter=%b, count=%b, offset=%b", + oap.exists(Request.OAP_TAGID_FILTER_MESSAGE_TYPE), + oap.exists(Request.OAP_TAGID_MAX_LIST_COUNT), + oap.exists(Request.OAP_TAGID_START_OFFSET))); + + Log.d( + TAG, + String.format( + "testBase: [i=%d] folder=%s, maxCount=%d, offset=%d," + + " filterMessageType=%02X", + i, folderName, maxListCount, startOffset, filterMessageType)); newRequest.readResponse( - folders.getMessageListingAsInputStream(folderName, startOffset, maxListCount, - filterMessageType)); + folders.getMessageListingAsInputStream( + folderName, startOffset, maxListCount, filterMessageType)); } return newRequest.getOwnNumber(); } /** - * Preconditions: - * - SENT is empty. - * - INBOX is empty. + * Preconditions: - SENT is empty. - INBOX is empty. * - * Actions: - * - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly until the - * own number has been found or folder elements have been exhausted. + *

Actions: - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly + * until the own number has been found or folder elements have been exhausted. * - * Outcome: - * - Own number is not found. + *

Outcome: - Own number is not found. */ @Test public void testEmpty_Empty_null() { @@ -237,24 +263,25 @@ public class RequestGetMessagesListingForOwnNumberTest { int inboxFolderPosition = -1; BluetoothMapMessageListingElement targetElement = null; - String ownNumber = testGetOwnNumberBase(sentFolderSize, inboxFolderSize, - sentFolderPosition, inboxFolderPosition, targetElement); + String ownNumber = + testGetOwnNumberBase( + sentFolderSize, + inboxFolderSize, + sentFolderPosition, + inboxFolderPosition, + targetElement); assertThat(ownNumber).isNull(); } /** - * Preconditions: - * - SENT number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - MMS with own number as sender is the first message in SENT folder. - * - INBOX is empty. + * Preconditions: - SENT number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - + * MMS with own number as sender is the first message in SENT folder. - INBOX is empty. * - * Actions: - * - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly until the - * own number has been found or folder elements have been exhausted. + *

Actions: - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly + * until the own number has been found or folder elements have been exhausted. * - * Outcome: - * - Own number is found. + *

Outcome: - Own number is found. */ @Test public void testHalfFirst_Empty_found() { @@ -264,24 +291,25 @@ public class RequestGetMessagesListingForOwnNumberTest { int inboxFolderPosition = -1; BluetoothMapMessageListingElement targetElement = mMMSWithOwnNumberAsSender; - String ownNumber = testGetOwnNumberBase(sentFolderSize, inboxFolderSize, - sentFolderPosition, inboxFolderPosition, targetElement); + String ownNumber = + testGetOwnNumberBase( + sentFolderSize, + inboxFolderSize, + sentFolderPosition, + inboxFolderPosition, + targetElement); assertThat(ownNumber).isEqualTo(TEST_OWN_NUMBER); } /** - * Preconditions: - * - SENT number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - MMS with own number as sender is the last message in SENT folder. - * - INBOX is empty. + * Preconditions: - SENT number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - + * MMS with own number as sender is the last message in SENT folder. - INBOX is empty. * - * Actions: - * - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly until the - * own number has been found or folder elements have been exhausted. + *

Actions: - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly + * until the own number has been found or folder elements have been exhausted. * - * Outcome: - * - Own number is found. + *

Outcome: - Own number is found. */ @Test public void testHalfLast_Empty_found() { @@ -291,24 +319,25 @@ public class RequestGetMessagesListingForOwnNumberTest { int inboxFolderPosition = -1; BluetoothMapMessageListingElement targetElement = mMMSWithOwnNumberAsSender; - String ownNumber = testGetOwnNumberBase(sentFolderSize, inboxFolderSize, - sentFolderPosition, inboxFolderPosition, targetElement); + String ownNumber = + testGetOwnNumberBase( + sentFolderSize, + inboxFolderSize, + sentFolderPosition, + inboxFolderPosition, + targetElement); assertThat(ownNumber).isEqualTo(TEST_OWN_NUMBER); } /** - * Preconditions: - * - SENT number of messages is equal to {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - MMS with own number as sender is the last message in SENT folder. - * - INBOX is empty. + * Preconditions: - SENT number of messages is equal to {@code LIST_START_OFFSET_UPPER_LIMIT}. - + * MMS with own number as sender is the last message in SENT folder. - INBOX is empty. * - * Actions: - * - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly until the - * own number has been found or folder elements have been exhausted. + *

Actions: - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly + * until the own number has been found or folder elements have been exhausted. * - * Outcome: - * - Own number is found. + *

Outcome: - Own number is found. */ @Test public void testFullLast_Empty_found() { @@ -318,24 +347,26 @@ public class RequestGetMessagesListingForOwnNumberTest { int inboxFolderPosition = -1; BluetoothMapMessageListingElement targetElement = mMMSWithOwnNumberAsSender; - String ownNumber = testGetOwnNumberBase(sentFolderSize, inboxFolderSize, - sentFolderPosition, inboxFolderPosition, targetElement); + String ownNumber = + testGetOwnNumberBase( + sentFolderSize, + inboxFolderSize, + sentFolderPosition, + inboxFolderPosition, + targetElement); assertThat(ownNumber).isEqualTo(TEST_OWN_NUMBER); } /** - * Preconditions: - * - SENT number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - INBOX number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - SMS with own number as recipient is the first message in INBOX folder. + * Preconditions: - SENT number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - + * INBOX number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - SMS with own + * number as recipient is the first message in INBOX folder. * - * Actions: - * - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly until the - * own number has been found or folder elements have been exhausted. + *

Actions: - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly + * until the own number has been found or folder elements have been exhausted. * - * Outcome: - * - Own number is found. + *

Outcome: - Own number is found. */ @Test public void testHalf_HalfFirst_found() { @@ -345,24 +376,26 @@ public class RequestGetMessagesListingForOwnNumberTest { int inboxFolderPosition = 0; BluetoothMapMessageListingElement targetElement = mSMSWithOwnNumberAsRecipient; - String ownNumber = testGetOwnNumberBase(sentFolderSize, inboxFolderSize, - sentFolderPosition, inboxFolderPosition, targetElement); + String ownNumber = + testGetOwnNumberBase( + sentFolderSize, + inboxFolderSize, + sentFolderPosition, + inboxFolderPosition, + targetElement); assertThat(ownNumber).isEqualTo(TEST_OWN_NUMBER); } /** - * Preconditions: - * - SENT number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - INBOX number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - SMS with own number as recipient is the last message in INBOX folder. + * Preconditions: - SENT number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - + * INBOX number of messages is half of {@code LIST_START_OFFSET_UPPER_LIMIT}. - SMS with own + * number as recipient is the last message in INBOX folder. * - * Actions: - * - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly until the - * own number has been found or folder elements have been exhausted. + *

Actions: - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly + * until the own number has been found or folder elements have been exhausted. * - * Outcome: - * - Own number is found. + *

Outcome: - Own number is found. */ @Test public void testHalf_HalfLast_found() { @@ -372,24 +405,26 @@ public class RequestGetMessagesListingForOwnNumberTest { int inboxFolderPosition = inboxFolderSize - 1; BluetoothMapMessageListingElement targetElement = mSMSWithOwnNumberAsRecipient; - String ownNumber = testGetOwnNumberBase(sentFolderSize, inboxFolderSize, - sentFolderPosition, inboxFolderPosition, targetElement); + String ownNumber = + testGetOwnNumberBase( + sentFolderSize, + inboxFolderSize, + sentFolderPosition, + inboxFolderPosition, + targetElement); assertThat(ownNumber).isEqualTo(TEST_OWN_NUMBER); } /** - * Preconditions: - * - SENT number of messages is equal to {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - INBOX number of messages is equal to {@code LIST_START_OFFSET_UPPER_LIMIT}. - * - SMS with own number as recipient is the last message in INBOX folder. + * Preconditions: - SENT number of messages is equal to {@code LIST_START_OFFSET_UPPER_LIMIT}. - + * INBOX number of messages is equal to {@code LIST_START_OFFSET_UPPER_LIMIT}. - SMS with own + * number as recipient is the last message in INBOX folder. * - * Actions: - * - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly until the - * own number has been found or folder elements have been exhausted. + *

Actions: - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly + * until the own number has been found or folder elements have been exhausted. * - * Outcome: - * - Own number is found. + *

Outcome: - Own number is found. */ @Test public void testFull_FullLast_found() { @@ -399,25 +434,26 @@ public class RequestGetMessagesListingForOwnNumberTest { int inboxFolderPosition = inboxFolderSize - 1; BluetoothMapMessageListingElement targetElement = mSMSWithOwnNumberAsRecipient; - String ownNumber = testGetOwnNumberBase(sentFolderSize, inboxFolderSize, - sentFolderPosition, inboxFolderPosition, targetElement); + String ownNumber = + testGetOwnNumberBase( + sentFolderSize, + inboxFolderSize, + sentFolderPosition, + inboxFolderPosition, + targetElement); assertThat(ownNumber).isEqualTo(TEST_OWN_NUMBER); } /** - * Preconditions: - * - SENT is empty. - * - INBOX contains a single message. - * - MMS with someone else's number as recipient in INBOX folder (e.g., group MMS case). + * Preconditions: - SENT is empty. - INBOX contains a single message. - MMS with someone else's + * number as recipient in INBOX folder (e.g., group MMS case). * - * Actions: - * - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly until the - * own number has been found or folder elements have been exhausted. + *

Actions: - Invoke {@link RequestGetMessagesListingForOwnNumber#readResponse} repeatedly + * until the own number has been found or folder elements have been exhausted. * - * Outcome: - * - No number is found, not even someone else's number, since MMS should be filtered out - * of INBOX. + *

Outcome: - No number is found, not even someone else's number, since MMS should be + * filtered out of INBOX. */ @Test public void testMMSinInbox_null() { @@ -429,8 +465,13 @@ public class RequestGetMessagesListingForOwnNumberTest { // is non-empty (i.e., would not get skipped if not filtered out by msg type). BluetoothMapMessageListingElement targetElement = mMMSWithOwnNumberAsSender; - String ownNumber = testGetOwnNumberBase(sentFolderSize, inboxFolderSize, - sentFolderPosition, inboxFolderPosition, targetElement); + String ownNumber = + testGetOwnNumberBase( + sentFolderSize, + inboxFolderSize, + sentFolderPosition, + inboxFolderPosition, + targetElement); assertThat(ownNumber).isNull(); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/RequestTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/RequestTest.java index 95599cd5799..a9b718d0c21 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/RequestTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/RequestTest.java @@ -57,12 +57,11 @@ public class RequestTest { private static final String TYPE_SET_NOTIFICATION_REGISTRATION = "x-bt/MAP-NotificationRegistration"; - private static final String HANDLE = "0000001"; private static final Bmessage TEST_MESSAGE = BmessageParser.createBmessage(SIMPLE_MMS_MESSAGE); - private static final ArrayList TEST_FOLDER_LIST = new ArrayList( - Arrays.asList("folder1")); + private static final ArrayList TEST_FOLDER_LIST = + new ArrayList(Arrays.asList("folder1")); private static final ArrayList TEST_MESSAGE_LIST = new ArrayList(); private static final Date TEST_TIME = new Date(); private static final byte TEST_STATUS_INDICATOR = Request.STATUS_INDICATOR_READ; @@ -80,9 +79,14 @@ public class RequestTest { @Test public void testRequestGetMessagesListing() throws IOException { - RequestGetMessagesListing newRequest = new RequestGetMessagesListing( - TEST_FOLDER_LIST.get(0), /*parameters*/ 0, /*filter*/ null, /*subjectLength*/ 0, - /*maxListCount*/ 0, /*listStartOffset*/ 0); + RequestGetMessagesListing newRequest = + new RequestGetMessagesListing( + TEST_FOLDER_LIST.get(0), /*parameters*/ + 0, /*filter*/ + null, /*subjectLength*/ + 0, + /*maxListCount*/ 0, /*listStartOffset*/ + 0); assertThat(newRequest).isNotNull(); newRequest.execute(mFakeClientSession); @@ -94,8 +98,8 @@ public class RequestTest { @Test public void testRequestGetMessage() throws IOException { - RequestGetMessage newRequest = new RequestGetMessage(HANDLE, MasClient.CharsetType.UTF_8, - /*attachment*/ false); + RequestGetMessage newRequest = + new RequestGetMessage(HANDLE, MasClient.CharsetType.UTF_8, /*attachment*/ false); assertThat(newRequest).isNotNull(); assertThat(newRequest.getHandle()).isEqualTo(HANDLE); newRequest.execute(mFakeClientSession); @@ -107,8 +111,8 @@ public class RequestTest { @Test public void testRequestGetFolderListing() throws IOException { - RequestGetFolderListing newRequest = new RequestGetFolderListing(/*maxListCount*/ 255, - /*listStartOffset*/ 0); + RequestGetFolderListing newRequest = + new RequestGetFolderListing(/*maxListCount*/ 255, /*listStartOffset*/ 0); assertThat(newRequest).isNotNull(); newRequest.execute(mFakeClientSession); @@ -118,8 +122,13 @@ public class RequestTest { @Test public void testRequestPushMessage() throws IOException { - RequestPushMessage newRequest = new RequestPushMessage(TEST_FOLDER_LIST.get(0), - TEST_MESSAGE, /*charset*/ null, /*transparent*/ false, /*retry*/ false); + RequestPushMessage newRequest = + new RequestPushMessage( + TEST_FOLDER_LIST.get(0), + TEST_MESSAGE, /*charset*/ + null, /*transparent*/ + false, /*retry*/ + false); assertThat(newRequest).isNotNull(); assertThat(newRequest.getMsgHandle()).isEqualTo(null); newRequest.execute(mFakeClientSession); @@ -131,8 +140,8 @@ public class RequestTest { @Test public void testRequestSetMessageStatus() throws IOException { - RequestSetMessageStatus newRequest = new RequestSetMessageStatus(HANDLE, - StatusIndicator.READ, TEST_STATUS_VALUE); + RequestSetMessageStatus newRequest = + new RequestSetMessageStatus(HANDLE, StatusIndicator.READ, TEST_STATUS_VALUE); assertThat(newRequest).isNotNull(); assertThat(newRequest.getHandle()).isEqualTo(HANDLE); newRequest.execute(mFakeClientSession); @@ -144,8 +153,8 @@ public class RequestTest { @Test public void testRequestSetNotificationRegistration() throws IOException { - RequestSetNotificationRegistration newRequest = new RequestSetNotificationRegistration( - /*status*/ true); + RequestSetNotificationRegistration newRequest = + new RequestSetNotificationRegistration(/*status*/ true); assertThat(newRequest).isNotNull(); newRequest.execute(mFakeClientSession); @@ -197,8 +206,8 @@ public class RequestTest { case TYPE_GET_MESSAGE_LISTING: outAppParams.setNewMessage(1); outAppParams.setMseTime(TEST_TIME.getTime()); - replyHeaders.setHeader(HeaderSet.APPLICATION_PARAMETER, - outAppParams.encodeParams()); + replyHeaders.setHeader( + HeaderSet.APPLICATION_PARAMETER, outAppParams.encodeParams()); op.sendHeaders(replyHeaders); return ResponseCodes.OBEX_HTTP_OK; } @@ -249,7 +258,9 @@ public class RequestTest { } @Override - public int onSetPathValidator(final HeaderSet request, HeaderSet reply, + public int onSetPathValidator( + final HeaderSet request, + HeaderSet reply, final boolean backup, final boolean create) { try { diff --git a/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java index ceb34661f28..849d3b73c02 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java @@ -50,12 +50,9 @@ public class McpServiceTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private AdapterService mAdapterService; - @Mock - private MediaControlGattService mMockMcpService; - @Mock - private MediaControlProfile mMediaControlProfile; + @Mock private AdapterService mAdapterService; + @Mock private MediaControlGattService mMockMcpService; + @Mock private MediaControlProfile mMediaControlProfile; @Before public void setUp() throws Exception { @@ -108,8 +105,8 @@ public class McpServiceTest { mMcpService.setDeviceAuthorized(device1, false); verify(mMediaControlProfile).onDeviceAuthorizationSet(eq(device1)); - Assert.assertEquals(BluetoothDevice.ACCESS_REJECTED, - mMcpService.getDeviceAuthorization(device1)); + Assert.assertEquals( + BluetoothDevice.ACCESS_REJECTED, mMcpService.getDeviceAuthorization(device1)); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java index 5588f5ae956..af855c0023a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java @@ -91,7 +91,6 @@ public class MediaControlGattServiceTest { Looper.prepare(); } - TestUtils.setAdapterService(mAdapterService); mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -103,8 +102,8 @@ public class MediaControlGattServiceTest { mMcpService.setServiceManagerForTesting(mMockMcpService); mMcpService.setLeAudioServiceForTesting(mMockLeAudioService); - when(mMockMcpService.getDeviceAuthorization(any(BluetoothDevice.class))).thenReturn( - BluetoothDevice.ACCESS_ALLOWED); + when(mMockMcpService.getDeviceAuthorization(any(BluetoothDevice.class))) + .thenReturn(BluetoothDevice.ACCESS_ALLOWED); } @After @@ -156,24 +155,36 @@ public class MediaControlGattServiceTest { } private BluetoothGattService initAllFeaturesGattService() { - long features = ServiceFeature.ALL_MANDATORY_SERVICE_FEATURES - | ServiceFeature.PLAYER_ICON_OBJ_ID | ServiceFeature.PLAYER_ICON_URL - | ServiceFeature.PLAYBACK_SPEED | ServiceFeature.SEEKING_SPEED - | ServiceFeature.CURRENT_TRACK_SEGMENT_OBJ_ID | ServiceFeature.CURRENT_TRACK_OBJ_ID - | ServiceFeature.NEXT_TRACK_OBJ_ID | ServiceFeature.CURRENT_GROUP_OBJ_ID - | ServiceFeature.PARENT_GROUP_OBJ_ID | ServiceFeature.PLAYING_ORDER - | ServiceFeature.PLAYING_ORDER_SUPPORTED | ServiceFeature.MEDIA_CONTROL_POINT - | ServiceFeature.MEDIA_CONTROL_POINT_OPCODES_SUPPORTED - | ServiceFeature.SEARCH_RESULT_OBJ_ID | ServiceFeature.SEARCH_CONTROL_POINT - // Notifications - | ServiceFeature.PLAYER_NAME_NOTIFY | ServiceFeature.TRACK_TITLE_NOTIFY - | ServiceFeature.TRACK_DURATION_NOTIFY | ServiceFeature.TRACK_POSITION_NOTIFY - | ServiceFeature.PLAYBACK_SPEED_NOTIFY | ServiceFeature.SEEKING_SPEED_NOTIFY - | ServiceFeature.CURRENT_TRACK_OBJ_ID_NOTIFY - | ServiceFeature.NEXT_TRACK_OBJ_ID_NOTIFY - | ServiceFeature.CURRENT_GROUP_OBJ_ID_NOTIFY - | ServiceFeature.PARENT_GROUP_OBJ_ID_NOTIFY | ServiceFeature.PLAYING_ORDER_NOTIFY - | ServiceFeature.MEDIA_CONTROL_POINT_OPCODES_SUPPORTED_NOTIFY; + long features = + ServiceFeature.ALL_MANDATORY_SERVICE_FEATURES + | ServiceFeature.PLAYER_ICON_OBJ_ID + | ServiceFeature.PLAYER_ICON_URL + | ServiceFeature.PLAYBACK_SPEED + | ServiceFeature.SEEKING_SPEED + | ServiceFeature.CURRENT_TRACK_SEGMENT_OBJ_ID + | ServiceFeature.CURRENT_TRACK_OBJ_ID + | ServiceFeature.NEXT_TRACK_OBJ_ID + | ServiceFeature.CURRENT_GROUP_OBJ_ID + | ServiceFeature.PARENT_GROUP_OBJ_ID + | ServiceFeature.PLAYING_ORDER + | ServiceFeature.PLAYING_ORDER_SUPPORTED + | ServiceFeature.MEDIA_CONTROL_POINT + | ServiceFeature.MEDIA_CONTROL_POINT_OPCODES_SUPPORTED + | ServiceFeature.SEARCH_RESULT_OBJ_ID + | ServiceFeature.SEARCH_CONTROL_POINT + // Notifications + | ServiceFeature.PLAYER_NAME_NOTIFY + | ServiceFeature.TRACK_TITLE_NOTIFY + | ServiceFeature.TRACK_DURATION_NOTIFY + | ServiceFeature.TRACK_POSITION_NOTIFY + | ServiceFeature.PLAYBACK_SPEED_NOTIFY + | ServiceFeature.SEEKING_SPEED_NOTIFY + | ServiceFeature.CURRENT_TRACK_OBJ_ID_NOTIFY + | ServiceFeature.NEXT_TRACK_OBJ_ID_NOTIFY + | ServiceFeature.CURRENT_GROUP_OBJ_ID_NOTIFY + | ServiceFeature.PARENT_GROUP_OBJ_ID_NOTIFY + | ServiceFeature.PLAYING_ORDER_NOTIFY + | ServiceFeature.MEDIA_CONTROL_POINT_OPCODES_SUPPORTED_NOTIFY; doReturn(features).when(mMockMcsCallbacks).onGetFeatureFlags(); Assert.assertTrue(mMcpService.init(UUID_GMCS)); @@ -188,8 +199,8 @@ public class MediaControlGattServiceTest { // called mMcpService.mServerCallback.onServiceAdded(BluetoothGatt.GATT_SUCCESS, service); verify(mMockMcsCallbacks) - .onServiceInstanceRegistered(any(ServiceStatus.class), any( - MediaControlGattServiceInterface.class)); + .onServiceInstanceRegistered( + any(ServiceStatus.class), any(MediaControlGattServiceInterface.class)); return service; } @@ -202,51 +213,62 @@ public class MediaControlGattServiceTest { BluetoothGattCharacteristic characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYER_NAME); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY); Assert.assertEquals("", characteristic.getStringValue(0)); characteristic = service.getCharacteristic(MediaControlGattService.UUID_TRACK_TITLE); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY); Assert.assertEquals("", characteristic.getStringValue(0)); characteristic = service.getCharacteristic(MediaControlGattService.UUID_TRACK_DURATION); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY); - Assert.assertEquals(0xFFFFFFFF, - characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT32, 0) + Assert.assertEquals( + 0xFFFFFFFF, + characteristic + .getIntValue(BluetoothGattCharacteristic.FORMAT_SINT32, 0) .intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_TRACK_POSITION); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE | BluetoothGattCharacteristic.PROPERTY_NOTIFY); - Assert.assertEquals(0xFFFFFFFF, - characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT32, 0) + Assert.assertEquals( + 0xFFFFFFFF, + characteristic + .getIntValue(BluetoothGattCharacteristic.FORMAT_SINT32, 0) .intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_MEDIA_STATE); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY); - Assert.assertEquals(MediaState.INACTIVE.getValue(), + Assert.assertEquals( + MediaState.INACTIVE.getValue(), characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0).intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_CONTENT_CONTROL_ID); Assert.assertNotNull(characteristic); Assert.assertEquals( characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ); - Assert.assertEquals(TEST_CCID, + Assert.assertEquals( + TEST_CCID, characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0).intValue()); // Check initial state of all optional characteristics @@ -269,20 +291,24 @@ public class MediaControlGattServiceTest { characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYBACK_SPEED); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE | BluetoothGattCharacteristic.PROPERTY_NOTIFY); - Assert.assertEquals(0, + Assert.assertEquals( + 0, characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT8, 0).intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_SEEKING_SPEED); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY); - Assert.assertEquals(0, + Assert.assertEquals( + 0, characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT8, 0).intValue()); characteristic = @@ -293,10 +319,11 @@ public class MediaControlGattServiceTest { characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ); Assert.assertTrue(characteristic.getValue().length == 0); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_CURRENT_TRACK_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_CURRENT_TRACK_OBJ_ID); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE @@ -305,62 +332,72 @@ public class MediaControlGattServiceTest { characteristic = service.getCharacteristic(MediaControlGattService.UUID_NEXT_TRACK_OBJ_ID); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE | BluetoothGattCharacteristic.PROPERTY_NOTIFY); Assert.assertTrue(characteristic.getValue().length == 0); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_CURRENT_GROUP_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_CURRENT_GROUP_OBJ_ID); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE | BluetoothGattCharacteristic.PROPERTY_NOTIFY); Assert.assertTrue(characteristic.getValue().length == 0); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_PARENT_GROUP_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_PARENT_GROUP_OBJ_ID); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY); Assert.assertTrue(characteristic.getValue().length == 0); characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYING_ORDER); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE | BluetoothGattCharacteristic.PROPERTY_NOTIFY); - Assert.assertEquals(PlayingOrder.SINGLE_ONCE.getValue(), + Assert.assertEquals( + PlayingOrder.SINGLE_ONCE.getValue(), characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0).intValue()); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_PLAYING_ORDER_SUPPORTED); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_PLAYING_ORDER_SUPPORTED); Assert.assertNotNull(characteristic); Assert.assertEquals( characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ); - Assert.assertEquals(SupportedPlayingOrder.SINGLE_ONCE, - characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0) + Assert.assertEquals( + SupportedPlayingOrder.SINGLE_ONCE, + characteristic + .getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0) .intValue()); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_MEDIA_CONTROL_POINT); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_MEDIA_CONTROL_POINT); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); + characteristic = + service.getCharacteristic( + MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY); Assert.assertEquals( @@ -369,18 +406,20 @@ public class MediaControlGattServiceTest { .getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 0) .intValue()); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_SEARCH_RESULT_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_SEARCH_RESULT_OBJ_ID); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY); Assert.assertTrue(characteristic.getValue().length == 0); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_SEARCH_CONTROL_POINT); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_SEARCH_CONTROL_POINT); Assert.assertNotNull(characteristic); - Assert.assertEquals(characteristic.getProperties(), + Assert.assertEquals( + characteristic.getProperties(), BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE); @@ -396,33 +435,40 @@ public class MediaControlGattServiceTest { String player_name = "TestPlayerName"; String icon_url = "www.testiconurl.com"; Long icon_obj_id = 7L; - Integer playing_order_supported = SupportedPlayingOrder.IN_ORDER_REPEAT - | SupportedPlayingOrder.SINGLE_ONCE | SupportedPlayingOrder.SINGLE_REPEAT - | SupportedPlayingOrder.IN_ORDER_ONCE | SupportedPlayingOrder.IN_ORDER_REPEAT - | SupportedPlayingOrder.OLDEST_ONCE | SupportedPlayingOrder.OLDEST_REPEAT - | SupportedPlayingOrder.NEWEST_ONCE | SupportedPlayingOrder.NEWEST_REPEAT - | SupportedPlayingOrder.SHUFFLE_ONCE | SupportedPlayingOrder.SHUFFLE_REPEAT; - Integer opcodes_supported = Request.SupportedOpcodes.NONE - | Request.SupportedOpcodes.PLAY - | Request.SupportedOpcodes.PAUSE - | Request.SupportedOpcodes.FAST_REWIND - | Request.SupportedOpcodes.FAST_FORWARD - | Request.SupportedOpcodes.STOP - | Request.SupportedOpcodes.MOVE_RELATIVE - | Request.SupportedOpcodes.PREVIOUS_SEGMENT - | Request.SupportedOpcodes.NEXT_SEGMENT - | Request.SupportedOpcodes.FIRST_SEGMENT - | Request.SupportedOpcodes.LAST_SEGMENT - | Request.SupportedOpcodes.GOTO_SEGMENT - | Request.SupportedOpcodes.PREVIOUS_TRACK - | Request.SupportedOpcodes.NEXT_TRACK - | Request.SupportedOpcodes.FIRST_TRACK - | Request.SupportedOpcodes.LAST_TRACK - | Request.SupportedOpcodes.GOTO_TRACK - | Request.SupportedOpcodes.PREVIOUS_GROUP - | Request.SupportedOpcodes.NEXT_GROUP - | Request.SupportedOpcodes.FIRST_GROUP - | Request.SupportedOpcodes.LAST_GROUP; + Integer playing_order_supported = + SupportedPlayingOrder.IN_ORDER_REPEAT + | SupportedPlayingOrder.SINGLE_ONCE + | SupportedPlayingOrder.SINGLE_REPEAT + | SupportedPlayingOrder.IN_ORDER_ONCE + | SupportedPlayingOrder.IN_ORDER_REPEAT + | SupportedPlayingOrder.OLDEST_ONCE + | SupportedPlayingOrder.OLDEST_REPEAT + | SupportedPlayingOrder.NEWEST_ONCE + | SupportedPlayingOrder.NEWEST_REPEAT + | SupportedPlayingOrder.SHUFFLE_ONCE + | SupportedPlayingOrder.SHUFFLE_REPEAT; + Integer opcodes_supported = + Request.SupportedOpcodes.NONE + | Request.SupportedOpcodes.PLAY + | Request.SupportedOpcodes.PAUSE + | Request.SupportedOpcodes.FAST_REWIND + | Request.SupportedOpcodes.FAST_FORWARD + | Request.SupportedOpcodes.STOP + | Request.SupportedOpcodes.MOVE_RELATIVE + | Request.SupportedOpcodes.PREVIOUS_SEGMENT + | Request.SupportedOpcodes.NEXT_SEGMENT + | Request.SupportedOpcodes.FIRST_SEGMENT + | Request.SupportedOpcodes.LAST_SEGMENT + | Request.SupportedOpcodes.GOTO_SEGMENT + | Request.SupportedOpcodes.PREVIOUS_TRACK + | Request.SupportedOpcodes.NEXT_TRACK + | Request.SupportedOpcodes.FIRST_TRACK + | Request.SupportedOpcodes.LAST_TRACK + | Request.SupportedOpcodes.GOTO_TRACK + | Request.SupportedOpcodes.PREVIOUS_GROUP + | Request.SupportedOpcodes.NEXT_GROUP + | Request.SupportedOpcodes.FIRST_GROUP + | Request.SupportedOpcodes.LAST_GROUP; String track_title = "Test Song"; long track_duration = 1000; MediaState playback_state = MediaState.SEEKING; @@ -450,14 +496,17 @@ public class MediaControlGattServiceTest { characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYING_ORDER); Assert.assertNotNull(characteristic); - Assert.assertEquals(playing_order.getValue(), + Assert.assertEquals( + playing_order.getValue(), characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0).intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_TRACK_POSITION); Assert.assertNotNull(characteristic); // Set value as ms, kept in characteristic as 0.01s - Assert.assertEquals(track_position / 10, - characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT32, 0) + Assert.assertEquals( + track_position / 10, + characteristic + .getIntValue(BluetoothGattCharacteristic.FORMAT_SINT32, 0) .intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYER_NAME); @@ -473,18 +522,23 @@ public class MediaControlGattServiceTest { Assert.assertEquals( icon_obj_id.longValue(), mMcpService.byteArray2ObjId(characteristic.getValue())); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_PLAYING_ORDER_SUPPORTED); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_PLAYING_ORDER_SUPPORTED); Assert.assertNotNull(characteristic); - Assert.assertEquals(playing_order_supported.intValue(), - characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0) + Assert.assertEquals( + playing_order_supported.intValue(), + characteristic + .getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0) .intValue()); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); + characteristic = + service.getCharacteristic( + MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); Assert.assertNotNull(characteristic); - Assert.assertEquals(opcodes_supported.intValue(), - characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 0) + Assert.assertEquals( + opcodes_supported.intValue(), + characteristic + .getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 0) .intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_TRACK_TITLE); @@ -494,13 +548,16 @@ public class MediaControlGattServiceTest { characteristic = service.getCharacteristic(MediaControlGattService.UUID_TRACK_DURATION); Assert.assertNotNull(characteristic); // Set value as ms, kept in characteristic as 0.01s - Assert.assertEquals(track_duration / 10, - characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_SINT32, 0) + Assert.assertEquals( + track_duration / 10, + characteristic + .getIntValue(BluetoothGattCharacteristic.FORMAT_SINT32, 0) .intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_MEDIA_STATE); Assert.assertNotNull(characteristic); - Assert.assertEquals(playback_state.getValue(), + Assert.assertEquals( + playback_state.getValue(), characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0).intValue()); characteristic = service.getCharacteristic(MediaControlGattService.UUID_SEEKING_SPEED); @@ -510,13 +567,23 @@ public class MediaControlGattServiceTest { private void verifyWriteObjIdsValid( BluetoothGattCharacteristic characteristic, long value, int id) { - mMcpService.mServerCallback.onCharacteristicWriteRequest(mCurrentDevice, 1, characteristic, - false, true, 0, mMcpService.objId2ByteArray(value)); + mMcpService.mServerCallback.onCharacteristicWriteRequest( + mCurrentDevice, + 1, + characteristic, + false, + true, + 0, + mMcpService.objId2ByteArray(value)); verify(mMockMcsCallbacks).onSetObjectIdRequest(eq(id), eq(value)); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), eq(BluetoothGatt.GATT_SUCCESS), eq(0), + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_SUCCESS), + eq(0), eq(mMcpService.objId2ByteArray(value))); } @@ -544,7 +611,11 @@ public class MediaControlGattServiceTest { verify(mMockMcsCallbacks).onTrackPositionSetRequest(eq(track_position * 10L)); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), eq(BluetoothGatt.GATT_SUCCESS), eq(0), + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_SUCCESS), + eq(0), eq(bb.array())); characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYBACK_SPEED); @@ -559,24 +630,28 @@ public class MediaControlGattServiceTest { .onPlaybackSpeedSetRequest(eq((float) Math.pow(2, playback_speed / 64))); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), eq(BluetoothGatt.GATT_SUCCESS), eq(0), + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_SUCCESS), + eq(0), eq(bb.array())); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_CURRENT_TRACK_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_CURRENT_TRACK_OBJ_ID); verifyWriteObjIdsValid( characteristic, current_track_obj_id, ObjectIds.CURRENT_TRACK_OBJ_ID); characteristic = service.getCharacteristic(MediaControlGattService.UUID_NEXT_TRACK_OBJ_ID); verifyWriteObjIdsValid(characteristic, next_track_obj_id, ObjectIds.NEXT_TRACK_OBJ_ID); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_CURRENT_GROUP_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_CURRENT_GROUP_OBJ_ID); verifyWriteObjIdsValid( characteristic, current_group_obj_id, ObjectIds.CURRENT_GROUP_OBJ_ID); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_PLAYING_ORDER_SUPPORTED); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_PLAYING_ORDER_SUPPORTED); characteristic.setValue( playing_order_supported, BluetoothGattCharacteristic.FORMAT_UINT16, 0); characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYING_ORDER); @@ -589,19 +664,27 @@ public class MediaControlGattServiceTest { verify(mMockMcsCallbacks).onPlayingOrderSetRequest(eq(playing_order.getValue())); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), eq(BluetoothGatt.GATT_SUCCESS), eq(0), + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_SUCCESS), + eq(0), eq(bb.array())); } private void verifyWriteObjIdsInvalid( BluetoothGattCharacteristic characteristic, int id, byte diffByte) { - byte[] value = new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, diffByte}; + byte[] value = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, diffByte}; mMcpService.mServerCallback.onCharacteristicWriteRequest( mCurrentDevice, 1, characteristic, false, true, 0, value); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), - eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), eq(0), eq(value)); + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), + eq(0), + eq(value)); } @Test @@ -624,8 +707,12 @@ public class MediaControlGattServiceTest { mCurrentDevice, 1, characteristic, false, true, 0, bb.array()); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), - eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), eq(0), eq(bb.array())); + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), + eq(0), + eq(bb.array())); characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYBACK_SPEED); @@ -637,18 +724,22 @@ public class MediaControlGattServiceTest { mCurrentDevice, 1, characteristic, false, true, 0, bb.array()); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), - eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), eq(0), eq(bb.array())); + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), + eq(0), + eq(bb.array())); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_CURRENT_TRACK_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_CURRENT_TRACK_OBJ_ID); verifyWriteObjIdsInvalid(characteristic, ObjectIds.CURRENT_TRACK_OBJ_ID, diff_byte++); characteristic = service.getCharacteristic(MediaControlGattService.UUID_NEXT_TRACK_OBJ_ID); verifyWriteObjIdsInvalid(characteristic, ObjectIds.NEXT_TRACK_OBJ_ID, diff_byte++); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_CURRENT_GROUP_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_CURRENT_GROUP_OBJ_ID); verifyWriteObjIdsInvalid(characteristic, ObjectIds.CURRENT_GROUP_OBJ_ID, diff_byte++); characteristic = service.getCharacteristic(MediaControlGattService.UUID_PLAYING_ORDER); @@ -660,8 +751,12 @@ public class MediaControlGattServiceTest { mCurrentDevice, 1, characteristic, false, true, 0, bb.array()); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), - eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), eq(0), eq(bb.array())); + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), + eq(0), + eq(bb.array())); } private void testNotify(boolean registerForNotification) { @@ -676,30 +771,32 @@ public class MediaControlGattServiceTest { PlayingOrder playing_order = PlayingOrder.IN_ORDER_REPEAT; int playing_order_supported = SupportedPlayingOrder.IN_ORDER_REPEAT; int playback_state = MediaState.SEEKING.getValue(); - Integer opcodes_supported = Request.SupportedOpcodes.NONE - | Request.SupportedOpcodes.PLAY - | Request.SupportedOpcodes.PAUSE - | Request.SupportedOpcodes.FAST_REWIND - | Request.SupportedOpcodes.FAST_FORWARD - | Request.SupportedOpcodes.STOP - | Request.SupportedOpcodes.MOVE_RELATIVE - | Request.SupportedOpcodes.PREVIOUS_SEGMENT - | Request.SupportedOpcodes.NEXT_SEGMENT - | Request.SupportedOpcodes.FIRST_SEGMENT - | Request.SupportedOpcodes.LAST_SEGMENT - | Request.SupportedOpcodes.GOTO_SEGMENT - | Request.SupportedOpcodes.PREVIOUS_TRACK - | Request.SupportedOpcodes.NEXT_TRACK - | Request.SupportedOpcodes.FIRST_TRACK - | Request.SupportedOpcodes.LAST_TRACK - | Request.SupportedOpcodes.GOTO_TRACK - | Request.SupportedOpcodes.PREVIOUS_GROUP - | Request.SupportedOpcodes.NEXT_GROUP - | Request.SupportedOpcodes.FIRST_GROUP - | Request.SupportedOpcodes.LAST_GROUP; - byte[] ccc_val = registerForNotification - ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE.clone() - : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE.clone(); + Integer opcodes_supported = + Request.SupportedOpcodes.NONE + | Request.SupportedOpcodes.PLAY + | Request.SupportedOpcodes.PAUSE + | Request.SupportedOpcodes.FAST_REWIND + | Request.SupportedOpcodes.FAST_FORWARD + | Request.SupportedOpcodes.STOP + | Request.SupportedOpcodes.MOVE_RELATIVE + | Request.SupportedOpcodes.PREVIOUS_SEGMENT + | Request.SupportedOpcodes.NEXT_SEGMENT + | Request.SupportedOpcodes.FIRST_SEGMENT + | Request.SupportedOpcodes.LAST_SEGMENT + | Request.SupportedOpcodes.GOTO_SEGMENT + | Request.SupportedOpcodes.PREVIOUS_TRACK + | Request.SupportedOpcodes.NEXT_TRACK + | Request.SupportedOpcodes.FIRST_TRACK + | Request.SupportedOpcodes.LAST_TRACK + | Request.SupportedOpcodes.GOTO_TRACK + | Request.SupportedOpcodes.PREVIOUS_GROUP + | Request.SupportedOpcodes.NEXT_GROUP + | Request.SupportedOpcodes.FIRST_GROUP + | Request.SupportedOpcodes.LAST_GROUP; + byte[] ccc_val = + registerForNotification + ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE.clone() + : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE.clone(); int times_cnt = registerForNotification ? 1 : 0; int media_control_request_opcode = Request.Opcodes.MOVE_RELATIVE; @@ -746,8 +843,8 @@ public class MediaControlGattServiceTest { verify(mMockGattServer, times(times_cnt)) .notifyCharacteristicChanged(eq(mCurrentDevice), eq(characteristic), eq(false)); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_CURRENT_TRACK_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_CURRENT_TRACK_OBJ_ID); prepareConnectedDevicesCccVal(characteristic, ccc_val); mMcpService.updateObjectID(ObjectIds.CURRENT_TRACK_OBJ_ID, obj_id); verify(mMockGattServer, times(times_cnt)) @@ -759,15 +856,15 @@ public class MediaControlGattServiceTest { verify(mMockGattServer, times(times_cnt)) .notifyCharacteristicChanged(eq(mCurrentDevice), eq(characteristic), eq(false)); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_CURRENT_GROUP_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_CURRENT_GROUP_OBJ_ID); prepareConnectedDevicesCccVal(characteristic, ccc_val); mMcpService.updateObjectID(ObjectIds.CURRENT_GROUP_OBJ_ID, obj_id); verify(mMockGattServer, times(times_cnt)) .notifyCharacteristicChanged(eq(mCurrentDevice), eq(characteristic), eq(false)); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_PARENT_GROUP_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_PARENT_GROUP_OBJ_ID); prepareConnectedDevicesCccVal(characteristic, ccc_val); mMcpService.updateObjectID(ObjectIds.PARENT_GROUP_OBJ_ID, obj_id); verify(mMockGattServer, times(times_cnt)) @@ -780,31 +877,31 @@ public class MediaControlGattServiceTest { verify(mMockGattServer, times(times_cnt)) .notifyCharacteristicChanged(eq(mCurrentDevice), eq(characteristic), eq(false)); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_MEDIA_CONTROL_POINT); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_MEDIA_CONTROL_POINT); prepareConnectedDevicesCccVal(characteristic, ccc_val); mMcpService.setMediaControlRequestResult( - new Request(media_control_request_opcode, 0), - Request.Results.SUCCESS); + new Request(media_control_request_opcode, 0), Request.Results.SUCCESS); verify(mMockGattServer, times(times_cnt)) .notifyCharacteristicChanged(eq(mCurrentDevice), eq(characteristic), eq(false)); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); + characteristic = + service.getCharacteristic( + MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); prepareConnectedDevicesCccVal(characteristic, ccc_val); mMcpService.updateSupportedOpcodesChar(opcodes_supported, true); verify(mMockGattServer, times(times_cnt)) .notifyCharacteristicChanged(eq(mCurrentDevice), eq(characteristic), eq(false)); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_SEARCH_RESULT_OBJ_ID); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_SEARCH_RESULT_OBJ_ID); prepareConnectedDevicesCccVal(characteristic, ccc_val); mMcpService.updateObjectID(ObjectIds.SEARCH_RESULT_OBJ_ID, obj_id); verify(mMockGattServer, times(times_cnt)) .notifyCharacteristicChanged(eq(mCurrentDevice), eq(characteristic), eq(false)); - characteristic = service.getCharacteristic( - MediaControlGattService.UUID_SEARCH_CONTROL_POINT); + characteristic = + service.getCharacteristic(MediaControlGattService.UUID_SEARCH_CONTROL_POINT); prepareConnectedDevicesCccVal(characteristic, ccc_val); mMcpService.setSearchRequestResult(null, SearchRequest.Results.SUCCESS, obj_id); verify(mMockGattServer, times(times_cnt)) @@ -821,8 +918,12 @@ public class MediaControlGattServiceTest { testNotify(false); } - private void verifyMediaControlPointRequest(BluetoothGattService service, int opcode, - Integer value, int expectedGattResult, int invocation_count) { + private void verifyMediaControlPointRequest( + BluetoothGattService service, + int opcode, + Integer value, + int expectedGattResult, + int invocation_count) { BluetoothGattCharacteristic characteristic = service.getCharacteristic(MediaControlGattService.UUID_MEDIA_CONTROL_POINT); ByteBuffer bb; @@ -830,15 +931,17 @@ public class MediaControlGattServiceTest { if (expectedGattResult == BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH) { bb = ByteBuffer.allocate(6).order(ByteOrder.LITTLE_ENDIAN); } else { - bb = ByteBuffer.allocate(value != null ? (Integer.BYTES + Byte.BYTES) : Byte.BYTES) - .order(ByteOrder.LITTLE_ENDIAN); + bb = + ByteBuffer.allocate(value != null ? (Integer.BYTES + Byte.BYTES) : Byte.BYTES) + .order(ByteOrder.LITTLE_ENDIAN); } bb.put((byte) opcode); if (value != null) { bb.putInt(value); } - Assert.assertEquals(expectedGattResult, + Assert.assertEquals( + expectedGattResult, mMcpService.handleMediaControlPointRequest(mCurrentDevice, bb.array())); if (expectedGattResult == BluetoothGatt.GATT_SUCCESS) { @@ -851,81 +954,112 @@ public class MediaControlGattServiceTest { private void verifyMediaControlPointRequests(int expectedGattResult) { BluetoothGattService service = initAllFeaturesGattService(); int invocation_count = 1; - Integer opcodes_supported = Request.SupportedOpcodes.PLAY - | Request.SupportedOpcodes.PAUSE - | Request.SupportedOpcodes.FAST_REWIND - | Request.SupportedOpcodes.FAST_FORWARD - | Request.SupportedOpcodes.STOP - | Request.SupportedOpcodes.MOVE_RELATIVE - | Request.SupportedOpcodes.PREVIOUS_SEGMENT - | Request.SupportedOpcodes.NEXT_SEGMENT - | Request.SupportedOpcodes.FIRST_SEGMENT - | Request.SupportedOpcodes.LAST_SEGMENT - | Request.SupportedOpcodes.GOTO_SEGMENT - | Request.SupportedOpcodes.PREVIOUS_TRACK - | Request.SupportedOpcodes.NEXT_TRACK - | Request.SupportedOpcodes.FIRST_TRACK - | Request.SupportedOpcodes.LAST_TRACK - | Request.SupportedOpcodes.GOTO_TRACK - | Request.SupportedOpcodes.PREVIOUS_GROUP - | Request.SupportedOpcodes.NEXT_GROUP - | Request.SupportedOpcodes.FIRST_GROUP - | Request.SupportedOpcodes.LAST_GROUP - | Request.SupportedOpcodes.GOTO_GROUP; - - BluetoothGattCharacteristic characteristic = service.getCharacteristic( - MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); + Integer opcodes_supported = + Request.SupportedOpcodes.PLAY + | Request.SupportedOpcodes.PAUSE + | Request.SupportedOpcodes.FAST_REWIND + | Request.SupportedOpcodes.FAST_FORWARD + | Request.SupportedOpcodes.STOP + | Request.SupportedOpcodes.MOVE_RELATIVE + | Request.SupportedOpcodes.PREVIOUS_SEGMENT + | Request.SupportedOpcodes.NEXT_SEGMENT + | Request.SupportedOpcodes.FIRST_SEGMENT + | Request.SupportedOpcodes.LAST_SEGMENT + | Request.SupportedOpcodes.GOTO_SEGMENT + | Request.SupportedOpcodes.PREVIOUS_TRACK + | Request.SupportedOpcodes.NEXT_TRACK + | Request.SupportedOpcodes.FIRST_TRACK + | Request.SupportedOpcodes.LAST_TRACK + | Request.SupportedOpcodes.GOTO_TRACK + | Request.SupportedOpcodes.PREVIOUS_GROUP + | Request.SupportedOpcodes.NEXT_GROUP + | Request.SupportedOpcodes.FIRST_GROUP + | Request.SupportedOpcodes.LAST_GROUP + | Request.SupportedOpcodes.GOTO_GROUP; + + BluetoothGattCharacteristic characteristic = + service.getCharacteristic( + MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); prepareConnectedDevicesCccVal( characteristic, BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE.clone()); mMcpService.updateSupportedOpcodesChar(opcodes_supported, true); verify(mMockGattServer, times(0)) .notifyCharacteristicChanged(eq(mCurrentDevice), eq(characteristic), eq(false)); - verifyMediaControlPointRequest(service, Request.Opcodes.PLAY, null, - expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.PAUSE, null, - expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.FAST_REWIND, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.FAST_FORWARD, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.STOP, null, - expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.MOVE_RELATIVE, - 100, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, - Request.Opcodes.PREVIOUS_SEGMENT, null, expectedGattResult, + verifyMediaControlPointRequest( + service, Request.Opcodes.PLAY, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.PAUSE, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.FAST_REWIND, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, + Request.Opcodes.FAST_FORWARD, + null, + expectedGattResult, + invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.STOP, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, + Request.Opcodes.MOVE_RELATIVE, + 100, + expectedGattResult, + invocation_count++); + verifyMediaControlPointRequest( + service, + Request.Opcodes.PREVIOUS_SEGMENT, + null, + expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.NEXT_SEGMENT, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.FIRST_SEGMENT, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.LAST_SEGMENT, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.GOTO_SEGMENT, - 10, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, - Request.Opcodes.PREVIOUS_TRACK, null, expectedGattResult, + verifyMediaControlPointRequest( + service, + Request.Opcodes.NEXT_SEGMENT, + null, + expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.NEXT_TRACK, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.FIRST_TRACK, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.LAST_TRACK, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.GOTO_TRACK, 7, - expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, - Request.Opcodes.PREVIOUS_GROUP, null, expectedGattResult, + verifyMediaControlPointRequest( + service, + Request.Opcodes.FIRST_SEGMENT, + null, + expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.NEXT_GROUP, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.FIRST_GROUP, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.LAST_GROUP, - null, expectedGattResult, invocation_count++); - verifyMediaControlPointRequest(service, Request.Opcodes.GOTO_GROUP, - 10, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, + Request.Opcodes.LAST_SEGMENT, + null, + expectedGattResult, + invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.GOTO_SEGMENT, 10, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, + Request.Opcodes.PREVIOUS_TRACK, + null, + expectedGattResult, + invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.NEXT_TRACK, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.FIRST_TRACK, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.LAST_TRACK, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.GOTO_TRACK, 7, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, + Request.Opcodes.PREVIOUS_GROUP, + null, + expectedGattResult, + invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.NEXT_GROUP, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.FIRST_GROUP, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.LAST_GROUP, null, expectedGattResult, invocation_count++); + verifyMediaControlPointRequest( + service, Request.Opcodes.GOTO_GROUP, 10, expectedGattResult, invocation_count++); } @Test @@ -942,8 +1076,7 @@ public class MediaControlGattServiceTest { public void testMediaControlPointRequestInvalid() { Integer opcodes_supported = Request.SupportedOpcodes.NONE; - Assert.assertFalse( - mMcpService.isOpcodeSupported(Request.Opcodes.PLAY)); + Assert.assertFalse(mMcpService.isOpcodeSupported(Request.Opcodes.PLAY)); } @Test @@ -952,8 +1085,8 @@ public class MediaControlGattServiceTest { BluetoothGattService service = initAllFeaturesGattService(); prepareConnectedDevice(); mMcpService.updateSupportedOpcodesChar(Request.SupportedOpcodes.PLAY, true); - verifyMediaControlPointRequest(service, Request.Opcodes.PLAY, null, - BluetoothGatt.GATT_SUCCESS, 1); + verifyMediaControlPointRequest( + service, Request.Opcodes.PLAY, null, BluetoothGatt.GATT_SUCCESS, 1); if (!Flags.leaudioBroadcastFeatureSupport()) { verify(mMockLeAudioService).setActiveDevice(any(BluetoothDevice.class)); } else { @@ -996,30 +1129,32 @@ public class MediaControlGattServiceTest { @Test public void testUpdateSupportedOpcodesChar() { BluetoothGattService service = initAllFeaturesGattService(); - Integer opcodes_supported = Request.SupportedOpcodes.PLAY - | Request.SupportedOpcodes.PAUSE - | Request.SupportedOpcodes.FAST_REWIND - | Request.SupportedOpcodes.FAST_FORWARD - | Request.SupportedOpcodes.STOP - | Request.SupportedOpcodes.MOVE_RELATIVE - | Request.SupportedOpcodes.PREVIOUS_SEGMENT - | Request.SupportedOpcodes.NEXT_SEGMENT - | Request.SupportedOpcodes.FIRST_SEGMENT - | Request.SupportedOpcodes.LAST_SEGMENT - | Request.SupportedOpcodes.GOTO_SEGMENT - | Request.SupportedOpcodes.PREVIOUS_TRACK - | Request.SupportedOpcodes.NEXT_TRACK - | Request.SupportedOpcodes.FIRST_TRACK - | Request.SupportedOpcodes.LAST_TRACK - | Request.SupportedOpcodes.GOTO_TRACK - | Request.SupportedOpcodes.PREVIOUS_GROUP - | Request.SupportedOpcodes.NEXT_GROUP - | Request.SupportedOpcodes.FIRST_GROUP - | Request.SupportedOpcodes.LAST_GROUP - | Request.SupportedOpcodes.GOTO_GROUP; - - BluetoothGattCharacteristic characteristic = service.getCharacteristic( - MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); + Integer opcodes_supported = + Request.SupportedOpcodes.PLAY + | Request.SupportedOpcodes.PAUSE + | Request.SupportedOpcodes.FAST_REWIND + | Request.SupportedOpcodes.FAST_FORWARD + | Request.SupportedOpcodes.STOP + | Request.SupportedOpcodes.MOVE_RELATIVE + | Request.SupportedOpcodes.PREVIOUS_SEGMENT + | Request.SupportedOpcodes.NEXT_SEGMENT + | Request.SupportedOpcodes.FIRST_SEGMENT + | Request.SupportedOpcodes.LAST_SEGMENT + | Request.SupportedOpcodes.GOTO_SEGMENT + | Request.SupportedOpcodes.PREVIOUS_TRACK + | Request.SupportedOpcodes.NEXT_TRACK + | Request.SupportedOpcodes.FIRST_TRACK + | Request.SupportedOpcodes.LAST_TRACK + | Request.SupportedOpcodes.GOTO_TRACK + | Request.SupportedOpcodes.PREVIOUS_GROUP + | Request.SupportedOpcodes.NEXT_GROUP + | Request.SupportedOpcodes.FIRST_GROUP + | Request.SupportedOpcodes.LAST_GROUP + | Request.SupportedOpcodes.GOTO_GROUP; + + BluetoothGattCharacteristic characteristic = + service.getCharacteristic( + MediaControlGattService.UUID_MEDIA_CONTROL_POINT_OPCODES_SUPPORTED); prepareConnectedDevicesCccVal( characteristic, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE.clone()); @@ -1088,8 +1223,12 @@ public class MediaControlGattServiceTest { mCurrentDevice, 1, 0, characteristic); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), - eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), eq(0), any()); + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), + eq(0), + any()); } @Test @@ -1185,8 +1324,12 @@ public class MediaControlGattServiceTest { mCurrentDevice, 1, characteristic, false, true, 0, bb.array()); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), - eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), eq(0), any()); + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), + eq(0), + any()); } @Test @@ -1228,8 +1371,12 @@ public class MediaControlGattServiceTest { mMcpService.mServerCallback.onDescriptorReadRequest(mCurrentDevice, 1, 0, descriptor); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), - eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), eq(0), any()); + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), + eq(0), + any()); } @Test @@ -1279,8 +1426,12 @@ public class MediaControlGattServiceTest { mCurrentDevice, 1, descriptor, false, true, 0, bb.array()); verify(mMockGattServer) - .sendResponse(eq(mCurrentDevice), eq(1), - eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), eq(0), any()); + .sendResponse( + eq(mCurrentDevice), + eq(1), + eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), + eq(0), + any()); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlProfileTest.java b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlProfileTest.java index 7ce0374564d..07cbc9a9b9b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlProfileTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlProfileTest.java @@ -129,7 +129,7 @@ public class MediaControlProfileTest { MediaControlProfile.setsMediaPlayerListForTesting(mMockMediaPlayerList); mMediaControlProfile = new MediaControlProfile(mMockMcpService); - //this is equivalent of what usually happens inside init class + // this is equivalent of what usually happens inside init class mMediaControlProfile.injectGattServiceForTesting(packageName, mMockGMcsService); mMediaControlProfile.onServiceInstanceRegistered(ServiceStatus.OK, mMockGMcsService); mMcpServiceCallbacks = mMediaControlProfile; @@ -173,21 +173,27 @@ public class MediaControlProfileTest { // No metadata equals no track duration mMockMediaData.metadata = null; - Assert.assertEquals(MediaControlGattServiceInterface.TRACK_DURATION_UNAVAILABLE, + Assert.assertEquals( + MediaControlGattServiceInterface.TRACK_DURATION_UNAVAILABLE, mMediaControlProfile.getCurrentTrackDuration()); } @Test public void testPlayerState2McsState() { - Assert.assertEquals(mMediaControlProfile.playerState2McsState(PlaybackState.STATE_PLAYING), + Assert.assertEquals( + mMediaControlProfile.playerState2McsState(PlaybackState.STATE_PLAYING), MediaState.PLAYING); - Assert.assertEquals(mMediaControlProfile.playerState2McsState(PlaybackState.STATE_NONE), + Assert.assertEquals( + mMediaControlProfile.playerState2McsState(PlaybackState.STATE_NONE), MediaState.INACTIVE); - Assert.assertEquals(mMediaControlProfile.playerState2McsState(PlaybackState.STATE_STOPPED), + Assert.assertEquals( + mMediaControlProfile.playerState2McsState(PlaybackState.STATE_STOPPED), MediaState.PAUSED); - Assert.assertEquals(mMediaControlProfile.playerState2McsState(PlaybackState.STATE_PAUSED), + Assert.assertEquals( + mMediaControlProfile.playerState2McsState(PlaybackState.STATE_PAUSED), MediaState.PAUSED); - Assert.assertEquals(mMediaControlProfile.playerState2McsState(PlaybackState.STATE_PLAYING), + Assert.assertEquals( + mMediaControlProfile.playerState2McsState(PlaybackState.STATE_PLAYING), MediaState.PLAYING); Assert.assertEquals( mMediaControlProfile.playerState2McsState(PlaybackState.STATE_FAST_FORWARDING), @@ -198,7 +204,8 @@ public class MediaControlProfileTest { Assert.assertEquals( mMediaControlProfile.playerState2McsState(PlaybackState.STATE_BUFFERING), MediaState.PAUSED); - Assert.assertEquals(mMediaControlProfile.playerState2McsState(PlaybackState.STATE_ERROR), + Assert.assertEquals( + mMediaControlProfile.playerState2McsState(PlaybackState.STATE_ERROR), MediaState.INACTIVE); Assert.assertEquals( mMediaControlProfile.playerState2McsState(PlaybackState.STATE_CONNECTING), @@ -209,8 +216,9 @@ public class MediaControlProfileTest { Assert.assertEquals( mMediaControlProfile.playerState2McsState(PlaybackState.STATE_SKIPPING_TO_NEXT), MediaState.PAUSED); - Assert.assertEquals(mMediaControlProfile.playerState2McsState( - PlaybackState.STATE_SKIPPING_TO_QUEUE_ITEM), + Assert.assertEquals( + mMediaControlProfile.playerState2McsState( + PlaybackState.STATE_SKIPPING_TO_QUEUE_ITEM), MediaState.PAUSED); } @@ -221,7 +229,8 @@ public class MediaControlProfileTest { float playback_speed = 1.5f; long update_time = 77; - Assert.assertEquals(mMcpServiceCallbacks.onGetCurrentTrackPosition(), + Assert.assertEquals( + mMcpServiceCallbacks.onGetCurrentTrackPosition(), MediaControlGattServiceInterface.TRACK_POSITION_UNAVAILABLE); PlaybackState.Builder bob = new PlaybackState.Builder(mMockMediaData.state); @@ -229,7 +238,8 @@ public class MediaControlProfileTest { mMockMediaData.state = bob.build(); doReturn(mMockMediaData.state).when(mMockMediaPlayerWrapper).getPlaybackState(); - Assert.assertNotEquals(mMcpServiceCallbacks.onGetCurrentTrackPosition(), + Assert.assertNotEquals( + mMcpServiceCallbacks.onGetCurrentTrackPosition(), MediaControlGattServiceInterface.TRACK_POSITION_UNAVAILABLE); } @@ -276,8 +286,7 @@ public class MediaControlProfileTest { verify(mMockMediaPlayerWrapper, timeout(100).times(times)).seekTo(positionCaptor.capture()); // position cannot be negative and bigger than track duration - if (position < 0) - Assert.assertEquals(positionCaptor.getValue().longValue(), 0); + if (position < 0) Assert.assertEquals(positionCaptor.getValue().longValue(), 0); else if (position > duration) { Assert.assertEquals(positionCaptor.getValue().longValue(), duration); } else { @@ -328,18 +337,22 @@ public class MediaControlProfileTest { @Test public void testHandleMediaControlRequest() { - long actions = PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PAUSE - | PlaybackState.ACTION_STOP | PlaybackState.ACTION_SKIP_TO_PREVIOUS - | PlaybackState.ACTION_SKIP_TO_NEXT | PlaybackState.ACTION_REWIND - | PlaybackState.ACTION_FAST_FORWARD | PlaybackState.ACTION_SEEK_TO; + long actions = + PlaybackState.ACTION_PLAY + | PlaybackState.ACTION_PAUSE + | PlaybackState.ACTION_STOP + | PlaybackState.ACTION_SKIP_TO_PREVIOUS + | PlaybackState.ACTION_SKIP_TO_NEXT + | PlaybackState.ACTION_REWIND + | PlaybackState.ACTION_FAST_FORWARD + | PlaybackState.ACTION_SEEK_TO; long duration = 10; PlaybackState.Builder bob = new PlaybackState.Builder(mMockMediaData.state); bob.setActions(actions); mMockMediaData.state = bob.build(); - Request request = - new Request(Request.Opcodes.PLAY, 0); + Request request = new Request(Request.Opcodes.PLAY, 0); mMcpServiceCallbacks.onMediaControlRequest(request); verify(mMockMediaPlayerWrapper, timeout(100)).playCurrent(); request = new Request(Request.Opcodes.PAUSE, 0); @@ -349,27 +362,22 @@ public class MediaControlProfileTest { mMcpServiceCallbacks.onMediaControlRequest(request); verify(mMockMediaPlayerWrapper, timeout(100)).seekTo(0); verify(mMockMediaPlayerWrapper).stopCurrent(); - request = new Request( - Request.Opcodes.PREVIOUS_TRACK, 0); + request = new Request(Request.Opcodes.PREVIOUS_TRACK, 0); mMcpServiceCallbacks.onMediaControlRequest(request); verify(mMockMediaPlayerWrapper, timeout(100)).skipToPrevious(); - request = new Request( - Request.Opcodes.NEXT_TRACK, 0); + request = new Request(Request.Opcodes.NEXT_TRACK, 0); mMcpServiceCallbacks.onMediaControlRequest(request); verify(mMockMediaPlayerWrapper, timeout(100)).skipToNext(); - request = new Request( - Request.Opcodes.FAST_REWIND, 0); + request = new Request(Request.Opcodes.FAST_REWIND, 0); mMcpServiceCallbacks.onMediaControlRequest(request); verify(mMockMediaPlayerWrapper, timeout(100)).rewind(); - request = new Request( - Request.Opcodes.FAST_FORWARD, 0); + request = new Request(Request.Opcodes.FAST_FORWARD, 0); mMcpServiceCallbacks.onMediaControlRequest(request); verify(mMockMediaPlayerWrapper, timeout(100)).fastForward(); mMockMetadata.duration = Long.toString(duration); Assert.assertEquals(duration, mMediaControlProfile.getCurrentTrackDuration()); - request = new Request( - Request.Opcodes.MOVE_RELATIVE, 100); + request = new Request(Request.Opcodes.MOVE_RELATIVE, 100); mMcpServiceCallbacks.onMediaControlRequest(request); verify(mMockMediaPlayerWrapper, timeout(100)).seekTo(duration); @@ -410,26 +418,31 @@ public class MediaControlProfileTest { @Test public void testPlayerActions2McsSupportedOpcodes() { - long actions = PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PAUSE - | PlaybackState.ACTION_STOP | PlaybackState.ACTION_SKIP_TO_PREVIOUS - | PlaybackState.ACTION_SKIP_TO_NEXT | PlaybackState.ACTION_REWIND - | PlaybackState.ACTION_FAST_FORWARD | PlaybackState.ACTION_SEEK_TO; - int opcodes_supported = Request.SupportedOpcodes.STOP - | Request.SupportedOpcodes.PAUSE - | Request.SupportedOpcodes.PLAY - | Request.SupportedOpcodes.FAST_REWIND - | Request.SupportedOpcodes.PREVIOUS_TRACK - | Request.SupportedOpcodes.NEXT_TRACK - | Request.SupportedOpcodes.FAST_FORWARD - | Request.SupportedOpcodes.MOVE_RELATIVE; + long actions = + PlaybackState.ACTION_PLAY + | PlaybackState.ACTION_PAUSE + | PlaybackState.ACTION_STOP + | PlaybackState.ACTION_SKIP_TO_PREVIOUS + | PlaybackState.ACTION_SKIP_TO_NEXT + | PlaybackState.ACTION_REWIND + | PlaybackState.ACTION_FAST_FORWARD + | PlaybackState.ACTION_SEEK_TO; + int opcodes_supported = + Request.SupportedOpcodes.STOP + | Request.SupportedOpcodes.PAUSE + | Request.SupportedOpcodes.PLAY + | Request.SupportedOpcodes.FAST_REWIND + | Request.SupportedOpcodes.PREVIOUS_TRACK + | Request.SupportedOpcodes.NEXT_TRACK + | Request.SupportedOpcodes.FAST_FORWARD + | Request.SupportedOpcodes.MOVE_RELATIVE; Assert.assertEquals( mMediaControlProfile.playerActions2McsSupportedOpcodes(actions), opcodes_supported); // Verify toggle-style play/pause control support actions = PlaybackState.ACTION_PLAY_PAUSE; - opcodes_supported = Request.SupportedOpcodes.PAUSE - | Request.SupportedOpcodes.PLAY; + opcodes_supported = Request.SupportedOpcodes.PAUSE | Request.SupportedOpcodes.PLAY; Assert.assertEquals( mMediaControlProfile.playerActions2McsSupportedOpcodes(actions), opcodes_supported); @@ -447,11 +460,18 @@ public class MediaControlProfileTest { mMockMediaData.state = bob.build(); doReturn(mMockMediaData.state).when(mMockMediaPlayerWrapper).getPlaybackState(); - PlayerStateField[] state_fields = new PlayerStateField[] {PlayerStateField.PLAYBACK_STATE, - PlayerStateField.TRACK_DURATION, PlayerStateField.PLAYBACK_SPEED, - PlayerStateField.SEEKING_SPEED, PlayerStateField.PLAYING_ORDER, - PlayerStateField.TRACK_POSITION, PlayerStateField.PLAYER_NAME, - PlayerStateField.PLAYING_ORDER_SUPPORTED, PlayerStateField.OPCODES_SUPPORTED}; + PlayerStateField[] state_fields = + new PlayerStateField[] { + PlayerStateField.PLAYBACK_STATE, + PlayerStateField.TRACK_DURATION, + PlayerStateField.PLAYBACK_SPEED, + PlayerStateField.SEEKING_SPEED, + PlayerStateField.PLAYING_ORDER, + PlayerStateField.TRACK_POSITION, + PlayerStateField.PLAYER_NAME, + PlayerStateField.PLAYING_ORDER_SUPPORTED, + PlayerStateField.OPCODES_SUPPORTED + }; mMcpServiceCallbacks.onPlayerStateRequest(state_fields); // First time called from ListCallback. Give some time to verify if post function @@ -489,13 +509,10 @@ public class MediaControlProfileTest { private void testGetSupportedPlayingOrder(boolean is_shuffle_set, boolean is_repeat_set) { int expected_value = SupportedPlayingOrder.IN_ORDER_ONCE; - if (is_repeat_set) - expected_value |= SupportedPlayingOrder.IN_ORDER_REPEAT; + if (is_repeat_set) expected_value |= SupportedPlayingOrder.IN_ORDER_REPEAT; if (is_shuffle_set) { - if (is_repeat_set) - expected_value |= SupportedPlayingOrder.SHUFFLE_REPEAT; - else - expected_value |= SupportedPlayingOrder.SHUFFLE_ONCE; + if (is_repeat_set) expected_value |= SupportedPlayingOrder.SHUFFLE_REPEAT; + else expected_value |= SupportedPlayingOrder.SHUFFLE_ONCE; } doReturn(is_shuffle_set).when(mMockMediaPlayerWrapper).isShuffleSupported(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/obex/FakeObexServer.java b/android/app/tests/unit/src/com/android/bluetooth/obex/FakeObexServer.java index a040001b9b8..85beb8e1162 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/obex/FakeObexServer.java +++ b/android/app/tests/unit/src/com/android/bluetooth/obex/FakeObexServer.java @@ -29,8 +29,8 @@ import java.io.IOException; * A fake obex server for testing obex clients. Test cases should implement *Validator functions to * validate input and return appropriate responses for individual tests. * - * Note: it is important to not perform any testing Assert operations within the validators as that - * would crash the testing framework. + *

Note: it is important to not perform any testing Assert operations within the validators as + * that would crash the testing framework. */ public abstract class FakeObexServer { @@ -52,8 +52,8 @@ public abstract class FakeObexServer { public abstract int onPutValidator(Operation op); - public abstract int onSetPathValidator(HeaderSet request, HeaderSet reply, - boolean backup, boolean create); + public abstract int onSetPathValidator( + HeaderSet request, HeaderSet reply, boolean backup, boolean create); class Server extends ServerRequestHandler { @@ -63,8 +63,7 @@ public abstract class FakeObexServer { } @Override - public void onDisconnect(final HeaderSet request, HeaderSet reply) { - } + public void onDisconnect(final HeaderSet request, HeaderSet reply) {} @Override public int onGet(final Operation op) { @@ -82,13 +81,15 @@ public abstract class FakeObexServer { } @Override - public int onSetPath(final HeaderSet request, HeaderSet reply, final boolean backup, + public int onSetPath( + final HeaderSet request, + HeaderSet reply, + final boolean backup, final boolean create) { return onSetPathValidator(request, reply, backup, create); } @Override - public void onClose() { - } + public void onClose() {} } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/obex/FakeObexTransport.java b/android/app/tests/unit/src/com/android/bluetooth/obex/FakeObexTransport.java index b2b6c165ff5..27e0a29d46c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/obex/FakeObexTransport.java +++ b/android/app/tests/unit/src/com/android/bluetooth/obex/FakeObexTransport.java @@ -27,9 +27,9 @@ import java.io.PipedInputStream; import java.io.PipedOutputStream; /** - * A fake obex transport used for testing Client/Server connections. - * The transport uses two pairs of pipes to route input from the client to the server, and back. - * The obex transport is of the simplest form, returning default values for everything. + * A fake obex transport used for testing Client/Server connections. The transport uses two pairs of + * pipes to route input from the client to the server, and back. The obex transport is of the + * simplest form, returning default values for everything. */ public class FakeObexTransport { ObexTransport mClientTransport; @@ -81,24 +81,19 @@ public class FakeObexTransport { } @Override - public void connect() throws IOException { - } + public void connect() throws IOException {} @Override - public void create() throws IOException { - } + public void create() throws IOException {} @Override - public void disconnect() throws IOException { - } + public void disconnect() throws IOException {} @Override - public void listen() throws IOException { - } + public void listen() throws IOException {} @Override - public void close() throws IOException { - } + public void close() throws IOException {} public boolean isConnected() throws IOException { return true; diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBatchTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBatchTest.java index 2c013fc766f..5fb0108b248 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBatchTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBatchTest.java @@ -44,8 +44,22 @@ public class BluetoothOppBatchTest { @Before public void setUp() throws Exception { - mInitShareInfo = new BluetoothOppShareInfo(0, null, null, null, null, 0, - "00:11:22:33:44:55", 0, 0, BluetoothShare.STATUS_PENDING, 0, 0, 0, false); + mInitShareInfo = + new BluetoothOppShareInfo( + 0, + null, + null, + null, + null, + 0, + "00:11:22:33:44:55", + 0, + 0, + BluetoothShare.STATUS_PENDING, + 0, + 0, + 0, + false); mContext = InstrumentationRegistry.getInstrumentation().getContext(); mBluetoothOppBatch = new BluetoothOppBatch(mContext, mInitShareInfo); } @@ -62,24 +76,36 @@ public class BluetoothOppBatchTest { @Test public void addShare_shareInfoStoredCorrectly() { - BluetoothOppShareInfo newBluetoothOppShareInfo = new BluetoothOppShareInfo(1, null, null, - null, null, 0, "AA:BB:22:CD:E0:55", 0, 0, BluetoothShare.STATUS_PENDING, 0, 0, 0, - false); - - mBluetoothOppBatch.registerListener(new BluetoothOppBatch.BluetoothOppBatchListener() { - @Override - public void onShareAdded(int id) { - assertThat(id).isEqualTo(newBluetoothOppShareInfo.mId); - } - - @Override - public void onShareDeleted(int id) { - } - - @Override - public void onBatchCanceled() { - } - }); + BluetoothOppShareInfo newBluetoothOppShareInfo = + new BluetoothOppShareInfo( + 1, + null, + null, + null, + null, + 0, + "AA:BB:22:CD:E0:55", + 0, + 0, + BluetoothShare.STATUS_PENDING, + 0, + 0, + 0, + false); + + mBluetoothOppBatch.registerListener( + new BluetoothOppBatch.BluetoothOppBatchListener() { + @Override + public void onShareAdded(int id) { + assertThat(id).isEqualTo(newBluetoothOppShareInfo.mId); + } + + @Override + public void onShareDeleted(int id) {} + + @Override + public void onBatchCanceled() {} + }); assertThat(mBluetoothOppBatch.isEmpty()).isFalse(); assertThat(mBluetoothOppBatch.getNumShares()).isEqualTo(1); assertThat(mBluetoothOppBatch.hasShare(mInitShareInfo)).isTrue(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java index 3b5ede4f2ac..158a29caa91 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java @@ -77,15 +77,17 @@ public class BluetoothOppBtEnableActivityTest { @Test public void onCreate_clickOnEnable_launchEnablingActivity() { - ActivityScenario activityScenario = ActivityScenario.launch( - mIntent); + ActivityScenario activityScenario = + ActivityScenario.launch(mIntent); activityScenario.onActivity( activity -> activity.mOppManager = mock(BluetoothOppManager.class)); onView(withText(mTargetContext.getText(R.string.bt_enable_ok).toString())) .inRoot(isDialog()) .perform(ViewActions.scrollTo()); - onView(withText(mTargetContext.getText(R.string.bt_enable_ok).toString())).inRoot( - isDialog()).check(matches(isDisplayed())).perform(click()); + onView(withText(mTargetContext.getText(R.string.bt_enable_ok).toString())) + .inRoot(isDialog()) + .check(matches(isDisplayed())) + .perform(click()); intended(hasComponent(BluetoothOppBtEnablingActivity.class.getName())); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java index 83003113f4f..4625a2e4a36 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java @@ -60,8 +60,7 @@ import java.util.concurrent.atomic.AtomicBoolean; public class BluetoothOppBtEnablingActivityTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Spy - BluetoothMethodProxy mBluetoothMethodProxy; + @Spy BluetoothMethodProxy mBluetoothMethodProxy; Intent mIntent; Context mTargetContext; @@ -104,13 +103,14 @@ public class BluetoothOppBtEnablingActivityTest { BluetoothOppBtEnablingActivity.sBtEnablingTimeoutMs = spedUpTimeoutValue; doReturn(false).when(mBluetoothMethodProxy).bluetoothAdapterIsEnabled(any()); - ActivityScenario activityScenario = ActivityScenario.launch( - mIntent); + ActivityScenario activityScenario = + ActivityScenario.launch(mIntent); final BluetoothOppManager[] mOppManager = new BluetoothOppManager[1]; - activityScenario.onActivity(activity -> { - // Should be cancelled after timeout - mOppManager[0] = BluetoothOppManager.getInstance(activity); - }); + activityScenario.onActivity( + activity -> { + // Should be cancelled after timeout + mOppManager[0] = BluetoothOppManager.getInstance(activity); + }); Thread.sleep(spedUpTimeoutValue); assertThat(mOppManager[0].mSendingFlag).isEqualTo(false); assertActivityState(activityScenario, DESTROYED); @@ -119,8 +119,8 @@ public class BluetoothOppBtEnablingActivityTest { @Test public void onKeyDown_cancelProgress() throws Exception { doReturn(false).when(mBluetoothMethodProxy).bluetoothAdapterIsEnabled(any()); - ActivityScenario activityScenario = ActivityScenario.launch( - mIntent); + ActivityScenario activityScenario = + ActivityScenario.launch(mIntent); AtomicBoolean finishCalled = new AtomicBoolean(false); @@ -141,16 +141,16 @@ public class BluetoothOppBtEnablingActivityTest { @Test public void onCreate_bluetoothAlreadyEnabled_finishImmediately() throws Exception { doReturn(true).when(mBluetoothMethodProxy).bluetoothAdapterIsEnabled(any()); - ActivityScenario activityScenario = ActivityScenario.launch( - mIntent); + ActivityScenario activityScenario = + ActivityScenario.launch(mIntent); assertActivityState(activityScenario, DESTROYED); } @Test public void broadcastReceiver_onReceive_finishImmediately() throws Exception { doReturn(false).when(mBluetoothMethodProxy).bluetoothAdapterIsEnabled(any()); - ActivityScenario activityScenario = ActivityScenario.launch( - mIntent); + ActivityScenario activityScenario = + ActivityScenario.launch(mIntent); AtomicBoolean finishCalled = new AtomicBoolean(false); activityScenario.onActivity( @@ -165,22 +165,25 @@ public class BluetoothOppBtEnablingActivityTest { } private void assertActivityState(ActivityScenario activityScenario, Lifecycle.State state) - throws Exception { + throws Exception { // TODO: Change this into an event driven systems Thread.sleep(3_000); assertThat(activityScenario.getState()).isEqualTo(state); } private void enableActivity(boolean enable) { - int enabledState = enable ? COMPONENT_ENABLED_STATE_ENABLED - : COMPONENT_ENABLED_STATE_DEFAULT; - - mTargetContext.getPackageManager().setApplicationEnabledSetting( - mTargetContext.getPackageName(), enabledState, DONT_KILL_APP); - - ComponentName activityName = new ComponentName(mTargetContext, - BluetoothOppTransferActivity.class); - mTargetContext.getPackageManager().setComponentEnabledSetting( - activityName, enabledState, DONT_KILL_APP); + int enabledState = + enable ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DEFAULT; + + mTargetContext + .getPackageManager() + .setApplicationEnabledSetting( + mTargetContext.getPackageName(), enabledState, DONT_KILL_APP); + + ComponentName activityName = + new ComponentName(mTargetContext, BluetoothOppTransferActivity.class); + mTargetContext + .getPackageManager() + .setComponentEnabledSetting(activityName, enabledState, DONT_KILL_APP); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppHandoverReceiverTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppHandoverReceiverTest.java index b27740bf0be..6c3fcbb66fe 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppHandoverReceiverTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppHandoverReceiverTest.java @@ -56,16 +56,16 @@ public class BluetoothOppHandoverReceiverTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Spy - BluetoothMethodProxy mCallProxy = BluetoothMethodProxy.getInstance(); + @Spy BluetoothMethodProxy mCallProxy = BluetoothMethodProxy.getInstance(); @Before public void setUp() { mContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); BluetoothMethodProxy.setInstanceForTesting(mCallProxy); doReturn(0).when(mCallProxy).contentResolverDelete(any(), any(Uri.class), any(), any()); - doReturn(null).when(mCallProxy).contentResolverInsert( - any(), eq(BluetoothShare.CONTENT_URI), any()); + doReturn(null) + .when(mCallProxy) + .contentResolverInsert(any(), eq(BluetoothShare.CONTENT_URI), any()); } @After @@ -78,8 +78,10 @@ public class BluetoothOppHandoverReceiverTest { Intent intent = new Intent(Constants.ACTION_HANDOVER_SEND); String address = "AA:BB:CC:DD:EE:FF"; Uri uri = Uri.parse("content:///abc/xyz.txt"); - BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class)) - .getAdapter().getRemoteDevice(address); + BluetoothDevice device = + (mContext.getSystemService(BluetoothManager.class)) + .getAdapter() + .getRemoteDevice(address); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.setType("text/plain"); @@ -92,8 +94,9 @@ public class BluetoothOppHandoverReceiverTest { // this will run BluetoothOppManager#startTransfer, which will then make // InsertShareInfoThread insert into content resolver - verify(mCallProxy, timeout(3_000).times(1)).contentResolverInsert(any(), - eq(BluetoothShare.CONTENT_URI), nullable(ContentValues.class)); + verify(mCallProxy, timeout(3_000).times(1)) + .contentResolverInsert( + any(), eq(BluetoothShare.CONTENT_URI), nullable(ContentValues.class)); BluetoothOppManager.setInstance(null); } @@ -101,12 +104,16 @@ public class BluetoothOppHandoverReceiverTest { public void onReceive_withActionHandoverSendMultiple_startTransfer() { Intent intent = new Intent(Constants.ACTION_HANDOVER_SEND_MULTIPLE); String address = "AA:BB:CC:DD:EE:FF"; - ArrayList uris = new ArrayList( - List.of(Uri.parse("content:///abc/xyz.txt"), - Uri.parse("content:///a/b/c/d/x/y/z.txt"), - Uri.parse("content:///123/456.txt"))); - BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class)) - .getAdapter().getRemoteDevice(address); + ArrayList uris = + new ArrayList( + List.of( + Uri.parse("content:///abc/xyz.txt"), + Uri.parse("content:///a/b/c/d/x/y/z.txt"), + Uri.parse("content:///123/456.txt"))); + BluetoothDevice device = + (mContext.getSystemService(BluetoothManager.class)) + .getAdapter() + .getRemoteDevice(address); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); intent.putExtra(Intent.EXTRA_STREAM, uris); intent.setType("text/plain"); @@ -119,8 +126,9 @@ public class BluetoothOppHandoverReceiverTest { // this will run BluetoothOppManager#startTransfer, which will then make // InsertShareInfoThread insert into content resolver - verify(mCallProxy, timeout(3_000).times(3)).contentResolverInsert(any(), - eq(BluetoothShare.CONTENT_URI), nullable(ContentValues.class)); + verify(mCallProxy, timeout(3_000).times(3)) + .contentResolverInsert( + any(), eq(BluetoothShare.CONTENT_URI), nullable(ContentValues.class)); BluetoothOppManager.setInstance(null); } @@ -128,14 +136,17 @@ public class BluetoothOppHandoverReceiverTest { public void onReceive_withActionStopHandover_triggerContentResolverDelete() { Intent intent = new Intent(Constants.ACTION_STOP_HANDOVER); String address = "AA:BB:CC:DD:EE:FF"; - BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class)) - .getAdapter().getRemoteDevice(address); + BluetoothDevice device = + (mContext.getSystemService(BluetoothManager.class)) + .getAdapter() + .getRemoteDevice(address); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); intent.putExtra(Constants.EXTRA_BT_OPP_TRANSFER_ID, 0); new BluetoothOppHandoverReceiver().onReceive(mContext, intent); - verify(mCallProxy).contentResolverDelete(any(), any(), - nullable(String.class), nullable(String[].class)); + verify(mCallProxy) + .contentResolverDelete( + any(), any(), nullable(String.class), nullable(String[].class)); } -} \ No newline at end of file +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java index 234a3134c42..7ee7bd25f4f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java @@ -73,8 +73,7 @@ public class BluetoothOppLauncherActivityTest { BluetoothMethodProxy mMethodProxy; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - BluetoothOppManager mBluetoothOppManager; + @Mock BluetoothOppManager mBluetoothOppManager; // Activity tests can sometimes flaky because of external factors like system dialog, etc. // making the expected Espresso's root not focused or the activity doesn't show up. @@ -85,8 +84,7 @@ public class BluetoothOppLauncherActivityTest { public void setUp() throws Exception { Assume.assumeTrue(BluetoothProperties.isProfileOppEnabled().orElse(false)); - mTargetContext = spy(new ContextWrapper( - ApplicationProvider.getApplicationContext())); + mTargetContext = spy(new ContextWrapper(ApplicationProvider.getApplicationContext())); mMethodProxy = spy(BluetoothMethodProxy.getInstance()); BluetoothMethodProxy.setInstanceForTesting(mMethodProxy); @@ -112,16 +110,16 @@ public class BluetoothOppLauncherActivityTest { @Test public void onCreate_withNoAction_returnImmediately() throws Exception { - ActivityScenario activityScenario = ActivityScenario.launch( - mIntent); + ActivityScenario activityScenario = + ActivityScenario.launch(mIntent); assertActivityState(activityScenario, Lifecycle.State.DESTROYED); } @Test public void onCreate_withActionSend_withoutMetadata_finishImmediately() throws Exception { mIntent.setAction(Intent.ACTION_SEND); - ActivityScenario activityScenario = ActivityScenario.launch( - mIntent); + ActivityScenario activityScenario = + ActivityScenario.launch(mIntent); assertActivityState(activityScenario, Lifecycle.State.DESTROYED); } @@ -129,8 +127,8 @@ public class BluetoothOppLauncherActivityTest { public void onCreate_withActionSendMultiple_withoutMetadata_finishImmediately() throws Exception { mIntent.setAction(Intent.ACTION_SEND_MULTIPLE); - ActivityScenario activityScenario = ActivityScenario.launch( - mIntent); + ActivityScenario activityScenario = + ActivityScenario.launch(mIntent); assertActivityState(activityScenario, Lifecycle.State.DESTROYED); } @@ -186,10 +184,10 @@ public class BluetoothOppLauncherActivityTest { final String shareContent = "\na < b & c > a string to trigger pattern match with url: \r" + "www.google.com, phone number: +821023456798, and email: abc@test.com"; - scenario.onActivity(activity -> { - fileUri[0] = activity.createFileForSharedContent(activity, shareContent); - - }); + scenario.onActivity( + activity -> { + fileUri[0] = activity.createFileForSharedContent(activity, shareContent); + }); assertThat(fileUri[0].toString().endsWith(".html")).isTrue(); File file = new File(fileUri[0].getPath()); @@ -204,11 +202,13 @@ public class BluetoothOppLauncherActivityTest { // Unsupported action, the activity will stay without being finished right the way mIntent.setAction("unsupported-action"); ActivityScenario scenario = ActivityScenario.launch(mIntent); - doThrow(new IllegalArgumentException()).when(mBluetoothOppManager).saveSendingFileInfo( - any(), any(String.class), any(), any()); - scenario.onActivity(activity -> { - activity.sendFileInfo("text/plain", "content:///abc.txt", false, false); - }); + doThrow(new IllegalArgumentException()) + .when(mBluetoothOppManager) + .saveSendingFileInfo(any(), any(String.class), any(), any()); + scenario.onActivity( + activity -> { + activity.sendFileInfo("text/plain", "content:///abc.txt", false, false); + }); assertActivityState(scenario, Lifecycle.State.DESTROYED); } @@ -219,17 +219,19 @@ public class BluetoothOppLauncherActivityTest { assertThat(activityScenario.getState()).isEqualTo(state); } - private void enableActivity(boolean enable) { - int enabledState = enable ? COMPONENT_ENABLED_STATE_ENABLED - : COMPONENT_ENABLED_STATE_DEFAULT; - - mTargetContext.getPackageManager().setApplicationEnabledSetting( - mTargetContext.getPackageName(), enabledState, DONT_KILL_APP); - - ComponentName activityName = new ComponentName(mTargetContext, - BluetoothOppLauncherActivity.class); - mTargetContext.getPackageManager().setComponentEnabledSetting( - activityName, enabledState, DONT_KILL_APP); + int enabledState = + enable ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DEFAULT; + + mTargetContext + .getPackageManager() + .setApplicationEnabledSetting( + mTargetContext.getPackageName(), enabledState, DONT_KILL_APP); + + ComponentName activityName = + new ComponentName(mTargetContext, BluetoothOppLauncherActivity.class); + mTargetContext + .getPackageManager() + .setComponentEnabledSetting(activityName, enabledState, DONT_KILL_APP); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java index 695703c1f39..77163fa53bc 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java @@ -64,14 +64,17 @@ public class BluetoothOppManagerTest { @Before public void setUp() { - mContext = spy(new ContextWrapper( - InstrumentationRegistry.getInstrumentation().getTargetContext())); + mContext = + spy( + new ContextWrapper( + InstrumentationRegistry.getInstrumentation().getTargetContext())); mCallProxy = spy(BluetoothMethodProxy.getInstance()); BluetoothMethodProxy.setInstanceForTesting(mCallProxy); - doReturn(null).when(mCallProxy).contentResolverInsert( - any(), eq(BluetoothShare.CONTENT_URI), any()); + doReturn(null) + .when(mCallProxy) + .contentResolverInsert(any(), eq(BluetoothShare.CONTENT_URI), any()); Intents.init(); } @@ -88,54 +91,58 @@ public class BluetoothOppManagerTest { @Test public void - restoreApplicationData_afterSavingSingleSendingFileInfo_containsSendingFileInfoSaved() { + restoreApplicationData_afterSavingSingleSendingFileInfo_containsSendingFileInfoSaved() { BluetoothOppManager bluetoothOppManager = BluetoothOppManager.getInstance(mContext); bluetoothOppManager.mSendingFlag = true; - bluetoothOppManager.saveSendingFileInfo("text/plain", "content:///abc/xyz.txt", false, - true); + bluetoothOppManager.saveSendingFileInfo( + "text/plain", "content:///abc/xyz.txt", false, true); BluetoothOppManager.sInstance = null; - BluetoothOppManager restartedBluetoothOppManager = BluetoothOppManager.getInstance( - mContext); - assertThat(bluetoothOppManager.mSendingFlag).isEqualTo( - restartedBluetoothOppManager.mSendingFlag); - assertThat(bluetoothOppManager.mMultipleFlag).isEqualTo( - restartedBluetoothOppManager.mMultipleFlag); - assertThat(bluetoothOppManager.mUriOfSendingFile).isEqualTo( - restartedBluetoothOppManager.mUriOfSendingFile); - assertThat(bluetoothOppManager.mUrisOfSendingFiles).isEqualTo( - restartedBluetoothOppManager.mUrisOfSendingFiles); - assertThat(bluetoothOppManager.mMimeTypeOfSendingFile).isEqualTo( - restartedBluetoothOppManager.mMimeTypeOfSendingFile); - assertThat(bluetoothOppManager.mMimeTypeOfSendingFiles).isEqualTo( - restartedBluetoothOppManager.mMimeTypeOfSendingFiles); + BluetoothOppManager restartedBluetoothOppManager = + BluetoothOppManager.getInstance(mContext); + assertThat(bluetoothOppManager.mSendingFlag) + .isEqualTo(restartedBluetoothOppManager.mSendingFlag); + assertThat(bluetoothOppManager.mMultipleFlag) + .isEqualTo(restartedBluetoothOppManager.mMultipleFlag); + assertThat(bluetoothOppManager.mUriOfSendingFile) + .isEqualTo(restartedBluetoothOppManager.mUriOfSendingFile); + assertThat(bluetoothOppManager.mUrisOfSendingFiles) + .isEqualTo(restartedBluetoothOppManager.mUrisOfSendingFiles); + assertThat(bluetoothOppManager.mMimeTypeOfSendingFile) + .isEqualTo(restartedBluetoothOppManager.mMimeTypeOfSendingFile); + assertThat(bluetoothOppManager.mMimeTypeOfSendingFiles) + .isEqualTo(restartedBluetoothOppManager.mMimeTypeOfSendingFiles); } @Test public void - restoreApplicationData_afterSavingMultipleSendingFileInfo_containsSendingFileInfoSaved() { + restoreApplicationData_afterSavingMultipleSendingFileInfo_containsSendingFileInfoSaved() { BluetoothOppManager bluetoothOppManager = BluetoothOppManager.getInstance(mContext); bluetoothOppManager.mSendingFlag = true; - bluetoothOppManager.saveSendingFileInfo("text/plain", new ArrayList( - List.of(Uri.parse("content:///abc/xyz.txt"), Uri.parse("content:///123" - + "/456.txt"))), - false, true); + bluetoothOppManager.saveSendingFileInfo( + "text/plain", + new ArrayList( + List.of( + Uri.parse("content:///abc/xyz.txt"), + Uri.parse("content:///123" + "/456.txt"))), + false, + true); BluetoothOppManager.sInstance = null; - BluetoothOppManager restartedBluetoothOppManager = BluetoothOppManager.getInstance( - mContext); - assertThat(bluetoothOppManager.mSendingFlag).isEqualTo( - restartedBluetoothOppManager.mSendingFlag); - assertThat(bluetoothOppManager.mMultipleFlag).isEqualTo( - restartedBluetoothOppManager.mMultipleFlag); - assertThat(bluetoothOppManager.mUriOfSendingFile).isEqualTo( - restartedBluetoothOppManager.mUriOfSendingFile); - assertThat(bluetoothOppManager.mUrisOfSendingFiles).isEqualTo( - restartedBluetoothOppManager.mUrisOfSendingFiles); - assertThat(bluetoothOppManager.mMimeTypeOfSendingFile).isEqualTo( - restartedBluetoothOppManager.mMimeTypeOfSendingFile); - assertThat(bluetoothOppManager.mMimeTypeOfSendingFiles).isEqualTo( - restartedBluetoothOppManager.mMimeTypeOfSendingFiles); + BluetoothOppManager restartedBluetoothOppManager = + BluetoothOppManager.getInstance(mContext); + assertThat(bluetoothOppManager.mSendingFlag) + .isEqualTo(restartedBluetoothOppManager.mSendingFlag); + assertThat(bluetoothOppManager.mMultipleFlag) + .isEqualTo(restartedBluetoothOppManager.mMultipleFlag); + assertThat(bluetoothOppManager.mUriOfSendingFile) + .isEqualTo(restartedBluetoothOppManager.mUriOfSendingFile); + assertThat(bluetoothOppManager.mUrisOfSendingFiles) + .isEqualTo(restartedBluetoothOppManager.mUrisOfSendingFiles); + assertThat(bluetoothOppManager.mMimeTypeOfSendingFile) + .isEqualTo(restartedBluetoothOppManager.mMimeTypeOfSendingFile); + assertThat(bluetoothOppManager.mMimeTypeOfSendingFiles) + .isEqualTo(restartedBluetoothOppManager.mMimeTypeOfSendingFiles); } @Test @@ -165,30 +172,38 @@ public class BluetoothOppManagerTest { public void startTransfer_withMultipleUris_contentResolverInsertMultipleTimes() { BluetoothOppManager bluetoothOppManager = BluetoothOppManager.getInstance(mContext); String address = "AA:BB:CC:DD:EE:FF"; - bluetoothOppManager.saveSendingFileInfo("text/plain", new ArrayList( - List.of(Uri.parse("content:///abc/xyz.txt"), - Uri.parse("content:///a/b/c/d/x/y/z.docs"), - Uri.parse("content:///123/456.txt"))), false, true); - BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class)) - .getAdapter().getRemoteDevice(address); + bluetoothOppManager.saveSendingFileInfo( + "text/plain", + new ArrayList( + List.of( + Uri.parse("content:///abc/xyz.txt"), + Uri.parse("content:///a/b/c/d/x/y/z.docs"), + Uri.parse("content:///123/456.txt"))), + false, + true); + BluetoothDevice device = + (mContext.getSystemService(BluetoothManager.class)) + .getAdapter() + .getRemoteDevice(address); bluetoothOppManager.startTransfer(device); // add 2 files - verify(mCallProxy, timeout(5_000) - .times(3)).contentResolverInsert(any(), nullable(Uri.class), - nullable(ContentValues.class)); + verify(mCallProxy, timeout(5_000).times(3)) + .contentResolverInsert(any(), nullable(Uri.class), nullable(ContentValues.class)); } @Test public void startTransfer_withOneUri_contentResolverInsertOnce() { BluetoothOppManager bluetoothOppManager = BluetoothOppManager.getInstance(mContext); String address = "AA:BB:CC:DD:EE:FF"; - bluetoothOppManager.saveSendingFileInfo("text/plain", "content:///abc/xyz.txt", - false, true); - BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class)) - .getAdapter().getRemoteDevice(address); + bluetoothOppManager.saveSendingFileInfo( + "text/plain", "content:///abc/xyz.txt", false, true); + BluetoothDevice device = + (mContext.getSystemService(BluetoothManager.class)) + .getAdapter() + .getRemoteDevice(address); bluetoothOppManager.startTransfer(device); - verify(mCallProxy, timeout(5_000).times(1)).contentResolverInsert(any(), - nullable(Uri.class), nullable(ContentValues.class)); + verify(mCallProxy, timeout(5_000).times(1)) + .contentResolverInsert(any(), nullable(Uri.class), nullable(ContentValues.class)); } @Ignore("b/267270055") @@ -197,18 +212,21 @@ public class BluetoothOppManagerTest { throws InterruptedException { BluetoothOppManager bluetoothOppManager = BluetoothOppManager.getInstance(mContext); String address = "AA:BB:CC:DD:EE:FF"; - bluetoothOppManager.saveSendingFileInfo("text/plain", "content:///abc/xyz.txt", - false, true); - BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class)) - .getAdapter().getRemoteDevice(address); + bluetoothOppManager.saveSendingFileInfo( + "text/plain", "content:///abc/xyz.txt", false, true); + BluetoothDevice device = + (mContext.getSystemService(BluetoothManager.class)) + .getAdapter() + .getRemoteDevice(address); AtomicBoolean intended = new AtomicBoolean(false); - intending(anyIntent()).respondWithFunction( - intent -> { - // verify that at least one exceeding thread is blocked - intended.set(true); - return null; - }); + intending(anyIntent()) + .respondWithFunction( + intent -> { + // verify that at least one exceeding thread is blocked + intended.set(true); + return null; + }); // try flushing the transferring queue, for (int i = 0; i < ALLOWED_INSERT_SHARE_THREAD_NUMBER + 15; i++) { @@ -216,9 +234,8 @@ public class BluetoothOppManagerTest { } // success at least ALLOWED_INSERT_SHARE_THREAD_NUMBER times - verify(mCallProxy, - timeout(5_000).atLeast(ALLOWED_INSERT_SHARE_THREAD_NUMBER)).contentResolverInsert( - any(), nullable(Uri.class), nullable(ContentValues.class)); + verify(mCallProxy, timeout(5_000).atLeast(ALLOWED_INSERT_SHARE_THREAD_NUMBER)) + .contentResolverInsert(any(), nullable(Uri.class), nullable(ContentValues.class)); // there is at least a failed attempt assertThat(intended.get()).isTrue(); @@ -238,8 +255,8 @@ public class BluetoothOppManagerTest { BluetoothOppUtility.sSendFileMap.clear(); Uri uri = Uri.parse("content:///a/new/folder/abc/xyz.txt"); assertThat(BluetoothOppUtility.sSendFileMap.size()).isEqualTo(0); - BluetoothOppManager.getInstance(mContext).saveSendingFileInfo("text/plain", - uri.toString(), false, true); + BluetoothOppManager.getInstance(mContext) + .saveSendingFileInfo("text/plain", uri.toString(), false, true); assertThat(BluetoothOppUtility.sSendFileMap.size()).isEqualTo(1); BluetoothOppManager.getInstance(mContext).cleanUpSendingFileInfo(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppNotificationTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppNotificationTest.java index ed4a086a6a2..9cdbf70e3b4 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppNotificationTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppNotificationTest.java @@ -63,8 +63,7 @@ public class BluetoothOppNotificationTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - BluetoothMethodProxy mMethodProxy; + @Mock BluetoothMethodProxy mMethodProxy; Context mTargetContext; @@ -80,12 +79,12 @@ public class BluetoothOppNotificationTest { @Before public void setUp() throws Exception { - mTargetContext = spy(new ContextWrapper( - ApplicationProvider.getApplicationContext())); + mTargetContext = spy(new ContextWrapper(ApplicationProvider.getApplicationContext())); BluetoothMethodProxy.setInstanceForTesting(mMethodProxy); - InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> - mOppNotification = new BluetoothOppNotification(mTargetContext)); + InstrumentationRegistry.getInstrumentation() + .runOnMainSync( + () -> mOppNotification = new BluetoothOppNotification(mTargetContext)); Intents.init(); TestUtils.setUpUiTest(); @@ -93,12 +92,15 @@ public class BluetoothOppNotificationTest { UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).openNotification(); // Enable BluetoothOppReceiver and then check for dismissed notification - mReceiverName = new ComponentName(mTargetContext, - com.android.bluetooth.opp.BluetoothOppReceiver.class); - mPreviousState = mTargetContext.getPackageManager().getComponentEnabledSetting( - mReceiverName); - mTargetContext.getPackageManager().setComponentEnabledSetting( - mReceiverName, COMPONENT_ENABLED_STATE_ENABLED, DONT_KILL_APP); + mReceiverName = + new ComponentName( + mTargetContext, com.android.bluetooth.opp.BluetoothOppReceiver.class); + mPreviousState = + mTargetContext.getPackageManager().getComponentEnabledSetting(mReceiverName); + mTargetContext + .getPackageManager() + .setComponentEnabledSetting( + mReceiverName, COMPONENT_ENABLED_STATE_ENABLED, DONT_KILL_APP); // clear all OPP notifications before each test mOppNotification.cancelOppNotifications(); @@ -113,8 +115,9 @@ public class BluetoothOppNotificationTest { BluetoothMethodProxy.setInstanceForTesting(null); Intents.release(); - mTargetContext.getPackageManager().setComponentEnabledSetting( - mReceiverName, mPreviousState, DONT_KILL_APP); + mTargetContext + .getPackageManager() + .setComponentEnabledSetting(mReceiverName, mPreviousState, DONT_KILL_APP); // clear all OPP notifications after each test mOppNotification.cancelOppNotifications(); @@ -132,35 +135,67 @@ public class BluetoothOppNotificationTest { int confirmation = BluetoothShare.USER_CONFIRMATION_CONFIRMED; int confirmationHandoverInitiated = BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED; String destination = "AA:BB:CC:DD:EE:FF"; - MatrixCursor cursor = new MatrixCursor(new String[]{ - BluetoothShare.TIMESTAMP, BluetoothShare.DIRECTION, BluetoothShare._ID, - BluetoothShare.TOTAL_BYTES, BluetoothShare.CURRENT_BYTES, BluetoothShare._DATA, - BluetoothShare.FILENAME_HINT, BluetoothShare.USER_CONFIRMATION, - BluetoothShare.DESTINATION, BluetoothShare.STATUS - }); - cursor.addRow(new Object[]{ - timestamp, dir, id, total, current, null, null, confirmation, destination, status - }); - cursor.addRow(new Object[]{ - timestamp + 10L, dir, id, total, current, null, null, confirmationHandoverInitiated, - destination, status - }); - doReturn(cursor).when(mMethodProxy).contentResolverQuery(any(), - eq(BluetoothShare.CONTENT_URI), any(), any(), any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothShare.TIMESTAMP, + BluetoothShare.DIRECTION, + BluetoothShare._ID, + BluetoothShare.TOTAL_BYTES, + BluetoothShare.CURRENT_BYTES, + BluetoothShare._DATA, + BluetoothShare.FILENAME_HINT, + BluetoothShare.USER_CONFIRMATION, + BluetoothShare.DESTINATION, + BluetoothShare.STATUS + }); + cursor.addRow( + new Object[] { + timestamp, + dir, + id, + total, + current, + null, + null, + confirmation, + destination, + status + }); + cursor.addRow( + new Object[] { + timestamp + 10L, + dir, + id, + total, + current, + null, + null, + confirmationHandoverInitiated, + destination, + status + }); + doReturn(cursor) + .when(mMethodProxy) + .contentResolverQuery( + any(), eq(BluetoothShare.CONTENT_URI), any(), any(), any(), any()); mOppNotification.updateActiveNotification(); - //confirm handover case does broadcast - verify(mTargetContext).sendBroadcast(any(), eq(Constants.HANDOVER_STATUS_PERMISSION), - any()); + // confirm handover case does broadcast + verify(mTargetContext) + .sendBroadcast(any(), eq(Constants.HANDOVER_STATUS_PERMISSION), any()); - final UiDevice device = UiDevice.getInstance( - androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); + final UiDevice device = + UiDevice.getInstance( + androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); device.openNotification(); - String titleString = mTargetContext.getString(R.string.notification_receiving, - mTargetContext.getString(R.string.unknown_file)); + String titleString = + mTargetContext.getString( + R.string.notification_receiving, + mTargetContext.getString(R.string.unknown_file)); device.wait(Until.hasObject(By.text(titleString)), TIMEOUT_MS); UiObject2 title = device.findObject(By.text(titleString)); assertThat(title).isNotNull(); @@ -179,26 +214,56 @@ public class BluetoothOppNotificationTest { long current = 100; int confirmation = BluetoothShare.USER_CONFIRMATION_CONFIRMED; String destination = "AA:BB:CC:DD:EE:FF"; - MatrixCursor cursor = new MatrixCursor(new String[]{ - BluetoothShare.TIMESTAMP, BluetoothShare.DIRECTION, BluetoothShare._ID, - BluetoothShare.TOTAL_BYTES, BluetoothShare.CURRENT_BYTES, BluetoothShare._DATA, - BluetoothShare.FILENAME_HINT, BluetoothShare.USER_CONFIRMATION, - BluetoothShare.DESTINATION, BluetoothShare.STATUS - }); - cursor.addRow(new Object[]{ - timestamp, dir, id, total, current, null, null, confirmation, destination, status - }); - cursor.addRow(new Object[]{ - timestamp + 10L, dir, id, total, current, null, null, confirmation, - destination, statusError - }); - doReturn(cursor).when(mMethodProxy).contentResolverQuery(any(), - eq(BluetoothShare.CONTENT_URI), any(), any(), any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothShare.TIMESTAMP, + BluetoothShare.DIRECTION, + BluetoothShare._ID, + BluetoothShare.TOTAL_BYTES, + BluetoothShare.CURRENT_BYTES, + BluetoothShare._DATA, + BluetoothShare.FILENAME_HINT, + BluetoothShare.USER_CONFIRMATION, + BluetoothShare.DESTINATION, + BluetoothShare.STATUS + }); + cursor.addRow( + new Object[] { + timestamp, + dir, + id, + total, + current, + null, + null, + confirmation, + destination, + status + }); + cursor.addRow( + new Object[] { + timestamp + 10L, + dir, + id, + total, + current, + null, + null, + confirmation, + destination, + statusError + }); + doReturn(cursor) + .when(mMethodProxy) + .contentResolverQuery( + any(), eq(BluetoothShare.CONTENT_URI), any(), any(), any(), any()); mOppNotification.updateCompletedNotification(); - final UiDevice device = UiDevice.getInstance( - androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); + final UiDevice device = + UiDevice.getInstance( + androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); device.openNotification(); @@ -229,26 +294,56 @@ public class BluetoothOppNotificationTest { long current = 100; int confirmation = BluetoothShare.USER_CONFIRMATION_CONFIRMED; String destination = "AA:BB:CC:DD:EE:FF"; - MatrixCursor cursor = new MatrixCursor(new String[]{ - BluetoothShare.TIMESTAMP, BluetoothShare.DIRECTION, BluetoothShare._ID, - BluetoothShare.TOTAL_BYTES, BluetoothShare.CURRENT_BYTES, BluetoothShare._DATA, - BluetoothShare.FILENAME_HINT, BluetoothShare.USER_CONFIRMATION, - BluetoothShare.DESTINATION, BluetoothShare.STATUS - }); - cursor.addRow(new Object[]{ - timestamp, dir, id, total, current, null, null, confirmation, destination, status - }); - cursor.addRow(new Object[]{ - timestamp + 10L, dir, id, total, current, null, null, confirmation, - destination, statusError - }); - doReturn(cursor).when(mMethodProxy).contentResolverQuery(any(), - eq(BluetoothShare.CONTENT_URI), any(), any(), any(), any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothShare.TIMESTAMP, + BluetoothShare.DIRECTION, + BluetoothShare._ID, + BluetoothShare.TOTAL_BYTES, + BluetoothShare.CURRENT_BYTES, + BluetoothShare._DATA, + BluetoothShare.FILENAME_HINT, + BluetoothShare.USER_CONFIRMATION, + BluetoothShare.DESTINATION, + BluetoothShare.STATUS + }); + cursor.addRow( + new Object[] { + timestamp, + dir, + id, + total, + current, + null, + null, + confirmation, + destination, + status + }); + cursor.addRow( + new Object[] { + timestamp + 10L, + dir, + id, + total, + current, + null, + null, + confirmation, + destination, + statusError + }); + doReturn(cursor) + .when(mMethodProxy) + .contentResolverQuery( + any(), eq(BluetoothShare.CONTENT_URI), any(), any(), any(), any()); mOppNotification.updateCompletedNotification(); - final UiDevice device = UiDevice.getInstance( - androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); + final UiDevice device = + UiDevice.getInstance( + androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); device.openNotification(); @@ -282,44 +377,65 @@ public class BluetoothOppNotificationTest { mOppNotification.mNotificationMgr = spy(mOppNotification.mNotificationMgr); - MatrixCursor cursor = new MatrixCursor(new String[]{ - BluetoothShare.TIMESTAMP, BluetoothShare.DIRECTION, BluetoothShare._ID, - BluetoothShare.TOTAL_BYTES, BluetoothShare.CURRENT_BYTES, BluetoothShare._DATA, - BluetoothShare.FILENAME_HINT, BluetoothShare.USER_CONFIRMATION, BluetoothShare.URI, - BluetoothShare.DESTINATION, BluetoothShare.STATUS, BluetoothShare.MIMETYPE - }); - cursor.addRow(new Object[]{ - timestamp, dir, id, total, current, null, null, confirmation, url, destination, - status, mimeType - }); - doReturn(cursor).when(mMethodProxy).contentResolverQuery(any(), - eq(com.android.bluetooth.opp.BluetoothShare.CONTENT_URI), any(), any(), any(), - any()); + MatrixCursor cursor = + new MatrixCursor( + new String[] { + BluetoothShare.TIMESTAMP, BluetoothShare.DIRECTION, BluetoothShare._ID, + BluetoothShare.TOTAL_BYTES, BluetoothShare.CURRENT_BYTES, + BluetoothShare._DATA, + BluetoothShare.FILENAME_HINT, BluetoothShare.USER_CONFIRMATION, + BluetoothShare.URI, + BluetoothShare.DESTINATION, BluetoothShare.STATUS, + BluetoothShare.MIMETYPE + }); + cursor.addRow( + new Object[] { + timestamp, + dir, + id, + total, + current, + null, + null, + confirmation, + url, + destination, + status, + mimeType + }); + doReturn(cursor) + .when(mMethodProxy) + .contentResolverQuery( + any(), + eq(com.android.bluetooth.opp.BluetoothShare.CONTENT_URI), + any(), + any(), + any(), + any()); mOppNotification.updateIncomingFileConfirmNotification(); - final UiDevice device = UiDevice.getInstance( - androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); + final UiDevice device = + UiDevice.getInstance( + androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()); - String titleString = mTargetContext.getString( - R.string.incoming_file_confirm_Notification_title); + String titleString = + mTargetContext.getString(R.string.incoming_file_confirm_Notification_title); - String confirmString = mTargetContext.getString( - R.string.incoming_file_confirm_ok); - String declineString = mTargetContext.getString( - R.string.incoming_file_confirm_cancel); + String confirmString = mTargetContext.getString(R.string.incoming_file_confirm_ok); + String declineString = mTargetContext.getString(R.string.incoming_file_confirm_cancel); device.wait(Until.hasObject(By.text(titleString)), TIMEOUT_MS); UiObject2 title = device.findObject(By.text(titleString)); UiObject2 buttonOk = device.findObject(By.text(confirmString)); // In AOSP, all actions' titles are converted into upper case - if(buttonOk == null) { + if (buttonOk == null) { buttonOk = device.findObject(By.text(confirmString.toUpperCase())); } UiObject2 buttonDecline = device.findObject(By.text(declineString)); // In AOSP, all actions' titles are converted into upper case - if(buttonDecline == null) { + if (buttonDecline == null) { buttonDecline = device.findObject(By.text(declineString.toUpperCase())); } @@ -343,4 +459,3 @@ public class BluetoothOppNotificationTest { assertThat(device.findObject(By.text(declineString.toUpperCase()))).isNull(); } } - diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java index 60a04b61494..e848b52c8f3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java @@ -61,12 +61,10 @@ import java.util.concurrent.TimeUnit; public class BluetoothOppObexClientSessionTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - BluetoothMethodProxy mMethodProxy; + @Mock BluetoothMethodProxy mMethodProxy; Context mTargetContext; - @Mock - BluetoothObexTransport mTransport; + @Mock BluetoothObexTransport mTransport; BluetoothOppObexClientSession mClientSession; @@ -104,11 +102,24 @@ public class BluetoothOppObexClientSessionTest { int currentBytes = 42; int timestamp = 123456789; boolean mediaScanned = false; - BluetoothOppShareInfo shareInfo = new BluetoothOppShareInfo(0, uri, hintString, filename, - mimetype, direction, destination, visibility, confirm, status, totalBytes, - currentBytes, timestamp, mediaScanned); - BluetoothOppSendFileInfo sendFileInfo = new BluetoothOppSendFileInfo( - filename, mimetype, totalBytes, null, status); + BluetoothOppShareInfo shareInfo = + new BluetoothOppShareInfo( + 0, + uri, + hintString, + filename, + mimetype, + direction, + destination, + visibility, + confirm, + status, + totalBytes, + currentBytes, + timestamp, + mediaScanned); + BluetoothOppSendFileInfo sendFileInfo = + new BluetoothOppSendFileInfo(filename, mimetype, totalBytes, null, status); BluetoothOppUtility.putSendFileInfo(uri, sendFileInfo); // throw exception so the session will not connect @@ -116,15 +127,17 @@ public class BluetoothOppObexClientSessionTest { doThrow(new IOException()).when(mTransport).openOutputStream(); CountDownLatch sessionCompletedLatch = new CountDownLatch(1); - mClientSession.start(new Handler(Looper.getMainLooper()) { - @Override - public void handleMessage(Message msg) { - super.handleMessage(msg); - if (msg.what == MSG_SESSION_COMPLETE) { - sessionCompletedLatch.countDown(); - } - } - }, 1); + mClientSession.start( + new Handler(Looper.getMainLooper()) { + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + if (msg.what == MSG_SESSION_COMPLETE) { + sessionCompletedLatch.countDown(); + } + } + }, + 1); // make mWaitingForShare be false mClientSession.addShare(shareInfo); @@ -157,11 +170,24 @@ public class BluetoothOppObexClientSessionTest { int currentBytes = 42; int timestamp = 123456789; boolean mediaScanned = false; - BluetoothOppShareInfo shareInfo = new BluetoothOppShareInfo(0, uri, hintString, filename, - mimetype, direction, destination, visibility, confirm, status, totalBytes, - currentBytes, timestamp, mediaScanned); - BluetoothOppSendFileInfo sendFileInfo = new BluetoothOppSendFileInfo( - filename, mimetype, totalBytes, null, status); + BluetoothOppShareInfo shareInfo = + new BluetoothOppShareInfo( + 0, + uri, + hintString, + filename, + mimetype, + direction, + destination, + visibility, + confirm, + status, + totalBytes, + currentBytes, + timestamp, + mediaScanned); + BluetoothOppSendFileInfo sendFileInfo = + new BluetoothOppSendFileInfo(filename, mimetype, totalBytes, null, status); BluetoothOppObexClientSession.ClientThread thread = mClientSession @@ -174,7 +200,7 @@ public class BluetoothOppObexClientSessionTest { thread.mCs = new ClientSession(mTransport); thread.addShare(shareInfo); - //thread.mCs.put() will throw because the obexconnection is not connected + // thread.mCs.put() will throw because the obexconnection is not connected assertThat(thread.sendFile(sendFileInfo)).isEqualTo(BluetoothShare.STATUS_OBEX_DATA_ERROR); } @@ -206,8 +232,7 @@ public class BluetoothOppObexClientSessionTest { InputStream is = mock(InputStream.class); byte[] buffer = new byte[2]; int size = 10000; - doReturn(500, 500, -1).when(is).read(eq(buffer), anyInt(), - anyInt()); + doReturn(500, 500, -1).when(is).read(eq(buffer), anyInt(), anyInt()); assertThat(BluetoothOppObexClientSession.readFully(is, buffer, size)).isEqualTo(1000); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java index 2e5bf6383e9..6b45823e1ca 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java @@ -62,27 +62,24 @@ import java.io.OutputStream; public class BluetoothOppObexServerSessionTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - BluetoothMethodProxy mMethodProxy; + @Mock BluetoothMethodProxy mMethodProxy; Context mTargetContext; - @Mock - BluetoothObexTransport mTransport; + @Mock BluetoothObexTransport mTransport; - @Mock - BluetoothOppService mBluetoothOppService; - @Mock - Operation mOperation; + @Mock BluetoothOppService mBluetoothOppService; + @Mock Operation mOperation; BluetoothOppObexServerSession mServerSession; @Before public void setUp() throws IOException { - mTargetContext = spy( - new ContextWrapper( - InstrumentationRegistry.getInstrumentation().getTargetContext())); - mServerSession = new BluetoothOppObexServerSession(mTargetContext, mTransport, - mBluetoothOppService); + mTargetContext = + spy( + new ContextWrapper( + InstrumentationRegistry.getInstrumentation().getTargetContext())); + mServerSession = + new BluetoothOppObexServerSession(mTargetContext, mTransport, mBluetoothOppService); // to control the mServerSession.mSession InputStream input = mock(InputStream.class); @@ -101,8 +98,8 @@ public class BluetoothOppObexServerSessionTest { @Test public void constructor_createInstanceCorrectly() { - mServerSession = new BluetoothOppObexServerSession(mTargetContext, mTransport, - mBluetoothOppService); + mServerSession = + new BluetoothOppObexServerSession(mTargetContext, mTransport, mBluetoothOppService); assertThat(mServerSession.mBluetoothOppService).isEqualTo(mBluetoothOppService); assertThat(mServerSession.mTransport).isEqualTo(mTransport); assertThat(mServerSession.mContext).isEqualTo(mTargetContext); @@ -146,9 +143,22 @@ public class BluetoothOppObexServerSessionTest { int currentBytes = 42; int timestamp = 123456789; boolean mediaScanned = false; - BluetoothOppShareInfo info = new BluetoothOppShareInfo(0, uri, hintString, filename, - mimetype, direction, destination, visibility, confirm, status, totalBytes, - currentBytes, timestamp, mediaScanned); + BluetoothOppShareInfo info = + new BluetoothOppShareInfo( + 0, + uri, + hintString, + filename, + mimetype, + direction, + destination, + visibility, + confirm, + status, + totalBytes, + currentBytes, + timestamp, + mediaScanned); mServerSession.addShare(info); assertThat(mServerSession.mInfo).isEqualTo(info); @@ -176,8 +186,8 @@ public class BluetoothOppObexServerSessionTest { headerSet.setHeader(HeaderSet.NAME, name); headerSet.setHeader(HeaderSet.LENGTH, length); headerSet.setHeader(HeaderSet.TYPE, mimeType); - assertThat(mServerSession.onPut(mOperation)).isEqualTo( - ResponseCodes.OBEX_HTTP_LENGTH_REQUIRED); + assertThat(mServerSession.onPut(mOperation)) + .isEqualTo(ResponseCodes.OBEX_HTTP_LENGTH_REQUIRED); } @Test @@ -216,8 +226,8 @@ public class BluetoothOppObexServerSessionTest { headerSet.setHeader(HeaderSet.LENGTH, length); headerSet.setHeader(HeaderSet.TYPE, mimeType); doReturn(headerSet).when(mOperation).getReceivedHeader(); - assertThat(mServerSession.onPut(mOperation)).isEqualTo( - ResponseCodes.OBEX_HTTP_UNSUPPORTED_TYPE); + assertThat(mServerSession.onPut(mOperation)) + .isEqualTo(ResponseCodes.OBEX_HTTP_UNSUPPORTED_TYPE); } @Test @@ -228,7 +238,8 @@ public class BluetoothOppObexServerSessionTest { // unblock the server and remove timeout message // modify mInfo & mFileInfo, manipulate receiveFile() then return ResponseCodes.OBEX_HTTP_OK - Assume.assumeTrue("Ignore test when if there is not media mounted", + Assume.assumeTrue( + "Ignore test when if there is not media mounted", Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)); String name = "randomFile.txt"; long length = 10; @@ -245,9 +256,22 @@ public class BluetoothOppObexServerSessionTest { int currentBytes = 42; int timestamp = 123456789; boolean mediaScanned = false; - mServerSession.mInfo = new BluetoothOppShareInfo(0, uri, hint, name, - mimeType, direction, destination, visibility, confirm, status, totalBytes, - currentBytes, timestamp, mediaScanned); + mServerSession.mInfo = + new BluetoothOppShareInfo( + 0, + uri, + hint, + name, + mimeType, + direction, + destination, + visibility, + confirm, + status, + totalBytes, + currentBytes, + timestamp, + mediaScanned); mServerSession.mFileInfo = new BluetoothOppReceiveFileInfo(name, length, uri, status); HeaderSet headerSet = new HeaderSet(); @@ -256,20 +280,25 @@ public class BluetoothOppObexServerSessionTest { headerSet.setHeader(HeaderSet.TYPE, mimeType); doReturn(headerSet).when(mOperation).getReceivedHeader(); - doReturn(contentUri).when(mMethodProxy) + doReturn(contentUri) + .when(mMethodProxy) .contentResolverInsert(any(), eq(BluetoothShare.CONTENT_URI), any()); // unblocking the session mServerSession.unblock(); mServerSession.mAccepted = BluetoothShare.USER_CONFIRMATION_CONFIRMED; Handler handler = mock(Handler.class); - doAnswer(arg -> { - mServerSession.unblock(); - // to ignore removeMessage, which is not mockable - mServerSession.mTimeoutMsgSent = false; - return true; - }).when(handler).sendMessageAtTime( - argThat(arg -> arg.what == BluetoothOppObexSession.MSG_CONNECT_TIMEOUT), anyLong()); + doAnswer( + arg -> { + mServerSession.unblock(); + // to ignore removeMessage, which is not mockable + mServerSession.mTimeoutMsgSent = false; + return true; + }) + .when(handler) + .sendMessageAtTime( + argThat(arg -> arg.what == BluetoothOppObexSession.MSG_CONNECT_TIMEOUT), + anyLong()); mServerSession.start(handler, 0); // manipulate ReceiveFile @@ -289,8 +318,8 @@ public class BluetoothOppObexServerSessionTest { HeaderSet reply = new HeaderSet(); byte[] target = new byte[10]; request.setHeader(HeaderSet.TARGET, target); - assertThat(mServerSession.onConnect(request, reply)).isEqualTo( - ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE); + assertThat(mServerSession.onConnect(request, reply)) + .isEqualTo(ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE); } @Test @@ -298,12 +327,13 @@ public class BluetoothOppObexServerSessionTest { HeaderSet request = new HeaderSet(); HeaderSet reply = new HeaderSet(); request.setHeader(HeaderSet.TARGET, null); - BluetoothOppManager bluetoothOppManager = spy( - BluetoothOppManager.getInstance(mTargetContext)); + BluetoothOppManager bluetoothOppManager = + spy(BluetoothOppManager.getInstance(mTargetContext)); BluetoothOppManager.setInstance(bluetoothOppManager); doReturn(true).when(bluetoothOppManager).isAcceptlisted(any()); - doNothing().when(mTargetContext).sendBroadcast(any(), - eq(Constants.HANDOVER_STATUS_PERMISSION), any()); + doNothing() + .when(mTargetContext) + .sendBroadcast(any(), eq(Constants.HANDOVER_STATUS_PERMISSION), any()); assertThat(mServerSession.onConnect(request, reply)).isEqualTo(ResponseCodes.OBEX_HTTP_OK); BluetoothOppManager.setInstance(null); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppPreferenceTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppPreferenceTest.java index fa690958bc1..6ec5566961a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppPreferenceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppPreferenceTest.java @@ -48,14 +48,17 @@ public class BluetoothOppPreferenceTest { @Before public void setUp() { - mContext = spy(new ContextWrapper( - InstrumentationRegistry.getInstrumentation().getTargetContext())); + mContext = + spy( + new ContextWrapper( + InstrumentationRegistry.getInstrumentation().getTargetContext())); mCallProxy = spy(BluetoothMethodProxy.getInstance()); BluetoothMethodProxy.setInstanceForTesting(mCallProxy); - doReturn(null).when(mCallProxy).contentResolverInsert( - any(), eq(BluetoothShare.CONTENT_URI), any()); + doReturn(null) + .when(mCallProxy) + .contentResolverInsert(any(), eq(BluetoothShare.CONTENT_URI), any()); } @After @@ -75,13 +78,14 @@ public class BluetoothOppPreferenceTest { public void setNameAndGetNameAndRemoveName_setsAndGetsAndRemovesNameCorrectly() { String address = "AA:BB:CC:DD:EE:FF"; String name = "randomName"; - BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class)) - .getAdapter().getRemoteDevice(address); + BluetoothDevice device = + (mContext.getSystemService(BluetoothManager.class)) + .getAdapter() + .getRemoteDevice(address); BluetoothOppPreference.getInstance(mContext).setName(device, name); assertThat(BluetoothOppPreference.getInstance(mContext).getName(device)).isEqualTo(name); - // Undo the change so this will not be saved on share preference BluetoothOppPreference.getInstance(mContext).removeName(device); assertThat(BluetoothOppPreference.getInstance(mContext).getName(device)).isNull(); @@ -92,15 +96,17 @@ public class BluetoothOppPreferenceTest { String address = "AA:BB:CC:DD:EE:FF"; int uuid = 1234; int channel = 78910; - BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class)) - .getAdapter().getRemoteDevice(address); + BluetoothDevice device = + (mContext.getSystemService(BluetoothManager.class)) + .getAdapter() + .getRemoteDevice(address); BluetoothOppPreference.getInstance(mContext).setChannel(device, uuid, channel); - assertThat(BluetoothOppPreference.getInstance(mContext).getChannel(device, uuid)).isEqualTo( - channel); + assertThat(BluetoothOppPreference.getInstance(mContext).getChannel(device, uuid)) + .isEqualTo(channel); // Undo the change so this will not be saved on share preference BluetoothOppPreference.getInstance(mContext).removeChannel(device, uuid); - assertThat(BluetoothOppPreference.getInstance(mContext).getChannel(device, uuid)).isEqualTo( - -1); + assertThat(BluetoothOppPreference.getInstance(mContext).getChannel(device, uuid)) + .isEqualTo(-1); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfoTest.java index e0254948f7c..07cea67691d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfoTest.java @@ -50,14 +50,17 @@ public class BluetoothOppReceiveFileInfoTest { @Before public void setUp() { - mContext = spy(new ContextWrapper( - InstrumentationRegistry.getInstrumentation().getTargetContext())); + mContext = + spy( + new ContextWrapper( + InstrumentationRegistry.getInstrumentation().getTargetContext())); mCallProxy = spy(BluetoothMethodProxy.getInstance()); BluetoothMethodProxy.setInstanceForTesting(mCallProxy); - doReturn(null).when(mCallProxy).contentResolverInsert( - any(), eq(BluetoothShare.CONTENT_URI), any()); + doReturn(null) + .when(mCallProxy) + .contentResolverInsert(any(), eq(BluetoothShare.CONTENT_URI), any()); } @After @@ -103,21 +106,32 @@ public class BluetoothOppReceiveFileInfoTest { @Test public void generateFileInfo_wrongHint_fileError() { - Assume.assumeTrue("Ignore test when if there is no media mounted", + Assume.assumeTrue( + "Ignore test when if there is no media mounted", Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)); int id = 0; long fileLength = 100; String hint = "content:///arandomhint/"; String mimeType = "text/plain"; - mCursor = new MatrixCursor( - new String[]{BluetoothShare.FILENAME_HINT, BluetoothShare.TOTAL_BYTES, - BluetoothShare.MIMETYPE}); - mCursor.addRow(new Object[]{hint, fileLength, mimeType}); - - doReturn(mCursor).when(mCallProxy).contentResolverQuery( - any(), eq(Uri.parse(BluetoothShare.CONTENT_URI + "/" + id)), any(), any(), any(), - any()); + mCursor = + new MatrixCursor( + new String[] { + BluetoothShare.FILENAME_HINT, + BluetoothShare.TOTAL_BYTES, + BluetoothShare.MIMETYPE + }); + mCursor.addRow(new Object[] {hint, fileLength, mimeType}); + + doReturn(mCursor) + .when(mCallProxy) + .contentResolverQuery( + any(), + eq(Uri.parse(BluetoothShare.CONTENT_URI + "/" + id)), + any(), + any(), + any(), + any()); BluetoothOppReceiveFileInfo info = BluetoothOppReceiveFileInfo.generateFileInfo(mContext, id); @@ -127,7 +141,8 @@ public class BluetoothOppReceiveFileInfoTest { @Test public void generateFileInfo_noMediaMounted_noSdcardError() { - Assume.assumeTrue("Ignore test when if there is media mounted", + Assume.assumeTrue( + "Ignore test when if there is media mounted", !Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)); int id = 0; @@ -139,24 +154,36 @@ public class BluetoothOppReceiveFileInfoTest { @Test public void generateFileInfo_noInsertUri_returnFileError() { - Assume.assumeTrue("Ignore test when if there is not media mounted", + Assume.assumeTrue( + "Ignore test when if there is not media mounted", Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)); int id = 0; long fileLength = 100; String hint = "content:///arandomhint.txt"; String mimeType = "text/plain"; - mCursor = new MatrixCursor( - new String[]{BluetoothShare.FILENAME_HINT, BluetoothShare.TOTAL_BYTES, - BluetoothShare.MIMETYPE}); - mCursor.addRow(new Object[]{hint, fileLength, mimeType}); - - doReturn(mCursor).when(mCallProxy).contentResolverQuery( - any(), eq(Uri.parse(BluetoothShare.CONTENT_URI + "/" + id)), any(), any(), any(), - any()); - - doReturn(null).when(mCallProxy).contentResolverInsert( - any(), eq(MediaStore.Downloads.EXTERNAL_CONTENT_URI), any()); + mCursor = + new MatrixCursor( + new String[] { + BluetoothShare.FILENAME_HINT, + BluetoothShare.TOTAL_BYTES, + BluetoothShare.MIMETYPE + }); + mCursor.addRow(new Object[] {hint, fileLength, mimeType}); + + doReturn(mCursor) + .when(mCallProxy) + .contentResolverQuery( + any(), + eq(Uri.parse(BluetoothShare.CONTENT_URI + "/" + id)), + any(), + any(), + any(), + any()); + + doReturn(null) + .when(mCallProxy) + .contentResolverInsert(any(), eq(MediaStore.Downloads.EXTERNAL_CONTENT_URI), any()); BluetoothOppReceiveFileInfo info = BluetoothOppReceiveFileInfo.generateFileInfo(mContext, id); @@ -166,7 +193,8 @@ public class BluetoothOppReceiveFileInfoTest { @Test public void generateFileInfo_withInsertUri_workCorrectly() { - Assume.assumeTrue("Ignore test when if there is not media mounted", + Assume.assumeTrue( + "Ignore test when if there is not media mounted", Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)); int id = 0; long fileLength = 100; @@ -174,17 +202,28 @@ public class BluetoothOppReceiveFileInfoTest { String mimeType = "text/plain"; Uri insertUri = Uri.parse("content:///abc/xyz"); - mCursor = new MatrixCursor( - new String[]{BluetoothShare.FILENAME_HINT, BluetoothShare.TOTAL_BYTES, - BluetoothShare.MIMETYPE}); - mCursor.addRow(new Object[]{hint, fileLength, mimeType}); - - doReturn(mCursor).when(mCallProxy).contentResolverQuery( - any(), eq(Uri.parse(BluetoothShare.CONTENT_URI + "/" + id)), any(), any(), any(), - any()); - - doReturn(insertUri).when(mCallProxy).contentResolverInsert( - any(), eq(MediaStore.Downloads.EXTERNAL_CONTENT_URI), any()); + mCursor = + new MatrixCursor( + new String[] { + BluetoothShare.FILENAME_HINT, + BluetoothShare.TOTAL_BYTES, + BluetoothShare.MIMETYPE + }); + mCursor.addRow(new Object[] {hint, fileLength, mimeType}); + + doReturn(mCursor) + .when(mCallProxy) + .contentResolverQuery( + any(), + eq(Uri.parse(BluetoothShare.CONTENT_URI + "/" + id)), + any(), + any(), + any(), + any()); + + doReturn(insertUri) + .when(mCallProxy) + .contentResolverInsert(any(), eq(MediaStore.Downloads.EXTERNAL_CONTENT_URI), any()); assertThat(mCursor.moveToFirst()).isTrue(); @@ -198,7 +237,8 @@ public class BluetoothOppReceiveFileInfoTest { @Test public void generateFileInfo_longFileName_trimFileName() { - Assume.assumeTrue("Ignore test when if there is not media mounted", + Assume.assumeTrue( + "Ignore test when if there is not media mounted", Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)); int id = 0; long fileLength = 100; @@ -206,17 +246,28 @@ public class BluetoothOppReceiveFileInfoTest { String mimeType = "text/plain"; Uri insertUri = Uri.parse("content:///abc/xyz"); - mCursor = new MatrixCursor( - new String[]{BluetoothShare.FILENAME_HINT, BluetoothShare.TOTAL_BYTES, - BluetoothShare.MIMETYPE}); - mCursor.addRow(new Object[]{hint, fileLength, mimeType}); - - doReturn(mCursor).when(mCallProxy).contentResolverQuery( - any(), eq(Uri.parse(BluetoothShare.CONTENT_URI + "/" + id)), any(), any(), any(), - any()); - - doReturn(insertUri).when(mCallProxy).contentResolverInsert( - any(), eq(MediaStore.Downloads.EXTERNAL_CONTENT_URI), any()); + mCursor = + new MatrixCursor( + new String[] { + BluetoothShare.FILENAME_HINT, + BluetoothShare.TOTAL_BYTES, + BluetoothShare.MIMETYPE + }); + mCursor.addRow(new Object[] {hint, fileLength, mimeType}); + + doReturn(mCursor) + .when(mCallProxy) + .contentResolverQuery( + any(), + eq(Uri.parse(BluetoothShare.CONTENT_URI + "/" + id)), + any(), + any(), + any(), + any()); + + doReturn(insertUri) + .when(mCallProxy) + .contentResolverInsert(any(), eq(MediaStore.Downloads.EXTERNAL_CONTENT_URI), any()); assertThat(mCursor.moveToFirst()).isTrue(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java index b47cbd99b8b..7b6c5f73444 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java @@ -77,14 +77,15 @@ public class BluetoothOppReceiverTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - BluetoothMethodProxy mBluetoothMethodProxy; + @Mock BluetoothMethodProxy mBluetoothMethodProxy; BluetoothOppReceiver mReceiver; @Before public void setUp() throws Exception { - mContext = spy(new ContextWrapper( - InstrumentationRegistry.getInstrumentation().getTargetContext())); + mContext = + spy( + new ContextWrapper( + InstrumentationRegistry.getInstrumentation().getTargetContext())); // mock instance so query/insert/update/etc. will not be executed BluetoothMethodProxy.setInstanceForTesting(mBluetoothMethodProxy); @@ -110,8 +111,10 @@ public class BluetoothOppReceiverTest { BluetoothOppManager bluetoothOppManager = spy(BluetoothOppManager.getInstance(mContext)); BluetoothOppManager.setInstance(bluetoothOppManager); String address = "AA:BB:CC:DD:EE:FF"; - BluetoothDevice device = mContext.getSystemService(BluetoothManager.class) - .getAdapter().getRemoteDevice(address); + BluetoothDevice device = + mContext.getSystemService(BluetoothManager.class) + .getAdapter() + .getRemoteDevice(address); Intent intent = new Intent(); intent.setAction(BluetoothDevicePicker.ACTION_DEVICE_SELECTED); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); @@ -153,9 +156,17 @@ public class BluetoothOppReceiverTest { intent.setAction(Constants.ACTION_ACCEPT); intent.setData(uri); mReceiver.onReceive(mContext, intent); - verify(mBluetoothMethodProxy).contentResolverUpdate(any(), eq(uri), argThat(arg -> - Objects.equal(BluetoothShare.USER_CONFIRMATION_CONFIRMED, - arg.get(BluetoothShare.USER_CONFIRMATION))), any(), any()); + verify(mBluetoothMethodProxy) + .contentResolverUpdate( + any(), + eq(uri), + argThat( + arg -> + Objects.equal( + BluetoothShare.USER_CONFIRMATION_CONFIRMED, + arg.get(BluetoothShare.USER_CONFIRMATION))), + any(), + any()); } @Test @@ -165,9 +176,17 @@ public class BluetoothOppReceiverTest { intent.setAction(Constants.ACTION_DECLINE); intent.setData(uri); mReceiver.onReceive(mContext, intent); - verify(mBluetoothMethodProxy).contentResolverUpdate(any(), eq(uri), argThat(arg -> - Objects.equal(BluetoothShare.USER_CONFIRMATION_DENIED, - arg.get(BluetoothShare.USER_CONFIRMATION))), any(), any()); + verify(mBluetoothMethodProxy) + .contentResolverUpdate( + any(), + eq(uri), + argThat( + arg -> + Objects.equal( + BluetoothShare.USER_CONFIRMATION_DENIED, + arg.get(BluetoothShare.USER_CONFIRMATION))), + any(), + any()); } @Test @@ -217,26 +236,40 @@ public class BluetoothOppReceiverTest { public void onReceive_withActionHide_contentUpdate() { List cursorMockDataList; Cursor cursor = mock(Cursor.class); - cursorMockDataList = new ArrayList<>(List.of( - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.VISIBILITY, 0, - BluetoothShare.VISIBILITY_VISIBLE), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.USER_CONFIRMATION, 1, - BluetoothShare.USER_CONFIRMATION_PENDING) - )); + cursorMockDataList = + new ArrayList<>( + List.of( + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.VISIBILITY, + 0, + BluetoothShare.VISIBILITY_VISIBLE), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.USER_CONFIRMATION, + 1, + BluetoothShare.USER_CONFIRMATION_PENDING))); BluetoothOppTestUtils.setUpMockCursor(cursor, cursorMockDataList); - doReturn(cursor).when(mBluetoothMethodProxy).contentResolverQuery(any(), any(), any(), - any(), any(), any()); + doReturn(cursor) + .when(mBluetoothMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); doReturn(true).when(cursor).moveToFirst(); Intent intent = new Intent(); intent.setAction(Constants.ACTION_HIDE); mReceiver.onReceive(mContext, intent); - verify(mBluetoothMethodProxy).contentResolverUpdate(any(), any(), - argThat(arg -> Objects.equal(BluetoothShare.VISIBILITY_HIDDEN, - arg.get(BluetoothShare.VISIBILITY))), any(), any()); + verify(mBluetoothMethodProxy) + .contentResolverUpdate( + any(), + any(), + argThat( + arg -> + Objects.equal( + BluetoothShare.VISIBILITY_HIDDEN, + arg.get(BluetoothShare.VISIBILITY))), + any(), + any()); } @Test @@ -245,9 +278,17 @@ public class BluetoothOppReceiverTest { Intent intent = new Intent(); intent.setAction(Constants.ACTION_COMPLETE_HIDE); mReceiver.onReceive(mContext, intent); - verify(mBluetoothMethodProxy).contentResolverUpdate(any(), eq(BluetoothShare.CONTENT_URI), - argThat(arg -> Objects.equal(BluetoothShare.VISIBILITY_HIDDEN, - arg.get(BluetoothShare.VISIBILITY))), any(), any()); + verify(mBluetoothMethodProxy) + .contentResolverUpdate( + any(), + eq(BluetoothShare.CONTENT_URI), + argThat( + arg -> + Objects.equal( + BluetoothShare.VISIBILITY_HIDDEN, + arg.get(BluetoothShare.VISIBILITY))), + any(), + any()); } @Test @@ -297,31 +338,43 @@ public class BluetoothOppReceiverTest { String destinationValue = "AA:BB:CC:00:11:22"; String fileTypeValue = "text/plain"; - cursorMockDataList = new ArrayList<>(List.of( - new BluetoothOppTestUtils.CursorMockData(BluetoothShare._ID, 0, idValue), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.STATUS, 1, - BluetoothShare.STATUS_SUCCESS), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DIRECTION, 2, - BluetoothShare.DIRECTION_OUTBOUND), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 100), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.MIMETYPE, 5, fileTypeValue), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.TIMESTAMP, 6, - timestampValue), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DESTINATION, 7, - destinationValue), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare._DATA, 8, null), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.FILENAME_HINT, 9, null), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.URI, 10, - "content://textfile.txt"), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.USER_CONFIRMATION, 11, - BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED) - )); + cursorMockDataList = + new ArrayList<>( + List.of( + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare._ID, 0, idValue), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.STATUS, 1, BluetoothShare.STATUS_SUCCESS), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.DIRECTION, + 2, + BluetoothShare.DIRECTION_OUTBOUND), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.TOTAL_BYTES, 3, 100), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.CURRENT_BYTES, 4, 100), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.MIMETYPE, 5, fileTypeValue), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.TIMESTAMP, 6, timestampValue), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.DESTINATION, 7, destinationValue), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare._DATA, 8, null), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.FILENAME_HINT, 9, null), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.URI, 10, "content://textfile.txt"), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.USER_CONFIRMATION, + 11, + BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED))); BluetoothOppTestUtils.setUpMockCursor(cursor, cursorMockDataList); - doReturn(cursor).when(mBluetoothMethodProxy).contentResolverQuery(any(), any(), any(), - any(), any(), any()); + doReturn(cursor) + .when(mBluetoothMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); doReturn(true).when(cursor).moveToFirst(); Intent intent = new Intent(); @@ -341,31 +394,43 @@ public class BluetoothOppReceiverTest { String destinationValue = "AA:BB:CC:00:11:22"; String fileTypeValue = "text/plain"; - cursorMockDataList = new ArrayList<>(List.of( - new BluetoothOppTestUtils.CursorMockData(BluetoothShare._ID, 0, idValue), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.STATUS, 1, - BluetoothShare.STATUS_SUCCESS), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DIRECTION, 2, - BluetoothShare.DIRECTION_OUTBOUND), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 100), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.MIMETYPE, 5, fileTypeValue), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.TIMESTAMP, 6, - timestampValue), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DESTINATION, 7, - destinationValue), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare._DATA, 8, null), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.FILENAME_HINT, 9, null), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.URI, 10, - "content://textfile.txt"), - new BluetoothOppTestUtils.CursorMockData(BluetoothShare.USER_CONFIRMATION, 11, - BluetoothShare.USER_CONFIRMATION_CONFIRMED) - )); + cursorMockDataList = + new ArrayList<>( + List.of( + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare._ID, 0, idValue), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.STATUS, 1, BluetoothShare.STATUS_SUCCESS), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.DIRECTION, + 2, + BluetoothShare.DIRECTION_OUTBOUND), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.TOTAL_BYTES, 3, 100), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.CURRENT_BYTES, 4, 100), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.MIMETYPE, 5, fileTypeValue), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.TIMESTAMP, 6, timestampValue), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.DESTINATION, 7, destinationValue), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare._DATA, 8, null), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.FILENAME_HINT, 9, null), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.URI, 10, "content://textfile.txt"), + new BluetoothOppTestUtils.CursorMockData( + BluetoothShare.USER_CONFIRMATION, + 11, + BluetoothShare.USER_CONFIRMATION_CONFIRMED))); BluetoothOppTestUtils.setUpMockCursor(cursor, cursorMockDataList); - doReturn(cursor).when(mBluetoothMethodProxy).contentResolverQuery(any(), any(), any(), - any(), any(), any()); + doReturn(cursor) + .when(mBluetoothMethodProxy) + .contentResolverQuery(any(), any(), any(), any(), any(), any()); doReturn(true).when(cursor).moveToFirst(); Intent intent = new Intent(); @@ -375,7 +440,7 @@ public class BluetoothOppReceiverTest { // check Toast with Espresso seems not to work on Android 11+. Check not send broadcast // context instead - verify(mContext, never()).sendBroadcast(any(), eq(Constants.HANDOVER_STATUS_PERMISSION), - any()); + verify(mContext, never()) + .sendBroadcast(any(), eq(Constants.HANDOVER_STATUS_PERMISSION), any()); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppSendFileInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppSendFileInfoTest.java index 7d39d32d37b..273f6fd8d5c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppSendFileInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppSendFileInfoTest.java @@ -14,7 +14,6 @@ * limitations under the License. */ - package com.android.bluetooth.opp; import static com.google.common.truth.Truth.assertThat; @@ -56,8 +55,7 @@ public class BluetoothOppSendFileInfoTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - BluetoothMethodProxy mCallProxy; + @Mock BluetoothMethodProxy mCallProxy; @Before public void setUp() { @@ -93,8 +91,7 @@ public class BluetoothOppSendFileInfoTest { long length = 10000; int status = BluetoothShare.STATUS_SUCCESS; String data = "Testing is boring"; - BluetoothOppSendFileInfo info = - new BluetoothOppSendFileInfo(data, type, length, status); + BluetoothOppSendFileInfo info = new BluetoothOppSendFileInfo(data, type, length, status); assertThat(info.mStatus).isEqualTo(status); assertThat(info.mData).isEqualTo(data); @@ -107,8 +104,8 @@ public class BluetoothOppSendFileInfoTest { String type = "text/plain"; Uri uri = Uri.parse("https://www.google.com"); - BluetoothOppSendFileInfo info = BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, - type, true); + BluetoothOppSendFileInfo info = + BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, type, true); assertThat(info).isEqualTo(BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR); } @@ -117,8 +114,8 @@ public class BluetoothOppSendFileInfoTest { String type = "text/plain"; Uri uri = Uri.parse("content://com.android.bluetooth.map.MmsFileProvider:8080"); - BluetoothOppSendFileInfo info = BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, - type, true); + BluetoothOppSendFileInfo info = + BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, type, true); assertThat(info).isEqualTo(BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR); } @@ -127,12 +124,12 @@ public class BluetoothOppSendFileInfoTest { String type = "text/plain"; Uri uri = Uri.parse("content:///hello/world"); - doThrow(new SecurityException()).when(mCallProxy).contentResolverQuery( - any(), eq(uri), any(), any(), any(), - any()); + doThrow(new SecurityException()) + .when(mCallProxy) + .contentResolverQuery(any(), eq(uri), any(), any(), any(), any()); - BluetoothOppSendFileInfo info = BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, - type, true); + BluetoothOppSendFileInfo info = + BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, type, true); assertThat(info).isEqualTo(BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR); } @@ -148,24 +145,22 @@ public class BluetoothOppSendFileInfoTest { AssetFileDescriptor fd = mock(AssetFileDescriptor.class); FileInputStream fs = mock(FileInputStream.class); - mCursor = new MatrixCursor(new String[]{ - OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE - }); - mCursor.addRow(new Object[]{fileName, fileLength}); + mCursor = + new MatrixCursor(new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}); + mCursor.addRow(new Object[] {fileName, fileLength}); - doReturn(mCursor).when(mCallProxy).contentResolverQuery( - any(), eq(uri), any(), any(), any(), - any()); + doReturn(mCursor) + .when(mCallProxy) + .contentResolverQuery(any(), eq(uri), any(), any(), any(), any()); - doReturn(fd).when(mCallProxy).contentResolverOpenAssetFileDescriptor( - any(), eq(uri), any()); + doReturn(fd).when(mCallProxy).contentResolverOpenAssetFileDescriptor(any(), eq(uri), any()); doReturn(0L).when(fd).getLength(); doThrow(new IOException()).when(fd).createInputStream(); doReturn(fs).when(mCallProxy).contentResolverOpenInputStream(any(), eq(uri)); doReturn(0, -1).when(fs).read(any(), anyInt(), anyInt()); - BluetoothOppSendFileInfo info = BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, - type, true); + BluetoothOppSendFileInfo info = + BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, type, true); assertThat(info).isEqualTo(BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR); } @@ -183,25 +178,23 @@ public class BluetoothOppSendFileInfoTest { AssetFileDescriptor fd = mock(AssetFileDescriptor.class); FileInputStream fs = mock(FileInputStream.class); - mCursor = new MatrixCursor(new String[]{ - OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE - }); - mCursor.addRow(new Object[]{fileName, fileLength}); + mCursor = + new MatrixCursor(new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}); + mCursor.addRow(new Object[] {fileName, fileLength}); - doReturn(mCursor).when(mCallProxy).contentResolverQuery( - any(), eq(uri), any(), any(), any(), - any()); + doReturn(mCursor) + .when(mCallProxy) + .contentResolverQuery(any(), eq(uri), any(), any(), any(), any()); - doReturn(fd).when(mCallProxy).contentResolverOpenAssetFileDescriptor( - any(), eq(uri), any()); + doReturn(fd).when(mCallProxy).contentResolverOpenAssetFileDescriptor(any(), eq(uri), any()); doReturn(0L).when(fd).getLength(); doReturn(fs).when(fd).createInputStream(); // the real size will be returned in getStreamSize(fs) doReturn((int) correctFileLength, -1).when(fs).read(any(), anyInt(), anyInt()); - BluetoothOppSendFileInfo info = BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, - type, true); + BluetoothOppSendFileInfo info = + BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, type, true); assertThat(info.mInputStream).isEqualTo(fs); assertThat(info.mFileName).isEqualTo(fileName); @@ -214,8 +207,8 @@ public class BluetoothOppSendFileInfoTest { String type = "text/plain"; Uri uri = Uri.parse("file:///obviously/not/in/external/storage"); - BluetoothOppSendFileInfo info = BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, - type, true); + BluetoothOppSendFileInfo info = + BluetoothOppSendFileInfo.generateFileInfo(mContext, uri, type, true); assertThat(info).isEqualTo(BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppShareInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppShareInfoTest.java index ca549ecd8f4..1ec8853e9a6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppShareInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppShareInfoTest.java @@ -48,9 +48,22 @@ public class BluetoothOppShareInfoTest { @Before public void setUp() throws Exception { - mBluetoothOppShareInfo = new BluetoothOppShareInfo(0, uri, hintString, filename, - mimetype, direction, destination, visibility, confirm, status, totalBytes, - currentBytes, timestamp, mediaScanned); + mBluetoothOppShareInfo = + new BluetoothOppShareInfo( + 0, + uri, + hintString, + filename, + mimetype, + direction, + destination, + visibility, + confirm, + status, + totalBytes, + currentBytes, + timestamp, + mediaScanned); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTestUtils.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTestUtils.java index 0c238563118..33455307659 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTestUtils.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTestUtils.java @@ -42,7 +42,7 @@ public class BluetoothOppTestUtils { * @attr columnName is name of column to be used as a parameter in cursor.getColumnIndexOrThrow * @attr mIndex should be returned from cursor.getColumnIndexOrThrow * @attr mValue should be returned from cursor.getInt() or cursor.getString() or - * cursor.getLong() + * cursor.getLong() */ public static class CursorMockData { public final String mColumnName; @@ -57,8 +57,8 @@ public class BluetoothOppTestUtils { } /** - * Set up a mock single-row Cursor that work for common use cases in the OPP package. - * It mocks the database column index and value of the cell in that column of the current row + * Set up a mock single-row Cursor that work for common use cases in the OPP package. It mocks + * the database column index and value of the cell in that column of the current row * *

      *  cursorMockDataList.add(
@@ -74,37 +74,59 @@ public class BluetoothOppTestUtils {
      * @param cursor a mock/spy cursor to be setup
      * @param cursorMockDataList a list representing what cursor will return
      */
-    public static void setUpMockCursor(
-            Cursor cursor, List cursorMockDataList) {
-        assert(MockUtil.isMock(cursor));
-
-        doAnswer(invocation -> {
-            String name = invocation.getArgument(0);
-            return cursorMockDataList.stream().filter(
-                    mockCursorData -> Objects.equals(mockCursorData.mColumnName, name)
-            ).findFirst().orElse(new CursorMockData("", -1, null)).mColumnIndex;
-        }).when(cursor).getColumnIndexOrThrow(anyString());
-
-        doAnswer(invocation -> {
-            int index = invocation.getArgument(0);
-            return cursorMockDataList.stream().filter(
-                    mockCursorData -> mockCursorData.mColumnIndex == index
-            ).findFirst().orElse(new CursorMockData("", -1, -1)).mValue;
-        }).when(cursor).getInt(anyInt());
-
-        doAnswer(invocation -> {
-            int index = invocation.getArgument(0);
-            return cursorMockDataList.stream().filter(
-                    mockCursorData -> mockCursorData.mColumnIndex == index
-            ).findFirst().orElse(new CursorMockData("", -1, -1)).mValue;
-        }).when(cursor).getLong(anyInt());
-
-        doAnswer(invocation -> {
-            int index = invocation.getArgument(0);
-            return cursorMockDataList.stream().filter(
-                    mockCursorData -> mockCursorData.mColumnIndex == index
-            ).findFirst().orElse(new CursorMockData("", -1, null)).mValue;
-        }).when(cursor).getString(anyInt());
+    public static void setUpMockCursor(Cursor cursor, List cursorMockDataList) {
+        assert (MockUtil.isMock(cursor));
+
+        doAnswer(
+                        invocation -> {
+                            String name = invocation.getArgument(0);
+                            return cursorMockDataList.stream()
+                                    .filter(
+                                            mockCursorData ->
+                                                    Objects.equals(
+                                                            mockCursorData.mColumnName, name))
+                                    .findFirst()
+                                    .orElse(new CursorMockData("", -1, null))
+                                    .mColumnIndex;
+                        })
+                .when(cursor)
+                .getColumnIndexOrThrow(anyString());
+
+        doAnswer(
+                        invocation -> {
+                            int index = invocation.getArgument(0);
+                            return cursorMockDataList.stream()
+                                    .filter(mockCursorData -> mockCursorData.mColumnIndex == index)
+                                    .findFirst()
+                                    .orElse(new CursorMockData("", -1, -1))
+                                    .mValue;
+                        })
+                .when(cursor)
+                .getInt(anyInt());
+
+        doAnswer(
+                        invocation -> {
+                            int index = invocation.getArgument(0);
+                            return cursorMockDataList.stream()
+                                    .filter(mockCursorData -> mockCursorData.mColumnIndex == index)
+                                    .findFirst()
+                                    .orElse(new CursorMockData("", -1, -1))
+                                    .mValue;
+                        })
+                .when(cursor)
+                .getLong(anyInt());
+
+        doAnswer(
+                        invocation -> {
+                            int index = invocation.getArgument(0);
+                            return cursorMockDataList.stream()
+                                    .filter(mockCursorData -> mockCursorData.mColumnIndex == index)
+                                    .findFirst()
+                                    .orElse(new CursorMockData("", -1, null))
+                                    .mValue;
+                        })
+                .when(cursor)
+                .getString(anyInt());
 
         doReturn(true).when(cursor).moveToFirst();
         doReturn(true).when(cursor).moveToLast();
@@ -135,4 +157,3 @@ public class BluetoothOppTestUtils {
                 .setComponentEnabledSetting(activityName, enabledState, DONT_KILL_APP);
     }
 }
-
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferActivityTest.java
index 2fef8475083..2eaa49cf18c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferActivityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferActivityTest.java
@@ -16,7 +16,6 @@
 
 package com.android.bluetooth.opp;
 
-
 import static com.android.bluetooth.opp.BluetoothOppTestUtils.CursorMockData;
 import static com.android.bluetooth.opp.BluetoothOppTransferActivity.DIALOG_RECEIVE_COMPLETE_FAIL;
 import static com.android.bluetooth.opp.BluetoothOppTransferActivity.DIALOG_RECEIVE_COMPLETE_SUCCESS;
@@ -62,10 +61,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
 public class BluetoothOppTransferActivityTest {
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    Cursor mCursor;
-    @Spy
-    BluetoothMethodProxy mBluetoothMethodProxy;
+    @Mock Cursor mCursor;
+    @Spy BluetoothMethodProxy mBluetoothMethodProxy;
 
     List mCursorMockDataList;
 
@@ -89,29 +86,34 @@ public class BluetoothOppTransferActivityTest {
         mIntent.setClass(mTargetContext, BluetoothOppTransferActivity.class);
         mIntent.setData(dataUrl);
 
-        doReturn(mCursor).when(mBluetoothMethodProxy).contentResolverQuery(any(), eq(dataUrl),
-                eq(null), eq(null),
-                eq(null), eq(null));
+        doReturn(mCursor)
+                .when(mBluetoothMethodProxy)
+                .contentResolverQuery(any(), eq(dataUrl), eq(null), eq(null), eq(null), eq(null));
 
-        doReturn(1).when(mBluetoothMethodProxy).contentResolverUpdate(any(), eq(dataUrl),
-                any(), eq(null), eq(null));
+        doReturn(1)
+                .when(mBluetoothMethodProxy)
+                .contentResolverUpdate(any(), eq(dataUrl), any(), eq(null), eq(null));
 
         int idValue = 1234;
         Long timestampValue = 123456789L;
         String destinationValue = "AA:BB:CC:00:11:22";
         String fileTypeValue = "text/plain";
 
-        mCursorMockDataList = new ArrayList<>(List.of(
-                new CursorMockData(BluetoothShare._ID, 0, idValue),
-                new CursorMockData(BluetoothShare.MIMETYPE, 5, fileTypeValue),
-                new CursorMockData(BluetoothShare.TIMESTAMP, 6, timestampValue),
-                new CursorMockData(BluetoothShare.DESTINATION, 7, destinationValue),
-                new CursorMockData(BluetoothShare._DATA, 8, null),
-                new CursorMockData(BluetoothShare.FILENAME_HINT, 9, null),
-                new CursorMockData(BluetoothShare.URI, 10, "content://textfile.txt"),
-                new CursorMockData(BluetoothShare.USER_CONFIRMATION, 11,
-                        BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)
-        ));
+        mCursorMockDataList =
+                new ArrayList<>(
+                        List.of(
+                                new CursorMockData(BluetoothShare._ID, 0, idValue),
+                                new CursorMockData(BluetoothShare.MIMETYPE, 5, fileTypeValue),
+                                new CursorMockData(BluetoothShare.TIMESTAMP, 6, timestampValue),
+                                new CursorMockData(BluetoothShare.DESTINATION, 7, destinationValue),
+                                new CursorMockData(BluetoothShare._DATA, 8, null),
+                                new CursorMockData(BluetoothShare.FILENAME_HINT, 9, null),
+                                new CursorMockData(
+                                        BluetoothShare.URI, 10, "content://textfile.txt"),
+                                new CursorMockData(
+                                        BluetoothShare.USER_CONFIRMATION,
+                                        11,
+                                        BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)));
         BluetoothOppTestUtils.enableActivity(
                 BluetoothOppTransferActivity.class, true, mTargetContext);
         TestUtils.setUpUiTest();
@@ -131,19 +133,19 @@ public class BluetoothOppTransferActivityTest {
         mCursorMockDataList.add(
                 new CursorMockData(BluetoothShare.STATUS, 1, BluetoothShare.STATUS_PENDING));
         mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_OUTBOUND)
-        );
+                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_OUTBOUND));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 0));
         BluetoothOppTestUtils.setUpMockCursor(mCursor, mCursorMockDataList);
 
         AtomicBoolean check = new AtomicBoolean(false);
-        ActivityScenario activityScenario = ActivityScenario.launch(
-                mIntent);
+        ActivityScenario activityScenario =
+                ActivityScenario.launch(mIntent);
 
-        activityScenario.onActivity(activity -> {
-            check.set(activity.mWhichDialog == DIALOG_SEND_ONGOING);
-        });
+        activityScenario.onActivity(
+                activity -> {
+                    check.set(activity.mWhichDialog == DIALOG_SEND_ONGOING);
+                });
 
         assertThat(check.get()).isTrue();
     }
@@ -151,23 +153,21 @@ public class BluetoothOppTransferActivityTest {
     @Test
     public void onCreate_showSendCompleteSuccessDialog() {
         mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.STATUS, 1, BluetoothShare.STATUS_SUCCESS)
-        );
+                new CursorMockData(BluetoothShare.STATUS, 1, BluetoothShare.STATUS_SUCCESS));
         mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_OUTBOUND)
-        );
+                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_OUTBOUND));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100));
-        mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 100));
+        mCursorMockDataList.add(new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 100));
         BluetoothOppTestUtils.setUpMockCursor(mCursor, mCursorMockDataList);
 
         AtomicBoolean check = new AtomicBoolean(false);
-        ActivityScenario activityScenario = ActivityScenario.launch(
-                mIntent);
+        ActivityScenario activityScenario =
+                ActivityScenario.launch(mIntent);
 
-        activityScenario.onActivity(activity -> {
-            check.set(activity.mWhichDialog == DIALOG_SEND_COMPLETE_SUCCESS);
-        });
+        activityScenario.onActivity(
+                activity -> {
+                    check.set(activity.mWhichDialog == DIALOG_SEND_COMPLETE_SUCCESS);
+                });
 
         assertThat(check.get()).isTrue();
     }
@@ -177,19 +177,19 @@ public class BluetoothOppTransferActivityTest {
         mCursorMockDataList.add(
                 new CursorMockData(BluetoothShare.STATUS, 1, BluetoothShare.STATUS_FORBIDDEN));
         mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_OUTBOUND)
-        );
+                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_OUTBOUND));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 42));
         BluetoothOppTestUtils.setUpMockCursor(mCursor, mCursorMockDataList);
 
         AtomicBoolean check = new AtomicBoolean(false);
-        ActivityScenario activityScenario = ActivityScenario.launch(
-                mIntent);
+        ActivityScenario activityScenario =
+                ActivityScenario.launch(mIntent);
 
-        activityScenario.onActivity(activity -> {
-            check.set(activity.mWhichDialog == DIALOG_SEND_COMPLETE_FAIL);
-        });
+        activityScenario.onActivity(
+                activity -> {
+                    check.set(activity.mWhichDialog == DIALOG_SEND_COMPLETE_FAIL);
+                });
 
         assertThat(check.get()).isTrue();
     }
@@ -199,19 +199,19 @@ public class BluetoothOppTransferActivityTest {
         mCursorMockDataList.add(
                 new CursorMockData(BluetoothShare.STATUS, 1, BluetoothShare.STATUS_PENDING));
         mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_INBOUND)
-        );
+                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_INBOUND));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 0));
         BluetoothOppTestUtils.setUpMockCursor(mCursor, mCursorMockDataList);
 
         AtomicBoolean check = new AtomicBoolean(false);
-        ActivityScenario activityScenario = ActivityScenario.launch(
-                mIntent);
+        ActivityScenario activityScenario =
+                ActivityScenario.launch(mIntent);
 
-        activityScenario.onActivity(activity -> {
-            check.set(activity.mWhichDialog == DIALOG_RECEIVE_ONGOING);
-        });
+        activityScenario.onActivity(
+                activity -> {
+                    check.set(activity.mWhichDialog == DIALOG_RECEIVE_ONGOING);
+                });
 
         assertThat(check.get()).isTrue();
     }
@@ -221,22 +221,20 @@ public class BluetoothOppTransferActivityTest {
         mCursorMockDataList.add(
                 new CursorMockData(BluetoothShare.STATUS, 1, BluetoothShare.STATUS_SUCCESS));
         mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_INBOUND)
-        );
+                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_INBOUND));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100));
-        mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 100)
-        );
+        mCursorMockDataList.add(new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 100));
 
         BluetoothOppTestUtils.setUpMockCursor(mCursor, mCursorMockDataList);
 
         AtomicBoolean check = new AtomicBoolean(false);
-        ActivityScenario activityScenario = ActivityScenario.launch(
-                mIntent);
+        ActivityScenario activityScenario =
+                ActivityScenario.launch(mIntent);
 
-        activityScenario.onActivity(activity -> {
-            check.set(activity.mWhichDialog == DIALOG_RECEIVE_COMPLETE_SUCCESS);
-        });
+        activityScenario.onActivity(
+                activity -> {
+                    check.set(activity.mWhichDialog == DIALOG_RECEIVE_COMPLETE_SUCCESS);
+                });
 
         assertThat(check.get()).isTrue();
     }
@@ -246,20 +244,20 @@ public class BluetoothOppTransferActivityTest {
         mCursorMockDataList.add(
                 new CursorMockData(BluetoothShare.STATUS, 1, BluetoothShare.STATUS_FORBIDDEN));
         mCursorMockDataList.add(
-                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_INBOUND)
-        );
+                new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_INBOUND));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100));
         mCursorMockDataList.add(new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 42));
 
         BluetoothOppTestUtils.setUpMockCursor(mCursor, mCursorMockDataList);
 
         AtomicBoolean check = new AtomicBoolean(false);
-        ActivityScenario activityScenario = ActivityScenario.launch(
-                mIntent);
+        ActivityScenario activityScenario =
+                ActivityScenario.launch(mIntent);
 
-        activityScenario.onActivity(activity -> {
-            check.set(activity.mWhichDialog == DIALOG_RECEIVE_COMPLETE_FAIL);
-        });
+        activityScenario.onActivity(
+                activity -> {
+                    check.set(activity.mWhichDialog == DIALOG_RECEIVE_COMPLETE_FAIL);
+                });
 
         assertThat(check.get()).isTrue();
     }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferHistoryTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferHistoryTest.java
index 9cc3c0397bd..a50be0b5dec 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferHistoryTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferHistoryTest.java
@@ -64,17 +64,13 @@ import org.mockito.junit.MockitoRule;
 import java.util.ArrayList;
 import java.util.List;
 
-/**
- * This class will also test BluetoothOppTransferAdapter
- */
+/** This class will also test BluetoothOppTransferAdapter */
 @RunWith(AndroidJUnit4.class)
 public class BluetoothOppTransferHistoryTest {
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    Cursor mCursor;
-    @Spy
-    BluetoothMethodProxy mBluetoothMethodProxy;
+    @Mock Cursor mCursor;
+    @Spy BluetoothMethodProxy mBluetoothMethodProxy;
 
     List mCursorMockDataList;
 
@@ -98,35 +94,47 @@ public class BluetoothOppTransferHistoryTest {
         mIntent.setClass(mTargetContext, BluetoothOppTransferHistory.class);
         mIntent.setData(dataUrl);
 
-        doReturn(mCursor).when(mBluetoothMethodProxy).contentResolverQuery(any(),
-                eq(BluetoothShare.CONTENT_URI),
-                any(), any(), any(), any());
+        doReturn(mCursor)
+                .when(mBluetoothMethodProxy)
+                .contentResolverQuery(
+                        any(), eq(BluetoothShare.CONTENT_URI), any(), any(), any(), any());
 
         int idValue = 1234;
         Long timestampValue = 123456789L;
         String destinationValue = "AA:BB:CC:00:11:22";
         String fileTypeValue = "text/plain";
 
-        mCursorMockDataList = new ArrayList<>(List.of(
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.STATUS, 1,
-                        BluetoothShare.STATUS_SUCCESS),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DIRECTION, 2,
-                        BluetoothShare.DIRECTION_INBOUND),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 0),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare._ID, 0, idValue),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.MIMETYPE, 5, fileTypeValue),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.TIMESTAMP, 6,
-                        timestampValue),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DESTINATION, 7,
-                        destinationValue),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare._DATA, 8, null),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.FILENAME_HINT, 9, null),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.URI, 10,
-                        "content://textfile.txt"),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.USER_CONFIRMATION, 11,
-                        BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)
-        ));
+        mCursorMockDataList =
+                new ArrayList<>(
+                        List.of(
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.STATUS, 1, BluetoothShare.STATUS_SUCCESS),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.DIRECTION,
+                                        2,
+                                        BluetoothShare.DIRECTION_INBOUND),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.TOTAL_BYTES, 3, 100),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.CURRENT_BYTES, 4, 0),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare._ID, 0, idValue),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.MIMETYPE, 5, fileTypeValue),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.TIMESTAMP, 6, timestampValue),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.DESTINATION, 7, destinationValue),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare._DATA, 8, null),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.FILENAME_HINT, 9, null),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.URI, 10, "content://textfile.txt"),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.USER_CONFIRMATION,
+                                        11,
+                                        BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)));
 
         BluetoothOppTestUtils.enableActivity(
                 BluetoothOppTransferHistory.class, true, mTargetContext);
@@ -156,8 +164,8 @@ public class BluetoothOppTransferHistoryTest {
         ActivityScenario scenario = ActivityScenario.launch(mIntent);
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
-        onView(withText(mTargetContext.getText(R.string.inbound_history_title).toString())).check(
-                matches(isDisplayed()));
+        onView(withText(mTargetContext.getText(R.string.inbound_history_title).toString()))
+                .check(matches(isDisplayed()));
     }
 
     @Test
@@ -166,9 +174,10 @@ public class BluetoothOppTransferHistoryTest {
                 mTargetContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH));
 
         BluetoothOppTestUtils.setUpMockCursor(mCursor, mCursorMockDataList);
-        mCursorMockDataList.set(1,
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DIRECTION, 2,
-                        BluetoothShare.DIRECTION_OUTBOUND));
+        mCursorMockDataList.set(
+                1,
+                new BluetoothOppTestUtils.CursorMockData(
+                        BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_OUTBOUND));
         if (Flags.oppStartActivityDirectlyFromNotification()) {
             mIntent.setAction(Constants.ACTION_OPEN_OUTBOUND_TRANSFER);
         } else {
@@ -178,8 +187,8 @@ public class BluetoothOppTransferHistoryTest {
         ActivityScenario scenario = ActivityScenario.launch(mIntent);
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
-        onView(withText(mTargetContext.getText(R.string.outbound_history_title).toString())).check(
-                matches(isDisplayed()));
+        onView(withText(mTargetContext.getText(R.string.outbound_history_title).toString()))
+                .check(matches(isDisplayed()));
     }
 
     // TODO: Check whether watch devices can pass this test
@@ -191,31 +200,51 @@ public class BluetoothOppTransferHistoryTest {
 
         ActivityScenario scenario = ActivityScenario.launch(mIntent);
 
-
         MenuItem mockMenuItem = mock(MenuItem.class);
         doReturn(R.id.transfer_menu_clear_all).when(mockMenuItem).getItemId();
-        scenario.onActivity(activity -> {
-            activity.onOptionsItemSelected(mockMenuItem);
-        });
+        scenario.onActivity(
+                activity -> {
+                    activity.onOptionsItemSelected(mockMenuItem);
+                });
         InstrumentationRegistry.getInstrumentation().waitForIdleSync();
 
         // Controlling clear all download
         doReturn(true, false).when(mCursor).moveToFirst();
         doReturn(false, true).when(mCursor).isAfterLast();
-        doReturn(0).when(mBluetoothMethodProxy).contentResolverUpdate(any(), any(),
-                argThat(arg -> Objects.equal(arg.get(BluetoothShare.VISIBILITY),
-                        BluetoothShare.VISIBILITY_HIDDEN)), any(), any());
+        doReturn(0)
+                .when(mBluetoothMethodProxy)
+                .contentResolverUpdate(
+                        any(),
+                        any(),
+                        argThat(
+                                arg ->
+                                        Objects.equal(
+                                                arg.get(BluetoothShare.VISIBILITY),
+                                                BluetoothShare.VISIBILITY_HIDDEN)),
+                        any(),
+                        any());
 
         onView(withText(mTargetContext.getText(R.string.transfer_clear_dlg_title).toString()))
-                .inRoot(isDialog()).check(matches(isDisplayed()));
+                .inRoot(isDialog())
+                .check(matches(isDisplayed()));
 
         // Click ok on the prompted dialog
-        onView(withText(mTargetContext.getText(android.R.string.ok).toString())).inRoot(
-                isDialog()).check(matches(isDisplayed())).perform(click());
+        onView(withText(mTargetContext.getText(android.R.string.ok).toString()))
+                .inRoot(isDialog())
+                .check(matches(isDisplayed()))
+                .perform(click());
 
         // Verify that item is hidden
-        verify(mBluetoothMethodProxy).contentResolverUpdate(any(), any(),
-                argThat(arg -> Objects.equal(arg.get(BluetoothShare.VISIBILITY),
-                        BluetoothShare.VISIBILITY_HIDDEN)), any(), any());
+        verify(mBluetoothMethodProxy)
+                .contentResolverUpdate(
+                        any(),
+                        any(),
+                        argThat(
+                                arg ->
+                                        Objects.equal(
+                                                arg.get(BluetoothShare.VISIBILITY),
+                                                BluetoothShare.VISIBILITY_HIDDEN)),
+                        any(),
+                        any());
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java
index 46a1d5496e3..fbf67c4a736 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java
@@ -83,10 +83,8 @@ public class BluetoothOppTransferTest {
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
     @Rule public final SetFlagsRule mSetFlagRule = new SetFlagsRule();
 
-    @Mock
-    BluetoothOppObexSession mSession;
-    @Mock
-    BluetoothMethodProxy mCallProxy;
+    @Mock BluetoothOppObexSession mSession;
+    @Mock BluetoothMethodProxy mCallProxy;
     Context mContext;
     BluetoothOppBatch mBluetoothOppBatch;
     BluetoothOppTransfer mTransfer;
@@ -96,18 +94,42 @@ public class BluetoothOppTransferTest {
     @Before
     public void setUp() throws Exception {
         BluetoothMethodProxy.setInstanceForTesting(mCallProxy);
-        doReturn(0).when(mCallProxy).contentResolverDelete(any(), nullable(Uri.class),
-                nullable(String.class), nullable(String[].class));
-        doReturn(0).when(mCallProxy).contentResolverUpdate(any(), nullable(Uri.class),
-                nullable(ContentValues.class), nullable(String.class), nullable(String[].class));
-
-        mInitShareInfo = new BluetoothOppShareInfo(8765, mUri, mHintString, mFilename, mMimetype,
-                mDirection, mDestination, mVisibility, mConfirm, mStatus, mTotalBytes,
-                mCurrentBytes,
-                mTimestamp, mMediaScanned);
-        mContext = spy(
-                new ContextWrapper(
-                        InstrumentationRegistry.getInstrumentation().getTargetContext()));
+        doReturn(0)
+                .when(mCallProxy)
+                .contentResolverDelete(
+                        any(),
+                        nullable(Uri.class),
+                        nullable(String.class),
+                        nullable(String[].class));
+        doReturn(0)
+                .when(mCallProxy)
+                .contentResolverUpdate(
+                        any(),
+                        nullable(Uri.class),
+                        nullable(ContentValues.class),
+                        nullable(String.class),
+                        nullable(String[].class));
+
+        mInitShareInfo =
+                new BluetoothOppShareInfo(
+                        8765,
+                        mUri,
+                        mHintString,
+                        mFilename,
+                        mMimetype,
+                        mDirection,
+                        mDestination,
+                        mVisibility,
+                        mConfirm,
+                        mStatus,
+                        mTotalBytes,
+                        mCurrentBytes,
+                        mTimestamp,
+                        mMediaScanned);
+        mContext =
+                spy(
+                        new ContextWrapper(
+                                InstrumentationRegistry.getInstrumentation().getTargetContext()));
         mBluetoothOppBatch = spy(new BluetoothOppBatch(mContext, mInitShareInfo));
         mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession);
         mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper());
@@ -120,17 +142,31 @@ public class BluetoothOppTransferTest {
 
     @Test
     public void onShareAdded_checkFirstPendingShare() {
-        BluetoothOppShareInfo newShareInfo = new BluetoothOppShareInfo(1, mUri, mHintString,
-                mFilename, mMimetype, BluetoothShare.DIRECTION_INBOUND, mDestination, mVisibility,
-                BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED, mStatus, mTotalBytes,
-                mCurrentBytes,
-                mTimestamp, mMediaScanned);
-
-        doAnswer(invocation -> {
-            assertThat((BluetoothOppShareInfo) invocation.getArgument(0))
-                    .isEqualTo(mInitShareInfo);
-            return null;
-        }).when(mSession).addShare(any(BluetoothOppShareInfo.class));
+        BluetoothOppShareInfo newShareInfo =
+                new BluetoothOppShareInfo(
+                        1,
+                        mUri,
+                        mHintString,
+                        mFilename,
+                        mMimetype,
+                        BluetoothShare.DIRECTION_INBOUND,
+                        mDestination,
+                        mVisibility,
+                        BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED,
+                        mStatus,
+                        mTotalBytes,
+                        mCurrentBytes,
+                        mTimestamp,
+                        mMediaScanned);
+
+        doAnswer(
+                        invocation -> {
+                            assertThat((BluetoothOppShareInfo) invocation.getArgument(0))
+                                    .isEqualTo(mInitShareInfo);
+                            return null;
+                        })
+                .when(mSession)
+                .addShare(any(BluetoothOppShareInfo.class));
 
         // This will trigger mTransfer.onShareAdded(), which will call mTransfer
         // .processCurrentShare(),
@@ -179,14 +215,14 @@ public class BluetoothOppTransferTest {
         assertThat(mBluetoothOppBatch.mStatus).isEqualTo(Constants.BATCH_STATUS_FAILED);
     }
 
-// TODO: try to use ShadowBluetoothDevice
-//    @Test
-//    public void eventHandler_handleMessage_SOCKET_ERROR_RETRY_connectThreadInitiated() {
-//        BluetoothDevice bluetoothDevice = ShadowBluetoothDevice();
-//        Message message = Message.obtain(mEventHandler, SOCKET_ERROR_RETRY, bluetoothDevice);
-//        mEventHandler.handleMessage(message);
-//        assertThat(mTransfer.mConnectThread).isNotNull();
-//    }
+    // TODO: try to use ShadowBluetoothDevice
+    //    @Test
+    //    public void eventHandler_handleMessage_SOCKET_ERROR_RETRY_connectThreadInitiated() {
+    //        BluetoothDevice bluetoothDevice = ShadowBluetoothDevice();
+    //        Message message = Message.obtain(mEventHandler, SOCKET_ERROR_RETRY, bluetoothDevice);
+    //        mEventHandler.handleMessage(message);
+    //        assertThat(mTransfer.mConnectThread).isNotNull();
+    //    }
 
     @Test
     public void eventHandler_handleMessage_TRANSPORT_CONNECTED_obexSessionStarted() {
@@ -200,12 +236,26 @@ public class BluetoothOppTransferTest {
     public void eventHandler_handleMessage_MSG_SHARE_COMPLETE_shareAdded() {
         Message message = Message.obtain(mEventHandler, BluetoothOppObexSession.MSG_SHARE_COMPLETE);
 
-        mInitShareInfo = new BluetoothOppShareInfo(123, mUri, mHintString, mFilename, mMimetype,
-                BluetoothShare.DIRECTION_OUTBOUND, mDestination, mVisibility, mConfirm, mStatus,
-                mTotalBytes, mCurrentBytes, mTimestamp, mMediaScanned);
-        mContext = spy(
-                new ContextWrapper(
-                        InstrumentationRegistry.getInstrumentation().getTargetContext()));
+        mInitShareInfo =
+                new BluetoothOppShareInfo(
+                        123,
+                        mUri,
+                        mHintString,
+                        mFilename,
+                        mMimetype,
+                        BluetoothShare.DIRECTION_OUTBOUND,
+                        mDestination,
+                        mVisibility,
+                        mConfirm,
+                        mStatus,
+                        mTotalBytes,
+                        mCurrentBytes,
+                        mTimestamp,
+                        mMediaScanned);
+        mContext =
+                spy(
+                        new ContextWrapper(
+                                InstrumentationRegistry.getInstrumentation().getTargetContext()));
         mBluetoothOppBatch = spy(new BluetoothOppBatch(mContext, mInitShareInfo));
         mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession);
         mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper());
@@ -218,9 +268,8 @@ public class BluetoothOppTransferTest {
     @Test
     public void eventHandler_handleMessage_MSG_SESSION_COMPLETE_batchFinished() {
         BluetoothOppShareInfo info = mock(BluetoothOppShareInfo.class);
-        Message message = Message.obtain(mEventHandler,
-                BluetoothOppObexSession.MSG_SESSION_COMPLETE,
-                info);
+        Message message =
+                Message.obtain(mEventHandler, BluetoothOppObexSession.MSG_SESSION_COMPLETE, info);
         mEventHandler.handleMessage(message);
 
         assertThat(mBluetoothOppBatch.mStatus).isEqualTo(Constants.BATCH_STATUS_FINISHED);
@@ -229,8 +278,8 @@ public class BluetoothOppTransferTest {
     @Test
     public void eventHandler_handleMessage_MSG_SESSION_ERROR_batchFailed() {
         BluetoothOppShareInfo info = mock(BluetoothOppShareInfo.class);
-        Message message = Message.obtain(mEventHandler, BluetoothOppObexSession.MSG_SESSION_ERROR,
-                info);
+        Message message =
+                Message.obtain(mEventHandler, BluetoothOppObexSession.MSG_SESSION_ERROR, info);
         mEventHandler.handleMessage(message);
 
         assertThat(mBluetoothOppBatch.mStatus).isEqualTo(Constants.BATCH_STATUS_FAILED);
@@ -239,17 +288,29 @@ public class BluetoothOppTransferTest {
     @Test
     public void eventHandler_handleMessage_MSG_SHARE_INTERRUPTED_batchFailed() {
 
-        mInitShareInfo = new BluetoothOppShareInfo(123, mUri, mHintString, mFilename, mMimetype,
-                BluetoothShare.DIRECTION_OUTBOUND, mDestination, mVisibility, mConfirm, mStatus,
-                mTotalBytes, mCurrentBytes, mTimestamp, mMediaScanned);
+        mInitShareInfo =
+                new BluetoothOppShareInfo(
+                        123,
+                        mUri,
+                        mHintString,
+                        mFilename,
+                        mMimetype,
+                        BluetoothShare.DIRECTION_OUTBOUND,
+                        mDestination,
+                        mVisibility,
+                        mConfirm,
+                        mStatus,
+                        mTotalBytes,
+                        mCurrentBytes,
+                        mTimestamp,
+                        mMediaScanned);
         mBluetoothOppBatch = spy(new BluetoothOppBatch(mContext, mInitShareInfo));
         mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession);
         mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper());
 
         BluetoothOppShareInfo info = mock(BluetoothOppShareInfo.class);
-        Message message = Message.obtain(mEventHandler,
-                BluetoothOppObexSession.MSG_SHARE_INTERRUPTED,
-                info);
+        Message message =
+                Message.obtain(mEventHandler, BluetoothOppObexSession.MSG_SHARE_INTERRUPTED, info);
         mEventHandler.handleMessage(message);
 
         assertThat(mBluetoothOppBatch.mStatus).isEqualTo(Constants.BATCH_STATUS_FAILED);
@@ -257,24 +318,45 @@ public class BluetoothOppTransferTest {
 
     @Test
     public void eventHandler_handleMessage_MSG_CONNECT_TIMEOUT() {
-        Message message = Message.obtain(mEventHandler,
-                BluetoothOppObexSession.MSG_CONNECT_TIMEOUT);
-        BluetoothOppShareInfo newInfo = new BluetoothOppShareInfo(321, mUri, mHintString,
-                mFilename, mMimetype, mDirection, mDestination, mVisibility, mConfirm, mStatus,
-                mTotalBytes, mCurrentBytes, mTimestamp, mMediaScanned);
+        Message message =
+                Message.obtain(mEventHandler, BluetoothOppObexSession.MSG_CONNECT_TIMEOUT);
+        BluetoothOppShareInfo newInfo =
+                new BluetoothOppShareInfo(
+                        321,
+                        mUri,
+                        mHintString,
+                        mFilename,
+                        mMimetype,
+                        mDirection,
+                        mDestination,
+                        mVisibility,
+                        mConfirm,
+                        mStatus,
+                        mTotalBytes,
+                        mCurrentBytes,
+                        mTimestamp,
+                        mMediaScanned);
         // Adding new info will assign value to mCurrentShare
         mBluetoothOppBatch.addShare(newInfo);
         mEventHandler.handleMessage(message);
 
-        verify(mContext).sendBroadcast(argThat(
-                arg -> arg.getAction().equals(BluetoothShare.USER_CONFIRMATION_TIMEOUT_ACTION)));
+        verify(mContext)
+                .sendBroadcast(
+                        argThat(
+                                arg ->
+                                        arg.getAction()
+                                                .equals(
+                                                        BluetoothShare
+                                                                .USER_CONFIRMATION_TIMEOUT_ACTION)));
     }
 
     @Test
     public void socketConnectThreadConstructors() {
         String address = "AA:BB:CC:EE:DD:11";
-        BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class))
-                .getAdapter().getRemoteDevice(address);
+        BluetoothDevice device =
+                (mContext.getSystemService(BluetoothManager.class))
+                        .getAdapter()
+                        .getRemoteDevice(address);
         BluetoothOppTransfer transfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch);
         BluetoothOppTransfer.SocketConnectThread socketConnectThread =
                 transfer.new SocketConnectThread(device, true);
@@ -287,8 +369,10 @@ public class BluetoothOppTransferTest {
     @Test
     public void socketConnectThreadInterrupt() {
         String address = "AA:BB:CC:EE:DD:11";
-        BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class))
-                .getAdapter().getRemoteDevice(address);
+        BluetoothDevice device =
+                (mContext.getSystemService(BluetoothManager.class))
+                        .getAdapter()
+                        .getRemoteDevice(address);
         BluetoothOppTransfer transfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch);
         BluetoothOppTransfer.SocketConnectThread socketConnectThread =
                 transfer.new SocketConnectThread(device, true);
@@ -300,8 +384,10 @@ public class BluetoothOppTransferTest {
     @SuppressWarnings("DoNotCall")
     public void socketConnectThreadRun_bluetoothDisabled_connectionFailed() {
         String address = "AA:BB:CC:EE:DD:11";
-        BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class))
-                .getAdapter().getRemoteDevice(address);
+        BluetoothDevice device =
+                (mContext.getSystemService(BluetoothManager.class))
+                        .getAdapter()
+                        .getRemoteDevice(address);
         BluetoothOppTransfer transfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch);
         BluetoothOppTransfer.SocketConnectThread socketConnectThread =
                 transfer.new SocketConnectThread(device, true);
@@ -313,8 +399,10 @@ public class BluetoothOppTransferTest {
 
     @Test
     public void oppConnectionReceiver_onReceiveWithActionAclDisconnected_sendsConnectTimeout() {
-        BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class))
-                .getAdapter().getRemoteDevice(mDestination);
+        BluetoothDevice device =
+                (mContext.getSystemService(BluetoothManager.class))
+                        .getAdapter()
+                        .getRemoteDevice(mDestination);
         BluetoothOppTransfer transfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch);
         transfer.mCurrentShare = mInitShareInfo;
         transfer.mCurrentShare.mConfirm = BluetoothShare.USER_CONFIRMATION_PENDING;
@@ -325,15 +413,17 @@ public class BluetoothOppTransferTest {
 
         transfer.mSessionHandler = mEventHandler;
         receiver.onReceive(mContext, intent);
-        verify(mCallProxy).handlerSendEmptyMessage(any(),
-                eq(BluetoothOppObexSession.MSG_CONNECT_TIMEOUT));
+        verify(mCallProxy)
+                .handlerSendEmptyMessage(any(), eq(BluetoothOppObexSession.MSG_CONNECT_TIMEOUT));
     }
 
     @Test
     public void oppConnectionReceiver_onReceiveWithActionSdpRecord_withoutSdpRecord() {
         mSetFlagRule.enableFlags(Flags.FLAG_IDENTITY_ADDRESS_NULL_IF_UNKNOWN);
-        BluetoothDevice device = (mContext.getSystemService(BluetoothManager.class))
-                .getAdapter().getRemoteDevice(mDestination);
+        BluetoothDevice device =
+                (mContext.getSystemService(BluetoothManager.class))
+                        .getAdapter()
+                        .getRemoteDevice(mDestination);
 
         BluetoothOppTransfer transfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch);
         transfer.mCurrentShare = mInitShareInfo;
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java
index e8a5dac0e02..9af7c38e32f 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java
@@ -65,19 +65,16 @@ import java.util.concurrent.atomic.AtomicInteger;
 
 public class BluetoothOppUtilityTest {
 
-    private static final Uri CORRECT_FORMAT_BUT_INVALID_FILE_URI = Uri.parse(
-            "content://com.android.bluetooth.opp/btopp/0123455343467");
+    private static final Uri CORRECT_FORMAT_BUT_INVALID_FILE_URI =
+            Uri.parse("content://com.android.bluetooth.opp/btopp/0123455343467");
     private static final Uri INCORRECT_FORMAT_URI = Uri.parse("www.google.com");
 
     Context mContext;
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    Cursor mCursor;
-
-    @Spy
-    BluetoothMethodProxy mCallProxy = BluetoothMethodProxy.getInstance();
+    @Mock Cursor mCursor;
 
+    @Spy BluetoothMethodProxy mCallProxy = BluetoothMethodProxy.getInstance();
 
     @Before
     public void setUp() throws Exception {
@@ -102,24 +99,36 @@ public class BluetoothOppUtilityTest {
 
     @Test
     public void queryRecord_withInvalidFileUrl_returnsNull() {
-        doReturn(null).when(mCallProxy).contentResolverQuery(any(),
-                eq(CORRECT_FORMAT_BUT_INVALID_FILE_URI), eq(null), eq(null),
-                eq(null), eq(null));
-        assertThat(BluetoothOppUtility.queryRecord(mContext,
-                CORRECT_FORMAT_BUT_INVALID_FILE_URI)).isNull();
+        doReturn(null)
+                .when(mCallProxy)
+                .contentResolverQuery(
+                        any(),
+                        eq(CORRECT_FORMAT_BUT_INVALID_FILE_URI),
+                        eq(null),
+                        eq(null),
+                        eq(null),
+                        eq(null));
+        assertThat(BluetoothOppUtility.queryRecord(mContext, CORRECT_FORMAT_BUT_INVALID_FILE_URI))
+                .isNull();
     }
 
     @Test
     public void queryRecord_mockCursor_returnsInstance() {
         String destinationValue = "AA:BB:CC:00:11:22";
 
-        doReturn(mCursor).when(mCallProxy).contentResolverQuery(any(),
-                eq(CORRECT_FORMAT_BUT_INVALID_FILE_URI), eq(null), eq(null),
-                eq(null), eq(null));
+        doReturn(mCursor)
+                .when(mCallProxy)
+                .contentResolverQuery(
+                        any(),
+                        eq(CORRECT_FORMAT_BUT_INVALID_FILE_URI),
+                        eq(null),
+                        eq(null),
+                        eq(null),
+                        eq(null));
         doReturn(true).when(mCursor).moveToFirst();
         doReturn(destinationValue).when(mCursor).getString(anyInt());
-        assertThat(BluetoothOppUtility.queryRecord(mContext,
-                CORRECT_FORMAT_BUT_INVALID_FILE_URI)).isInstanceOf(BluetoothOppTransferInfo.class);
+        assertThat(BluetoothOppUtility.queryRecord(mContext, CORRECT_FORMAT_BUT_INVALID_FILE_URI))
+                .isInstanceOf(BluetoothOppTransferInfo.class);
     }
 
     @Test
@@ -128,18 +137,21 @@ public class BluetoothOppUtilityTest {
         String where = BluetoothShare.TIMESTAMP + " == " + timestampValue;
         AtomicInteger cnt = new AtomicInteger(1);
 
-        doReturn(mCursor).when(mCallProxy).contentResolverQuery(any(),
-                eq(BluetoothShare.CONTENT_URI), eq(new String[]{
-                        BluetoothShare._DATA
-                }), eq(where), eq(null), eq(BluetoothShare._ID));
-
+        doReturn(mCursor)
+                .when(mCallProxy)
+                .contentResolverQuery(
+                        any(),
+                        eq(BluetoothShare.CONTENT_URI),
+                        eq(new String[] {BluetoothShare._DATA}),
+                        eq(where),
+                        eq(null),
+                        eq(BluetoothShare._ID));
 
         doAnswer(invocation -> cnt.incrementAndGet() > 5).when(mCursor).isAfterLast();
-        doReturn(CORRECT_FORMAT_BUT_INVALID_FILE_URI.toString()).when(mCursor)
-                .getString(0);
+        doReturn(CORRECT_FORMAT_BUT_INVALID_FILE_URI.toString()).when(mCursor).getString(0);
 
-        ArrayList answer = BluetoothOppUtility.queryTransfersInBatch(mContext,
-                timestampValue);
+        ArrayList answer =
+                BluetoothOppUtility.queryTransfersInBatch(mContext, timestampValue);
         for (String url : answer) {
             assertThat(url).isEqualTo(CORRECT_FORMAT_BUT_INVALID_FILE_URI.toString());
         }
@@ -154,26 +166,32 @@ public class BluetoothOppUtilityTest {
         Context spiedContext = spy(new ContextWrapper(mContext));
 
         doReturn(0).when(mCallProxy).contentResolverDelete(any(), any(), any(), any());
-        doReturn(mCursor).when(mCallProxy).contentResolverQuery(any(),
-                eq(contentResolverUri), any(), eq(null),
-                eq(null), eq(null));
+        doReturn(mCursor)
+                .when(mCallProxy)
+                .contentResolverQuery(
+                        any(), eq(contentResolverUri), any(), eq(null), eq(null), eq(null));
 
         doReturn(true).when(mCursor).moveToFirst();
         doReturn(fileUri.toString()).when(mCursor).getString(anyInt());
 
-        doReturn(0).when(mCallProxy).contentResolverDelete(any(), any(), nullable(String.class),
-                nullable(String[].class));
+        doReturn(0)
+                .when(mCallProxy)
+                .contentResolverDelete(
+                        any(), any(), nullable(String.class), nullable(String[].class));
 
         // Do nothing since we don't need the actual activity to be launched.
         doNothing().when(spiedContext).startActivity(any());
 
-        BluetoothOppUtility.openReceivedFile(spiedContext, "randomFileName.txt",
-                "text/plain", 0L, contentResolverUri);
+        BluetoothOppUtility.openReceivedFile(
+                spiedContext, "randomFileName.txt", "text/plain", 0L, contentResolverUri);
 
-        verify(spiedContext).startActivity(argThat(argument
-                -> Objects.equals(argument.getComponent().getClassName(),
-                BluetoothOppBtErrorActivity.class.getName())
-        ));
+        verify(spiedContext)
+                .startActivity(
+                        argThat(
+                                argument ->
+                                        Objects.equals(
+                                                argument.getComponent().getClassName(),
+                                                BluetoothOppBtErrorActivity.class.getName())));
     }
 
     @Test
@@ -185,9 +203,10 @@ public class BluetoothOppUtilityTest {
 
         Context spiedContext = spy(new ContextWrapper(mContext));
         // Control BluetoothOppUtility#fileExists flow
-        doReturn(mCursor).when(mCallProxy).contentResolverQuery(any(),
-                eq(contentResolverUri), any(), eq(null),
-                eq(null), eq(null));
+        doReturn(mCursor)
+                .when(mCallProxy)
+                .contentResolverQuery(
+                        any(), eq(contentResolverUri), any(), eq(null), eq(null), eq(null));
 
         doReturn(true).when(mCursor).moveToFirst();
         doReturn(fileUri.toString()).when(mCursor).getString(anyInt());
@@ -198,17 +217,23 @@ public class BluetoothOppUtilityTest {
         // Control BluetoothOppUtility#isRecognizedFileType flow
         PackageManager mockManager = mock(PackageManager.class);
         doReturn(mockManager).when(spiedContext).getPackageManager();
-        doReturn(List.of(new ResolveInfo())).when(mockManager).queryIntentActivities(any(),
-                anyInt());
-
-        BluetoothOppUtility.openReceivedFile(spiedContext, "randomFileName.txt",
-                "text/plain", 0L, contentResolverUri);
-
-        verify(spiedContext).startActivity(argThat(argument
-                        -> Objects.equals(
-                        argument.getData(), Uri.parse("content:///tmp/randomFileName.txt")
-                ) && Objects.equals(argument.getAction(), Intent.ACTION_VIEW)
-        ));
+        doReturn(List.of(new ResolveInfo()))
+                .when(mockManager)
+                .queryIntentActivities(any(), anyInt());
+
+        BluetoothOppUtility.openReceivedFile(
+                spiedContext, "randomFileName.txt", "text/plain", 0L, contentResolverUri);
+
+        verify(spiedContext)
+                .startActivity(
+                        argThat(
+                                argument ->
+                                        Objects.equals(
+                                                        argument.getData(),
+                                                        Uri.parse(
+                                                                "content:///tmp/randomFileName.txt"))
+                                                && Objects.equals(
+                                                        argument.getAction(), Intent.ACTION_VIEW)));
 
         verify(pfd).close();
     }
@@ -221,14 +246,14 @@ public class BluetoothOppUtilityTest {
 
         Context spiedContext = spy(new ContextWrapper(mContext));
         // Control BluetoothOppUtility#fileExists flow
-        doReturn(mCursor).when(mCallProxy).contentResolverQuery(any(),
-                eq(contentResolverUri), any(), eq(null),
-                eq(null), eq(null));
+        doReturn(mCursor)
+                .when(mCallProxy)
+                .contentResolverQuery(
+                        any(), eq(contentResolverUri), any(), eq(null), eq(null), eq(null));
 
         doReturn(true).when(mCursor).moveToFirst();
         doReturn(fileUri.toString()).when(mCursor).getString(anyInt());
 
-
         doReturn(0).when(mCallProxy).contentResolverDelete(any(), any(), any(), any());
         doReturn(pfd).when(mCallProxy).contentResolverOpenFileDescriptor(any(), eq(fileUri), any());
 
@@ -240,13 +265,18 @@ public class BluetoothOppUtilityTest {
         // Do nothing since we don't need the actual activity to be launched.
         doNothing().when(spiedContext).startActivity(any());
 
-        BluetoothOppUtility.openReceivedFile(spiedContext, "randomFileName.txt",
-                "text/plain", 0L, contentResolverUri);
-
-        verify(spiedContext).startActivity(
-                argThat(argument -> argument.getComponent().getClassName().equals(
-                        BluetoothOppBtErrorActivity.class.getName())
-                ));
+        BluetoothOppUtility.openReceivedFile(
+                spiedContext, "randomFileName.txt", "text/plain", 0L, contentResolverUri);
+
+        verify(spiedContext)
+                .startActivity(
+                        argThat(
+                                argument ->
+                                        argument.getComponent()
+                                                .getClassName()
+                                                .equals(
+                                                        BluetoothOppBtErrorActivity.class
+                                                                .getName())));
         verify(pfd).close();
     }
 
@@ -266,18 +296,18 @@ public class BluetoothOppUtilityTest {
         String deviceNameValue =
                 BluetoothOppManager.getInstance(mContext).getDeviceName(remoteDevice);
 
-        List cursorMockDataList = List.of(
-                new CursorMockData(BluetoothShare._ID, 0, idValue),
-                new CursorMockData(BluetoothShare.STATUS, 1, statusValue),
-                new CursorMockData(BluetoothShare.DIRECTION, 2, directionValue),
-                new CursorMockData(BluetoothShare.TOTAL_BYTES, 3, totalBytesValue),
-                new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, currentBytesValue),
-                new CursorMockData(BluetoothShare.TIMESTAMP, 5, timestampValue),
-                new CursorMockData(BluetoothShare.DESTINATION, 6, destinationValue),
-                new CursorMockData(BluetoothShare._DATA, 7, null),
-                new CursorMockData(BluetoothShare.FILENAME_HINT, 8, null),
-                new CursorMockData(BluetoothShare.MIMETYPE, 9, fileTypeValue)
-        );
+        List cursorMockDataList =
+                List.of(
+                        new CursorMockData(BluetoothShare._ID, 0, idValue),
+                        new CursorMockData(BluetoothShare.STATUS, 1, statusValue),
+                        new CursorMockData(BluetoothShare.DIRECTION, 2, directionValue),
+                        new CursorMockData(BluetoothShare.TOTAL_BYTES, 3, totalBytesValue),
+                        new CursorMockData(BluetoothShare.CURRENT_BYTES, 4, currentBytesValue),
+                        new CursorMockData(BluetoothShare.TIMESTAMP, 5, timestampValue),
+                        new CursorMockData(BluetoothShare.DESTINATION, 6, destinationValue),
+                        new CursorMockData(BluetoothShare._DATA, 7, null),
+                        new CursorMockData(BluetoothShare.FILENAME_HINT, 8, null),
+                        new CursorMockData(BluetoothShare.MIMETYPE, 9, fileTypeValue));
 
         BluetoothOppTestUtils.setUpMockCursor(mCursor, cursorMockDataList);
 
@@ -300,18 +330,16 @@ public class BluetoothOppUtilityTest {
 
     @Test
     public void fileExists_returnFalse() {
-        assertThat(
-                BluetoothOppUtility.fileExists(mContext, CORRECT_FORMAT_BUT_INVALID_FILE_URI)
-        ).isFalse();
+        assertThat(BluetoothOppUtility.fileExists(mContext, CORRECT_FORMAT_BUT_INVALID_FILE_URI))
+                .isFalse();
     }
 
     @Test
     public void isRecognizedFileType_withWrongFileUriAndMimeType_returnFalse() {
         assertThat(
-                BluetoothOppUtility.isRecognizedFileType(mContext,
-                        CORRECT_FORMAT_BUT_INVALID_FILE_URI,
-                        "aWrongMimeType")
-        ).isFalse();
+                        BluetoothOppUtility.isRecognizedFileType(
+                                mContext, CORRECT_FORMAT_BUT_INVALID_FILE_URI, "aWrongMimeType"))
+                .isFalse();
     }
 
     @Test
@@ -329,47 +357,60 @@ public class BluetoothOppUtilityTest {
     @Test
     public void getStatusDescription_returnCorrectString() {
         String deviceName = "randomName";
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_PENDING, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_pending));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_RUNNING, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_running));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_SUCCESS, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_success));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_NOT_ACCEPTABLE, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_not_accept));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_FORBIDDEN, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_forbidden));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_CANCELED, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_canceled));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_FILE_ERROR, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_file_error));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_CONNECTION_ERROR, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_connection_error));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_ERROR_NO_SDCARD, deviceName)).isEqualTo(
-                mContext.getString(BluetoothOppUtility.deviceHasNoSdCard()
-                        ? R.string.status_no_sd_card_nosdcard
-                        : R.string.status_no_sd_card_default)
-        );
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_ERROR_SDCARD_FULL, deviceName)).isEqualTo(
-                mContext.getString(
-                        BluetoothOppUtility.deviceHasNoSdCard() ? R.string.bt_sm_2_1_nosdcard
-                                : R.string.bt_sm_2_1_default)
-        );
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext,
-                BluetoothShare.STATUS_BAD_REQUEST, deviceName)).isEqualTo(
-                mContext.getString(R.string.status_protocol_error));
-        assertThat(BluetoothOppUtility.getStatusDescription(mContext, 12345465,
-                deviceName)).isEqualTo(mContext.getString(R.string.status_unknown_error));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_PENDING, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_pending));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_RUNNING, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_running));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_SUCCESS, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_success));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_NOT_ACCEPTABLE, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_not_accept));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_FORBIDDEN, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_forbidden));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_CANCELED, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_canceled));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_FILE_ERROR, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_file_error));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_CONNECTION_ERROR, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_connection_error));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_ERROR_NO_SDCARD, deviceName))
+                .isEqualTo(
+                        mContext.getString(
+                                BluetoothOppUtility.deviceHasNoSdCard()
+                                        ? R.string.status_no_sd_card_nosdcard
+                                        : R.string.status_no_sd_card_default));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_ERROR_SDCARD_FULL, deviceName))
+                .isEqualTo(
+                        mContext.getString(
+                                BluetoothOppUtility.deviceHasNoSdCard()
+                                        ? R.string.bt_sm_2_1_nosdcard
+                                        : R.string.bt_sm_2_1_default));
+        assertThat(
+                        BluetoothOppUtility.getStatusDescription(
+                                mContext, BluetoothShare.STATUS_BAD_REQUEST, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_protocol_error));
+        assertThat(BluetoothOppUtility.getStatusDescription(mContext, 12345465, deviceName))
+                .isEqualTo(mContext.getString(R.string.status_unknown_error));
     }
 
     @Test
@@ -381,22 +422,21 @@ public class BluetoothOppUtilityTest {
 
     @Test
     public void fileInfo_testFileInfoFunctions() {
+        assertThat(BluetoothOppUtility.getSendFileInfo(CORRECT_FORMAT_BUT_INVALID_FILE_URI))
+                .isEqualTo(BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR);
         assertThat(
-                BluetoothOppUtility.getSendFileInfo(CORRECT_FORMAT_BUT_INVALID_FILE_URI)
-        ).isEqualTo(
-                BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR
-        );
-        assertThat(BluetoothOppUtility.generateUri(CORRECT_FORMAT_BUT_INVALID_FILE_URI,
-                BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR).toString()
-        ).contains(
-                CORRECT_FORMAT_BUT_INVALID_FILE_URI.toString());
+                        BluetoothOppUtility.generateUri(
+                                        CORRECT_FORMAT_BUT_INVALID_FILE_URI,
+                                        BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR)
+                                .toString())
+                .contains(CORRECT_FORMAT_BUT_INVALID_FILE_URI.toString());
         try {
-            BluetoothOppUtility.putSendFileInfo(CORRECT_FORMAT_BUT_INVALID_FILE_URI,
+            BluetoothOppUtility.putSendFileInfo(
+                    CORRECT_FORMAT_BUT_INVALID_FILE_URI,
                     BluetoothOppSendFileInfo.SEND_FILE_INFO_ERROR);
             BluetoothOppUtility.closeSendFileInfo(CORRECT_FORMAT_BUT_INVALID_FILE_URI);
         } catch (Exception e) {
             assertWithMessage("Exception should not happen. " + e).fail();
         }
     }
-
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java
index 68756b67e68..b43c6f93a6c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java
@@ -74,10 +74,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
 public class IncomingFileConfirmActivityTest {
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    Cursor mCursor;
-    @Spy
-    BluetoothMethodProxy mBluetoothMethodProxy;
+    @Mock Cursor mCursor;
+    @Spy BluetoothMethodProxy mBluetoothMethodProxy;
 
     List mCursorMockDataList;
 
@@ -104,38 +102,50 @@ public class IncomingFileConfirmActivityTest {
         mIntent.setClass(mTargetContext, BluetoothOppIncomingFileConfirmActivity.class);
         mIntent.setData(dataUrl);
 
-        doReturn(mCursor).when(mBluetoothMethodProxy).contentResolverQuery(any(), eq(dataUrl),
-                eq(null), eq(null),
-                eq(null), eq(null));
+        doReturn(mCursor)
+                .when(mBluetoothMethodProxy)
+                .contentResolverQuery(any(), eq(dataUrl), eq(null), eq(null), eq(null), eq(null));
 
-        doReturn(1).when(mBluetoothMethodProxy).contentResolverUpdate(any(), eq(dataUrl),
-                any(), eq(null), eq(null));
+        doReturn(1)
+                .when(mBluetoothMethodProxy)
+                .contentResolverUpdate(any(), eq(dataUrl), any(), eq(null), eq(null));
 
         int idValue = 1234;
         Long timestampValue = 123456789L;
         String destinationValue = "AA:BB:CC:00:11:22";
         String fileTypeValue = "text/plain";
 
-        mCursorMockDataList = new ArrayList<>(List.of(
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.STATUS, 1,
-                        BluetoothShare.STATUS_PENDING),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DIRECTION, 2,
-                        BluetoothShare.DIRECTION_OUTBOUND),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.TOTAL_BYTES, 3, 100),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.CURRENT_BYTES, 4, 0),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare._ID, 0, idValue),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.MIMETYPE, 5, fileTypeValue),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.TIMESTAMP, 6,
-                        timestampValue),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.DESTINATION, 7,
-                        destinationValue),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare._DATA, 8, null),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.FILENAME_HINT, 9, null),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.URI, 10,
-                        "content://textfile.txt"),
-                new BluetoothOppTestUtils.CursorMockData(BluetoothShare.USER_CONFIRMATION, 11,
-                        BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)
-        ));
+        mCursorMockDataList =
+                new ArrayList<>(
+                        List.of(
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.STATUS, 1, BluetoothShare.STATUS_PENDING),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.DIRECTION,
+                                        2,
+                                        BluetoothShare.DIRECTION_OUTBOUND),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.TOTAL_BYTES, 3, 100),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.CURRENT_BYTES, 4, 0),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare._ID, 0, idValue),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.MIMETYPE, 5, fileTypeValue),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.TIMESTAMP, 6, timestampValue),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.DESTINATION, 7, destinationValue),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare._DATA, 8, null),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.FILENAME_HINT, 9, null),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.URI, 10, "content://textfile.txt"),
+                                new BluetoothOppTestUtils.CursorMockData(
+                                        BluetoothShare.USER_CONFIRMATION,
+                                        11,
+                                        BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)));
 
         BluetoothOppTestUtils.enableActivity(
                 BluetoothOppIncomingFileConfirmActivity.class, true, mTargetContext);
@@ -156,10 +166,9 @@ public class IncomingFileConfirmActivityTest {
             throws InterruptedException {
         BluetoothOppTestUtils.setUpMockCursor(mCursor, mCursorMockDataList);
 
-        ActivityScenario activityScenario
-                = ActivityScenario.launch(mIntent);
-        activityScenario.onActivity(activity -> {
-        });
+        ActivityScenario activityScenario =
+                ActivityScenario.launch(mIntent);
+        activityScenario.onActivity(activity -> {});
 
         // To work around (possibly) ActivityScenario's bug.
         // The dialog button is clicked (no error throw) but onClick() is not triggered.
@@ -169,13 +178,21 @@ public class IncomingFileConfirmActivityTest {
                 .inRoot(isDialog())
                 .perform(ViewActions.scrollTo());
         onView(withText(mTargetContext.getText(R.string.incoming_file_confirm_cancel).toString()))
-                .inRoot(isDialog()).check(matches(isDisplayed())).perform(click());
-
-        verify(mBluetoothMethodProxy).contentResolverUpdate(any(), any(), argThat(
-                argument -> Objects.equal(
-                        BluetoothShare.USER_CONFIRMATION_DENIED,
-                        argument.get(BluetoothShare.USER_CONFIRMATION))
-        ), nullable(String.class), nullable(String[].class));
+                .inRoot(isDialog())
+                .check(matches(isDisplayed()))
+                .perform(click());
+
+        verify(mBluetoothMethodProxy)
+                .contentResolverUpdate(
+                        any(),
+                        any(),
+                        argThat(
+                                argument ->
+                                        Objects.equal(
+                                                BluetoothShare.USER_CONFIRMATION_DENIED,
+                                                argument.get(BluetoothShare.USER_CONFIRMATION))),
+                        nullable(String.class),
+                        nullable(String[].class));
     }
 
     @Test
@@ -193,13 +210,21 @@ public class IncomingFileConfirmActivityTest {
                 .inRoot(isDialog())
                 .perform(ViewActions.scrollTo());
         onView(withText(mTargetContext.getText(R.string.incoming_file_confirm_ok).toString()))
-                .inRoot(isDialog()).check(matches(isDisplayed())).perform(click());
-
-        verify(mBluetoothMethodProxy).contentResolverUpdate(any(), any(), argThat(
-                argument -> Objects.equal(
-                        BluetoothShare.USER_CONFIRMATION_CONFIRMED,
-                        argument.get(BluetoothShare.USER_CONFIRMATION))
-        ), nullable(String.class), nullable(String[].class));
+                .inRoot(isDialog())
+                .check(matches(isDisplayed()))
+                .perform(click());
+
+        verify(mBluetoothMethodProxy)
+                .contentResolverUpdate(
+                        any(),
+                        any(),
+                        argThat(
+                                argument ->
+                                        Objects.equal(
+                                                BluetoothShare.USER_CONFIRMATION_CONFIRMED,
+                                                argument.get(BluetoothShare.USER_CONFIRMATION))),
+                        nullable(String.class),
+                        nullable(String[].class));
     }
 
     @Test
@@ -212,8 +237,9 @@ public class IncomingFileConfirmActivityTest {
         Intent in = new Intent(BluetoothShare.USER_CONFIRMATION_TIMEOUT_ACTION);
         mTargetContext.sendBroadcast(in);
 
-        verify(mBluetoothMethodProxy, timeout(TIMEOUT_MS)).handlerSendMessageDelayed(any(),
-                eq(DISMISS_TIMEOUT_DIALOG), eq((long) DISMISS_TIMEOUT_DIALOG_VALUE));
+        verify(mBluetoothMethodProxy, timeout(TIMEOUT_MS))
+                .handlerSendMessageDelayed(
+                        any(), eq(DISMISS_TIMEOUT_DIALOG), eq((long) DISMISS_TIMEOUT_DIALOG_VALUE));
     }
 
     @Test
@@ -222,19 +248,26 @@ public class IncomingFileConfirmActivityTest {
         ActivityScenario scenario =
                 ActivityScenario.launch(mIntent);
         AtomicBoolean atomicBoolean = new AtomicBoolean();
-        scenario.onActivity(activity -> {
-            atomicBoolean.set(activity.onKeyDown(KeyEvent.KEYCODE_A,
-                    new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A)));
-        });
+        scenario.onActivity(
+                activity -> {
+                    atomicBoolean.set(
+                            activity.onKeyDown(
+                                    KeyEvent.KEYCODE_A,
+                                    new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A)));
+                });
 
         assertThat(atomicBoolean.get()).isFalse();
         assertThat(scenario.getState()).isNotEqualTo(Lifecycle.State.DESTROYED);
 
-        scenario.onActivity(activity -> {
-            atomicBoolean.set(activity.onKeyDown(KeyEvent.KEYCODE_BACK,
-                    new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK))
-                    && activity.isFinishing());
-        });
+        scenario.onActivity(
+                activity -> {
+                    atomicBoolean.set(
+                            activity.onKeyDown(
+                                            KeyEvent.KEYCODE_BACK,
+                                            new KeyEvent(
+                                                    KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK))
+                                    && activity.isFinishing());
+                });
 
         assertThat(atomicBoolean.get()).isTrue();
     }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/TestActivity.java b/android/app/tests/unit/src/com/android/bluetooth/opp/TestActivity.java
index 2710aa18211..4fa885f1835 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/TestActivity.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/TestActivity.java
@@ -114,13 +114,13 @@ public class TestActivity extends Activity {
                  * Email.ACCEPTABLE_ATTACHMENT_SEND_TYPES)) {
                  * addAttachment(stream);
                  */
-                Log.v(Constants.TAG,
+                Log.v(
+                        Constants.TAG,
                         " Get share intent with Uri " + stream + " mimetype is " + type);
                 // Log.v(Constants.TAG, " trying Uri function " +
                 // stream.getAuthority() + " " + Uri.parse(stream));
                 Cursor cursor = c.getContentResolver().query(stream, null, null, null, null);
                 cursor.close();
-
             }
             /* start insert a record */
             /*
@@ -212,149 +212,164 @@ public class TestActivity extends Activity {
 
     }
 
-    public OnClickListener insertRecordListener = new OnClickListener() {
-        @Override
-        public void onClick(View view) {
+    public OnClickListener insertRecordListener =
+            new OnClickListener() {
+                @Override
+                public void onClick(View view) {
 
-            String address = null;
-            if (mAddressView.getText().length() != 0) {
-                address = mAddressView.getText().toString();
-                Log.v(Constants.TAG, "Send to address  " + address);
-            }
-            if (address == null) {
-                address = "00:17:83:58:5D:CC";
-            }
+                    String address = null;
+                    if (mAddressView.getText().length() != 0) {
+                        address = mAddressView.getText().toString();
+                        Log.v(Constants.TAG, "Send to address  " + address);
+                    }
+                    if (address == null) {
+                        address = "00:17:83:58:5D:CC";
+                    }
 
-            Integer media = null;
-            if (mMediaView.getText().length() != 0) {
-                media = Integer.parseInt(mMediaView.getText().toString().trim());
-                Log.v(Constants.TAG, "Send media no.  " + media);
-            }
-            if (media == null) {
-                media = 1;
-            }
-            ContentValues values = new ContentValues();
-            values.put(BluetoothShare.URI, "content://media/external/images/media/" + media);
-            // values.put(BluetoothShare.DESTINATION, "FF:FF:FF:00:00:00");
-            // baibai Q9 test
-            // values.put(BluetoothShare.DESTINATION, "12:34:56:78:9A:BC");
-            // java's nokia
-            // values.put(BluetoothShare.DESTINATION, "00:1B:33:F0:58:FB");
-            // Assis phone
-            // values.put(BluetoothShare.DESTINATION, "00:17:E5:5D:74:F3");
-            // Jackson E6
-            // values.put(BluetoothShare.DESTINATION, "00:1A:1B:7F:1E:F0");
-            // Baibai V950
-            // values.put(BluetoothShare.DESTINATION, "00:17:83:58:5D:CC");
-            // Baibai NSC1173
-            // values.put(BluetoothShare.DESTINATION, "00:16:41:49:5B:F3");
-
-            values.put(BluetoothShare.DESTINATION, address);
-
-            values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
-
-            Long ts = System.currentTimeMillis();
-            values.put(BluetoothShare.TIMESTAMP, ts);
-
-            Integer records = null;
-            if (mInsertView.getText().length() != 0) {
-                records = Integer.parseInt(mInsertView.getText().toString().trim());
-                Log.v(Constants.TAG, "parseInt  " + records);
-            }
-            if (records == null) {
-                records = 1;
-            }
-            for (int i = 0; i < records; i++) {
-                Uri contentUri = getContentResolver().insert(BluetoothShare.CONTENT_URI, values);
-                Log.v(Constants.TAG, "insert contentUri: " + contentUri);
-                currentInsert = contentUri.getPathSegments().get(1);
-                Log.v(Constants.TAG, "currentInsert = " + currentInsert);
-            }
+                    Integer media = null;
+                    if (mMediaView.getText().length() != 0) {
+                        media = Integer.parseInt(mMediaView.getText().toString().trim());
+                        Log.v(Constants.TAG, "Send media no.  " + media);
+                    }
+                    if (media == null) {
+                        media = 1;
+                    }
+                    ContentValues values = new ContentValues();
+                    values.put(
+                            BluetoothShare.URI, "content://media/external/images/media/" + media);
+                    // values.put(BluetoothShare.DESTINATION, "FF:FF:FF:00:00:00");
+                    // baibai Q9 test
+                    // values.put(BluetoothShare.DESTINATION, "12:34:56:78:9A:BC");
+                    // java's nokia
+                    // values.put(BluetoothShare.DESTINATION, "00:1B:33:F0:58:FB");
+                    // Assis phone
+                    // values.put(BluetoothShare.DESTINATION, "00:17:E5:5D:74:F3");
+                    // Jackson E6
+                    // values.put(BluetoothShare.DESTINATION, "00:1A:1B:7F:1E:F0");
+                    // Baibai V950
+                    // values.put(BluetoothShare.DESTINATION, "00:17:83:58:5D:CC");
+                    // Baibai NSC1173
+                    // values.put(BluetoothShare.DESTINATION, "00:16:41:49:5B:F3");
+
+                    values.put(BluetoothShare.DESTINATION, address);
+
+                    values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
+
+                    Long ts = System.currentTimeMillis();
+                    values.put(BluetoothShare.TIMESTAMP, ts);
+
+                    Integer records = null;
+                    if (mInsertView.getText().length() != 0) {
+                        records = Integer.parseInt(mInsertView.getText().toString().trim());
+                        Log.v(Constants.TAG, "parseInt  " + records);
+                    }
+                    if (records == null) {
+                        records = 1;
+                    }
+                    for (int i = 0; i < records; i++) {
+                        Uri contentUri =
+                                getContentResolver().insert(BluetoothShare.CONTENT_URI, values);
+                        Log.v(Constants.TAG, "insert contentUri: " + contentUri);
+                        currentInsert = contentUri.getPathSegments().get(1);
+                        Log.v(Constants.TAG, "currentInsert = " + currentInsert);
+                    }
+                }
+            };
 
-        }
-    };
-
-    public OnClickListener deleteRecordListener = new OnClickListener() {
-        @Override
-        public void onClick(View view) {
-            Uri contentUri =
-                    Uri.parse(BluetoothShare.CONTENT_URI + "/" + mDeleteView.getText().toString());
-            getContentResolver().delete(contentUri, null, null);
-        }
-    };
-
-    public OnClickListener updateRecordListener = new OnClickListener() {
-        @Override
-        public void onClick(View view) {
-            Uri contentUri =
-                    Uri.parse(BluetoothShare.CONTENT_URI + "/" + mUpdateView.getText().toString());
-            ContentValues updateValues = new ContentValues();
-            // mCurrentByte ++;
-            // updateValues.put(BluetoothShare.TOTAL_BYTES, "120000");
-            // updateValues.put(BluetoothShare.CURRENT_BYTES, mCurrentByte);
-            // updateValues.put(BluetoothShare.VISIBILITY,
-            // BluetoothShare.VISIBILITY_HIDDEN);
-            updateValues.put(BluetoothShare.USER_CONFIRMATION,
-                    BluetoothShare.USER_CONFIRMATION_CONFIRMED);
-            getContentResolver().update(contentUri, updateValues, null, null);
-        }
-    };
-
-    public OnClickListener ackRecordListener = new OnClickListener() {
-        @Override
-        public void onClick(View view) {
-            Uri contentUri =
-                    Uri.parse(BluetoothShare.CONTENT_URI + "/" + mAckView.getText().toString());
-            ContentValues updateValues = new ContentValues();
-            // mCurrentByte ++;
-            // updateValues.put(BluetoothShare.TOTAL_BYTES, "120000");
-            // updateValues.put(BluetoothShare.CURRENT_BYTES, mCurrentByte);
-            updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
-            // updateValues.put(BluetoothShare.USER_CONFIRMATION,
-            // BluetoothShare.USER_CONFIRMATION_CONFIRMED);
-            getContentResolver().update(contentUri, updateValues, null, null);
-        }
-    };
+    public OnClickListener deleteRecordListener =
+            new OnClickListener() {
+                @Override
+                public void onClick(View view) {
+                    Uri contentUri =
+                            Uri.parse(
+                                    BluetoothShare.CONTENT_URI
+                                            + "/"
+                                            + mDeleteView.getText().toString());
+                    getContentResolver().delete(contentUri, null, null);
+                }
+            };
 
-    public OnClickListener deleteAllRecordListener = new OnClickListener() {
-        @Override
-        public void onClick(View view) {
-            Uri contentUri = Uri.parse(String.valueOf(BluetoothShare.CONTENT_URI));
-            getContentResolver().delete(contentUri, null, null);
-        }
-    };
-
-    public OnClickListener startTcpServerListener = new OnClickListener() {
-        @Override
-        public void onClick(View view) {
-            mServer = new TestTcpServer();
-            Thread serverThread = new Thread(mServer);
-            serverThread.start();
-        }
-    };
+    public OnClickListener updateRecordListener =
+            new OnClickListener() {
+                @Override
+                public void onClick(View view) {
+                    Uri contentUri =
+                            Uri.parse(
+                                    BluetoothShare.CONTENT_URI
+                                            + "/"
+                                            + mUpdateView.getText().toString());
+                    ContentValues updateValues = new ContentValues();
+                    // mCurrentByte ++;
+                    // updateValues.put(BluetoothShare.TOTAL_BYTES, "120000");
+                    // updateValues.put(BluetoothShare.CURRENT_BYTES, mCurrentByte);
+                    // updateValues.put(BluetoothShare.VISIBILITY,
+                    // BluetoothShare.VISIBILITY_HIDDEN);
+                    updateValues.put(
+                            BluetoothShare.USER_CONFIRMATION,
+                            BluetoothShare.USER_CONFIRMATION_CONFIRMED);
+                    getContentResolver().update(contentUri, updateValues, null, null);
+                }
+            };
 
-    public OnClickListener notifyTcpServerListener = new OnClickListener() {
-        @Override
-        public void onClick(View view) {
-            final Thread notifyThread = new Thread() {
+    public OnClickListener ackRecordListener =
+            new OnClickListener() {
                 @Override
-                public void run() {
-                    synchronized (mServer) {
-                        mServer.a = true;
-                        mServer.notify();
-                    }
+                public void onClick(View view) {
+                    Uri contentUri =
+                            Uri.parse(
+                                    BluetoothShare.CONTENT_URI
+                                            + "/"
+                                            + mAckView.getText().toString());
+                    ContentValues updateValues = new ContentValues();
+                    // mCurrentByte ++;
+                    // updateValues.put(BluetoothShare.TOTAL_BYTES, "120000");
+                    // updateValues.put(BluetoothShare.CURRENT_BYTES, mCurrentByte);
+                    updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
+                    // updateValues.put(BluetoothShare.USER_CONFIRMATION,
+                    // BluetoothShare.USER_CONFIRMATION_CONFIRMED);
+                    getContentResolver().update(contentUri, updateValues, null, null);
+                }
+            };
+
+    public OnClickListener deleteAllRecordListener =
+            new OnClickListener() {
+                @Override
+                public void onClick(View view) {
+                    Uri contentUri = Uri.parse(String.valueOf(BluetoothShare.CONTENT_URI));
+                    getContentResolver().delete(contentUri, null, null);
                 }
+            };
 
+    public OnClickListener startTcpServerListener =
+            new OnClickListener() {
+                @Override
+                public void onClick(View view) {
+                    mServer = new TestTcpServer();
+                    Thread serverThread = new Thread(mServer);
+                    serverThread.start();
+                }
             };
-            notifyThread.start();
-        }
 
-    };
+    public OnClickListener notifyTcpServerListener =
+            new OnClickListener() {
+                @Override
+                public void onClick(View view) {
+                    final Thread notifyThread =
+                            new Thread() {
+                                @Override
+                                public void run() {
+                                    synchronized (mServer) {
+                                        mServer.a = true;
+                                        mServer.notify();
+                                    }
+                                }
+                            };
+                    notifyThread.start();
+                }
+            };
 }
 
-/**
- * This class listens on OPUSH channel for incoming connection
- */
+/** This class listens on OPUSH channel for incoming connection */
 class TestTcpListener {
 
     private static final String TAG = "BtOppRfcommListener";
@@ -388,66 +403,73 @@ class TestTcpListener {
     public synchronized boolean start(Handler callback) {
         if (mSocketAcceptThread == null) {
             mCallback = callback;
-            mSocketAcceptThread = new Thread(TAG) {
-                ServerSocket mServerSocket;
-
-                @Override
-                public void run() {
-                    if (D) {
-                        Log.d(TAG, "RfcommSocket listen thread starting");
-                    }
-                    try {
-                        if (V) {
-                            Log.v(TAG,
-                                    "Create server RfcommSocket on channel" + mBtOppRfcommChannel);
-                        }
-                        mServerSocket = new ServerSocket(6500, 1);
-                    } catch (IOException e) {
-                        Log.e(TAG, "Error listing on channel" + mBtOppRfcommChannel);
-                        mInterrupted = true;
-                    }
-                    while (!mInterrupted) {
-                        try {
-                            mServerSocket.setSoTimeout(ACCEPT_WAIT_TIMEOUT);
-                            Socket clientSocket = mServerSocket.accept();
-                            if (clientSocket == null) {
+            mSocketAcceptThread =
+                    new Thread(TAG) {
+                        ServerSocket mServerSocket;
+
+                        @Override
+                        public void run() {
+                            if (D) {
+                                Log.d(TAG, "RfcommSocket listen thread starting");
+                            }
+                            try {
                                 if (V) {
-                                    Log.v(TAG, "incomming connection time out");
-                                }
-                            } else {
-                                if (D) {
-                                    Log.d(TAG, "RfcommSocket connected!");
+                                    Log.v(
+                                            TAG,
+                                            "Create server RfcommSocket on channel"
+                                                    + mBtOppRfcommChannel);
                                 }
-                                Log.d(TAG,
-                                        "remote addr is " + clientSocket.getRemoteSocketAddress());
-                                TestTcpTransport transport = new TestTcpTransport(clientSocket);
-                                Message msg = Message.obtain();
-                                msg.setTarget(mCallback);
-                                msg.what = MSG_INCOMING_BTOPP_CONNECTION;
-                                msg.obj = transport;
-                                msg.sendToTarget();
+                                mServerSocket = new ServerSocket(6500, 1);
+                            } catch (IOException e) {
+                                Log.e(TAG, "Error listing on channel" + mBtOppRfcommChannel);
+                                mInterrupted = true;
                             }
-                        } catch (SocketException e) {
-                            Log.e(TAG, "Error accept connection " + e);
-                        } catch (IOException e) {
-                            Log.e(TAG, "Error accept connection " + e);
-                        }
+                            while (!mInterrupted) {
+                                try {
+                                    mServerSocket.setSoTimeout(ACCEPT_WAIT_TIMEOUT);
+                                    Socket clientSocket = mServerSocket.accept();
+                                    if (clientSocket == null) {
+                                        if (V) {
+                                            Log.v(TAG, "incomming connection time out");
+                                        }
+                                    } else {
+                                        if (D) {
+                                            Log.d(TAG, "RfcommSocket connected!");
+                                        }
+                                        Log.d(
+                                                TAG,
+                                                "remote addr is "
+                                                        + clientSocket.getRemoteSocketAddress());
+                                        TestTcpTransport transport =
+                                                new TestTcpTransport(clientSocket);
+                                        Message msg = Message.obtain();
+                                        msg.setTarget(mCallback);
+                                        msg.what = MSG_INCOMING_BTOPP_CONNECTION;
+                                        msg.obj = transport;
+                                        msg.sendToTarget();
+                                    }
+                                } catch (SocketException e) {
+                                    Log.e(TAG, "Error accept connection " + e);
+                                } catch (IOException e) {
+                                    Log.e(TAG, "Error accept connection " + e);
+                                }
 
-                        if (mInterrupted) {
-                            Log.e(TAG, "socketAcceptThread thread was interrupted (2), exiting");
+                                if (mInterrupted) {
+                                    Log.e(
+                                            TAG,
+                                            "socketAcceptThread thread was interrupted (2),"
+                                                    + " exiting");
+                                }
+                            }
+                            if (D) {
+                                Log.d(TAG, "RfcommSocket listen thread finished");
+                            }
                         }
-                    }
-                    if (D) {
-                        Log.d(TAG, "RfcommSocket listen thread finished");
-                    }
-                }
-            };
+                    };
             mInterrupted = false;
             mSocketAcceptThread.start();
-
         }
         return true;
-
     }
 
     public synchronized void stop() {
@@ -471,7 +493,6 @@ class TestTcpListener {
             }
         }
     }
-
 }
 
 class TestTcpServer extends ServerRequestHandler implements Runnable {
@@ -528,8 +549,11 @@ class TestTcpServer extends ServerRequestHandler implements Runnable {
         try {
             java.io.InputStream is = op.openInputStream();
 
-            updateStatus("Got data bytes " + is.available() + " name " + op.getReceivedHeader()
-                    .getHeader(HeaderSet.NAME));
+            updateStatus(
+                    "Got data bytes "
+                            + is.available()
+                            + " name "
+                            + op.getReceivedHeader().getHeader(HeaderSet.NAME));
 
             File f = new File((String) op.getReceivedHeader().getHeader(HeaderSet.NAME));
             fos = new FileOutputStream(f);
@@ -567,8 +591,7 @@ class TestTcpServer extends ServerRequestHandler implements Runnable {
     }
 
     @Override
-    public void onAuthenticationFailure(byte[] userName) {
-    }
+    public void onAuthenticationFailure(byte[] userName) {}
 
     @Override
     public int onSetPath(HeaderSet request, HeaderSet reply, boolean backup, boolean create) {
@@ -585,7 +608,6 @@ class TestTcpServer extends ServerRequestHandler implements Runnable {
     public int onGet(Operation op) {
         return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
     }
-
 }
 
 class TestTcpSessionNotifier {
@@ -613,15 +635,12 @@ class TestTcpSessionNotifier {
         TestTcpTransport tt = new TestTcpTransport(mConn);
 
         return new ServerSession((ObexTransport) tt, handler, auth);
-
     }
 
     public ServerSession acceptAndOpen(ServerRequestHandler handler) throws IOException {
 
         return acceptAndOpen(handler, null);
-
     }
-
 }
 
 class TestTcpTransport implements ObexTransport {
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java
index 4adb1889e9c..a80863120b5 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java
@@ -42,17 +42,14 @@ import org.mockito.junit.MockitoRule;
 import java.util.ArrayList;
 import java.util.List;
 
-/**
- * Test cases for {@link BluetoothTetheringNetworkFactory}.
- */
+/** Test cases for {@link BluetoothTetheringNetworkFactory}. */
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class BluetoothTetheringNetworkFactoryTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private PanService mPanService;
+    @Mock private PanService mPanService;
 
     private Context mContext = ApplicationProvider.getApplicationContext();
 
@@ -100,8 +97,7 @@ public class BluetoothTetheringNetworkFactoryTest {
 
         assertThat(bluetoothTetheringNetworkFactory.getProvider()).isNotNull();
 
-        BluetoothAdapter adapter =
-                mContext.getSystemService(BluetoothManager.class).getAdapter();
+        BluetoothAdapter adapter = mContext.getSystemService(BluetoothManager.class).getAdapter();
         List bluetoothDevices = new ArrayList<>();
         BluetoothDevice bluetoothDevice = adapter.getRemoteDevice("11:11:11:11:11:11");
         bluetoothDevices.add(bluetoothDevice);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java
index 86bfd8e0eaa..2033db98cfc 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java
@@ -40,8 +40,7 @@ public class PanServiceBinderTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private PanService mService;
+    @Mock private PanService mService;
 
     BluetoothDevice mRemoteDevice;
 
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
index 6467b771613..5d4e9216dc3 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
@@ -175,7 +175,8 @@ public class PanServiceTest {
     public void setConnectionPolicy_whenDatabaseManagerRefuses_returnsFalse() {
         int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
         when(mDatabaseManager.setProfileConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.PAN, connectionPolicy)).thenReturn(false);
+                        mRemoteDevice, BluetoothProfile.PAN, connectionPolicy))
+                .thenReturn(false);
 
         assertThat(mService.setConnectionPolicy(mRemoteDevice, connectionPolicy)).isFalse();
     }
@@ -183,16 +184,24 @@ public class PanServiceTest {
     @Test
     public void setConnectionPolicy_returnsTrue() {
         when(mDatabaseManager.setProfileConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.PAN, BluetoothProfile.CONNECTION_POLICY_ALLOWED))
+                        mRemoteDevice,
+                        BluetoothProfile.PAN,
+                        BluetoothProfile.CONNECTION_POLICY_ALLOWED))
                 .thenReturn(true);
-        assertThat(mService.setConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED)).isTrue();
+        assertThat(
+                        mService.setConnectionPolicy(
+                                mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED))
+                .isTrue();
 
         when(mDatabaseManager.setProfileConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.PAN, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+                        mRemoteDevice,
+                        BluetoothProfile.PAN,
+                        BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
                 .thenReturn(true);
-        assertThat(mService.setConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)).isTrue();
+        assertThat(
+                        mService.setConnectionPolicy(
+                                mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+                .isTrue();
     }
 
     @Test
@@ -202,8 +211,9 @@ public class PanServiceTest {
         int localRole = 3;
         int remoteRole = 4;
 
-        PanService.ConnectState connectState = new PanService.ConnectState(
-                REMOTE_DEVICE_ADDRESS_AS_ARRAY, state, error, localRole, remoteRole);
+        PanService.ConnectState connectState =
+                new PanService.ConnectState(
+                        REMOTE_DEVICE_ADDRESS_AS_ARRAY, state, error, localRole, remoteRole);
 
         assertThat(connectState.addr).isEqualTo(REMOTE_DEVICE_ADDRESS_AS_ARRAY);
         assertThat(connectState.state).isEqualTo(state);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapActivityTest.java
index e5431c5524f..54674b1d14c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapActivityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapActivityTest.java
@@ -104,8 +104,11 @@ public class BluetoothPbapActivityTest {
     public void onPreferenceChange_returnsTrue() throws Exception {
         AtomicBoolean result = new AtomicBoolean(false);
 
-        mActivityScenario.onActivity(activity -> result.set(
-                activity.onPreferenceChange(/*preference=*/null, /*newValue=*/null)));
+        mActivityScenario.onActivity(
+                activity ->
+                        result.set(
+                                activity.onPreferenceChange(
+                                        /* preference= */ null, /* newValue= */ null)));
 
         assertThat(result.get()).isTrue();
     }
@@ -140,9 +143,10 @@ public class BluetoothPbapActivityTest {
     public void onReceiveTimeoutIntent_sendsDismissDialogMessage() throws Exception {
         Intent intent = new Intent(BluetoothPbapService.USER_CONFIRM_TIMEOUT_ACTION);
 
-        mActivityScenario.onActivity(activity -> {
-            activity.mReceiver.onReceive(activity, intent);
-        });
+        mActivityScenario.onActivity(
+                activity -> {
+                    activity.mReceiver.onReceive(activity, intent);
+                });
 
         verify(mMethodProxy)
                 .handlerSendMessageDelayed(
@@ -154,10 +158,11 @@ public class BluetoothPbapActivityTest {
         Editable editable = new SpannableStringBuilder("An editable text");
         AtomicBoolean result = new AtomicBoolean(false);
 
-        mActivityScenario.onActivity(activity -> {
-            activity.afterTextChanged(editable);
-            result.set(activity.getButton(BUTTON_POSITIVE).isEnabled());
-        });
+        mActivityScenario.onActivity(
+                activity -> {
+                    activity.afterTextChanged(editable);
+                    result.set(activity.getButton(BUTTON_POSITIVE).isEnabled());
+                });
 
         assertThat(result.get()).isTrue();
     }
@@ -169,10 +174,11 @@ public class BluetoothPbapActivityTest {
     @Test
     public void emptyMethods_doesNotThrowException() throws Exception {
         try {
-            mActivityScenario.onActivity(activity -> {
-                activity.beforeTextChanged(null, 0, 0, 0);
-                activity.onTextChanged(null, 0, 0, 0);
-            });
+            mActivityScenario.onActivity(
+                    activity -> {
+                        activity.beforeTextChanged(null, 0, 0, 0);
+                        activity.onTextChanged(null, 0, 0, 0);
+                    });
         } catch (Exception ex) {
             assertWithMessage("Exception should not happen!").fail();
         }
@@ -185,14 +191,17 @@ public class BluetoothPbapActivityTest {
     }
 
     private void enableActivity(boolean enable) {
-        int enabledState = enable ? COMPONENT_ENABLED_STATE_ENABLED
-                : COMPONENT_ENABLED_STATE_DEFAULT;
+        int enabledState =
+                enable ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DEFAULT;
 
-        mTargetContext.getPackageManager().setApplicationEnabledSetting(
-                mTargetContext.getPackageName(), enabledState, DONT_KILL_APP);
+        mTargetContext
+                .getPackageManager()
+                .setApplicationEnabledSetting(
+                        mTargetContext.getPackageName(), enabledState, DONT_KILL_APP);
 
         ComponentName activityName = new ComponentName(mTargetContext, BluetoothPbapActivity.class);
-        mTargetContext.getPackageManager().setComponentEnabledSetting(
-                activityName, enabledState, DONT_KILL_APP);
+        mTargetContext
+                .getPackageManager()
+                .setComponentEnabledSetting(activityName, enabledState, DONT_KILL_APP);
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapAuthenticatorTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapAuthenticatorTest.java
index 9c00501b633..60b79dce88c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapAuthenticatorTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapAuthenticatorTest.java
@@ -42,8 +42,7 @@ public class BluetoothPbapAuthenticatorTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    PbapStateMachine mMockPbapStateMachine;
+    @Mock PbapStateMachine mMockPbapStateMachine;
 
     @Before
     public void setUp() throws Exception {
@@ -90,34 +89,48 @@ public class BluetoothPbapAuthenticatorTest {
     @Test
     public void testOnAuthenticationChallenge() {
         final String sessionKey = "test_session_key";
-        doAnswer(invocation -> {
-            mAuthenticator.setSessionKey(sessionKey);
-            mAuthenticator.setChallenged(true);
-            return null;
-        }).when(mMockPbapStateMachine).sendMessage(PbapStateMachine.CREATE_NOTIFICATION);
+        doAnswer(
+                        invocation -> {
+                            mAuthenticator.setSessionKey(sessionKey);
+                            mAuthenticator.setChallenged(true);
+                            return null;
+                        })
+                .when(mMockPbapStateMachine)
+                .sendMessage(PbapStateMachine.CREATE_NOTIFICATION);
 
         // Note: onAuthenticationChallenge() does not use any arguments
-        PasswordAuthentication passwordAuthentication = mAuthenticator.onAuthenticationChallenge(
-                /*description=*/ null, /*isUserIdRequired=*/ false, /*isFullAccess=*/ false);
+        PasswordAuthentication passwordAuthentication =
+                mAuthenticator.onAuthenticationChallenge(
+                        /* description= */ null,
+                        /* isUserIdRequired= */ false,
+                        /* isFullAccess= */ false);
 
         verify(mMockPbapStateMachine).sendMessage(PbapStateMachine.CREATE_NOTIFICATION);
-        verify(mMockPbapStateMachine).sendMessageDelayed(PbapStateMachine.REMOVE_NOTIFICATION,
-                BluetoothPbapService.USER_CONFIRM_TIMEOUT_VALUE);
+        verify(mMockPbapStateMachine)
+                .sendMessageDelayed(
+                        PbapStateMachine.REMOVE_NOTIFICATION,
+                        BluetoothPbapService.USER_CONFIRM_TIMEOUT_VALUE);
         assertThat(passwordAuthentication.getPassword()).isEqualTo(sessionKey.getBytes());
     }
 
     @Test
     public void testOnAuthenticationChallenge_returnsNullWhenSessionKeyIsEmpty() {
         final String emptySessionKey = "";
-        doAnswer(invocation -> {
-            mAuthenticator.setSessionKey(emptySessionKey);
-            mAuthenticator.setChallenged(true);
-            return null;
-        }).when(mMockPbapStateMachine).sendMessage(PbapStateMachine.CREATE_NOTIFICATION);
+        doAnswer(
+                        invocation -> {
+                            mAuthenticator.setSessionKey(emptySessionKey);
+                            mAuthenticator.setChallenged(true);
+                            return null;
+                        })
+                .when(mMockPbapStateMachine)
+                .sendMessage(PbapStateMachine.CREATE_NOTIFICATION);
 
         // Note: onAuthenticationChallenge() does not use any arguments
-        PasswordAuthentication passwordAuthentication = mAuthenticator.onAuthenticationChallenge(
-                /*description=*/ null, /*isUserIdRequired=*/ false, /*isFullAccess=*/ false);
+        PasswordAuthentication passwordAuthentication =
+                mAuthenticator.onAuthenticationChallenge(
+                        /* description= */ null,
+                        /* isUserIdRequired= */ false,
+                        /* isFullAccess= */ false);
         assertThat(passwordAuthentication).isNull();
     }
 
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposerTest.java
index 1ea6786e8bf..cd1699a27c9 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposerTest.java
@@ -64,19 +64,18 @@ public class BluetoothPbapCallLogComposerTest {
 
     private BluetoothPbapCallLogComposer mComposer;
 
-    @Spy
-    BluetoothMethodProxy mPbapCallProxy = BluetoothMethodProxy.getInstance();
+    @Spy BluetoothMethodProxy mPbapCallProxy = BluetoothMethodProxy.getInstance();
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    Cursor mMockCursor;
+    @Mock Cursor mMockCursor;
 
     @Before
     public void setUp() throws Exception {
         BluetoothMethodProxy.setInstanceForTesting(mPbapCallProxy);
 
-        doReturn(mMockCursor).when(mPbapCallProxy)
+        doReturn(mMockCursor)
+                .when(mPbapCallProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
         final int validRowCount = 5;
         when(mMockCursor.getCount()).thenReturn(validRowCount);
@@ -92,8 +91,7 @@ public class BluetoothPbapCallLogComposerTest {
 
     @Test
     public void testInit_success() {
-        assertThat(mComposer.init(CALL_LOG_URI, SELECTION, SELECTION_ARGS, SORT_ORDER))
-                .isTrue();
+        assertThat(mComposer.init(CALL_LOG_URI, SELECTION, SELECTION_ARGS, SORT_ORDER)).isTrue();
         assertThat(mComposer.getErrorReason()).isEqualTo(NO_ERROR);
     }
 
@@ -109,11 +107,11 @@ public class BluetoothPbapCallLogComposerTest {
 
     @Test
     public void testInit_failWhenCursorIsNull() {
-        doReturn(null).when(mPbapCallProxy)
+        doReturn(null)
+                .when(mPbapCallProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
-        assertThat(mComposer.init(CALL_LOG_URI, SELECTION, SELECTION_ARGS, SORT_ORDER))
-                .isFalse();
+        assertThat(mComposer.init(CALL_LOG_URI, SELECTION, SELECTION_ARGS, SORT_ORDER)).isFalse();
         assertThat(mComposer.getErrorReason())
                 .isEqualTo(FAILURE_REASON_FAILED_TO_GET_DATABASE_INFO);
     }
@@ -122,8 +120,7 @@ public class BluetoothPbapCallLogComposerTest {
     public void testInit_failWhenCursorRowCountIsZero() {
         when(mMockCursor.getCount()).thenReturn(0);
 
-        assertThat(mComposer.init(CALL_LOG_URI, SELECTION, SELECTION_ARGS, SORT_ORDER))
-                .isFalse();
+        assertThat(mComposer.init(CALL_LOG_URI, SELECTION, SELECTION_ARGS, SORT_ORDER)).isFalse();
         assertThat(mComposer.getErrorReason()).isEqualTo(FAILURE_REASON_NO_ENTRY);
         verify(mMockCursor).close();
     }
@@ -132,8 +129,7 @@ public class BluetoothPbapCallLogComposerTest {
     public void testInit_failWhenCursorMoveToFirstFails() {
         when(mMockCursor.moveToFirst()).thenReturn(false);
 
-        assertThat(mComposer.init(CALL_LOG_URI, SELECTION, SELECTION_ARGS, SORT_ORDER))
-                .isFalse();
+        assertThat(mComposer.init(CALL_LOG_URI, SELECTION, SELECTION_ARGS, SORT_ORDER)).isFalse();
         assertThat(mComposer.getErrorReason()).isEqualTo(FAILURE_REASON_NO_ENTRY);
         verify(mMockCursor).close();
     }
@@ -159,8 +155,12 @@ public class BluetoothPbapCallLogComposerTest {
         final String testPhoneName = "test_phone_name";
         final String testPhoneNumber = "0123456789";
 
-        assertThat(BluetoothPbapCallLogComposer.composeVCardForPhoneOwnNumber(
-                testPhoneType, testPhoneName, testPhoneNumber, /*vcardVer21=*/ true))
+        assertThat(
+                        BluetoothPbapCallLogComposer.composeVCardForPhoneOwnNumber(
+                                testPhoneType,
+                                testPhoneName,
+                                testPhoneNumber,
+                                /* vcardVer21= */ true))
                 .contains(testPhoneNumber);
     }
 
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapConfigTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapConfigTest.java
index 30445b1399b..634fe3b247c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapConfigTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapConfigTest.java
@@ -42,11 +42,9 @@ public class BluetoothPbapConfigTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    Context mContext;
+    @Mock Context mContext;
 
-    @Mock
-    Resources mResources;
+    @Mock Resources mResources;
 
     @Before
     public void setUp() throws Exception {
@@ -55,8 +53,7 @@ public class BluetoothPbapConfigTest {
 
     @Test
     public void testInit_whenUseProfileForOwnerVcardIsTrue() {
-        when(mResources.getBoolean(R.bool.pbap_use_profile_for_owner_vcard))
-                .thenReturn(true);
+        when(mResources.getBoolean(R.bool.pbap_use_profile_for_owner_vcard)).thenReturn(true);
 
         BluetoothPbapConfig.init(mContext);
         assertThat(BluetoothPbapConfig.useProfileForOwnerVcard()).isTrue();
@@ -64,8 +61,7 @@ public class BluetoothPbapConfigTest {
 
     @Test
     public void testInit_whenUseProfileForOwnerVcardIsFalse() {
-        when(mResources.getBoolean(R.bool.pbap_use_profile_for_owner_vcard))
-                .thenReturn(false);
+        when(mResources.getBoolean(R.bool.pbap_use_profile_for_owner_vcard)).thenReturn(false);
 
         BluetoothPbapConfig.init(mContext);
         assertThat(BluetoothPbapConfig.useProfileForOwnerVcard()).isFalse();
@@ -82,8 +78,7 @@ public class BluetoothPbapConfigTest {
 
     @Test
     public void testInit_whenIncludePhotosInVcardIsTrue() {
-        when(mResources.getBoolean(R.bool.pbap_include_photos_in_vcard))
-                .thenReturn(true);
+        when(mResources.getBoolean(R.bool.pbap_include_photos_in_vcard)).thenReturn(true);
 
         BluetoothPbapConfig.init(mContext);
         assertThat(BluetoothPbapConfig.includePhotosInVcard()).isTrue();
@@ -91,8 +86,7 @@ public class BluetoothPbapConfigTest {
 
     @Test
     public void testInit_whenIncludePhotosInVcardIsFalse() {
-        when(mResources.getBoolean(R.bool.pbap_include_photos_in_vcard))
-                .thenReturn(false);
+        when(mResources.getBoolean(R.bool.pbap_include_photos_in_vcard)).thenReturn(false);
 
         BluetoothPbapConfig.init(mContext);
         assertThat(BluetoothPbapConfig.includePhotosInVcard()).isFalse();
@@ -106,4 +100,4 @@ public class BluetoothPbapConfigTest {
         BluetoothPbapConfig.init(mContext);
         // Test should not crash
     }
-}
\ No newline at end of file
+}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java
index 8d176da7a52..473c4fcd43c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java
@@ -89,31 +89,33 @@ public class BluetoothPbapObexServerTest {
     @Mock Handler mMockHandler;
     @Mock PbapStateMachine mMockStateMachine;
 
-    @Spy
-    BluetoothMethodProxy mPbapMethodProxy = BluetoothMethodProxy.getInstance();
+    @Spy BluetoothMethodProxy mPbapMethodProxy = BluetoothMethodProxy.getInstance();
 
     BluetoothPbapObexServer mServer;
 
-    private static final byte[] WRONG_UUID = new byte[] {
-            0x00, 0x00, 0x00, 0x00, 0x00,
-            0x00, 0x00, 0x00, 0x00, 0x00,
-            0x00, 0x00, 0x00, 0x00, 0x00,
-            0x00,
-    };
+    private static final byte[] WRONG_UUID =
+            new byte[] {
+                0x00, 0x00, 0x00, 0x00, 0x00,
+                0x00, 0x00, 0x00, 0x00, 0x00,
+                0x00, 0x00, 0x00, 0x00, 0x00,
+                0x00,
+            };
 
-    private static final byte[] WRONG_LENGTH_UUID = new byte[] {
-            0x79,
-            0x61,
-            0x35,
-    };
+    private static final byte[] WRONG_LENGTH_UUID =
+            new byte[] {
+                0x79, 0x61, 0x35,
+            };
 
     private static final String ILLEGAL_PATH = "some/random/path";
 
     @Before
     public void setUp() throws Exception {
         BluetoothMethodProxy.setInstanceForTesting(mPbapMethodProxy);
-        mServer = new BluetoothPbapObexServer(
-                mMockHandler, InstrumentationRegistry.getTargetContext(), mMockStateMachine);
+        mServer =
+                new BluetoothPbapObexServer(
+                        mMockHandler,
+                        InstrumentationRegistry.getTargetContext(),
+                        mMockStateMachine);
     }
 
     @After
@@ -122,8 +124,7 @@ public class BluetoothPbapObexServerTest {
     }
 
     @Test
-    public void testOnConnect_whenIoExceptionIsThrownFromGettingTargetHeader()
-            throws Exception {
+    public void testOnConnect_whenIoExceptionIsThrownFromGettingTargetHeader() throws Exception {
         HeaderSet request = new HeaderSet();
         HeaderSet reply = new HeaderSet();
 
@@ -164,8 +165,7 @@ public class BluetoothPbapObexServerTest {
     }
 
     @Test
-    public void testOnConnect_whenIoExceptionIsThrownFromGettingWhoHeader()
-            throws Exception {
+    public void testOnConnect_whenIoExceptionIsThrownFromGettingWhoHeader() throws Exception {
         HeaderSet request = new HeaderSet();
         request.setHeader(HeaderSet.TARGET, BluetoothPbapObexServer.PBAP_TARGET);
         HeaderSet reply = new HeaderSet();
@@ -183,7 +183,8 @@ public class BluetoothPbapObexServerTest {
         request.setHeader(HeaderSet.TARGET, BluetoothPbapObexServer.PBAP_TARGET);
         HeaderSet reply = new HeaderSet();
 
-        doThrow(IOException.class).when(mPbapMethodProxy)
+        doThrow(IOException.class)
+                .when(mPbapMethodProxy)
                 .getHeader(request, HeaderSet.APPLICATION_PARAMETER);
 
         assertThat(mServer.onConnect(request, reply))
@@ -252,7 +253,7 @@ public class BluetoothPbapObexServerTest {
     }
 
     @Test
-    public void testCloseStream_success() throws Exception{
+    public void testCloseStream_success() throws Exception {
         OutputStream outputStream = mock(OutputStream.class);
         Operation operation = mock(Operation.class);
 
@@ -290,7 +291,7 @@ public class BluetoothPbapObexServerTest {
     }
 
     @Test
-    public void testLogHeader() throws Exception{
+    public void testLogHeader() throws Exception {
         HeaderSet headerSet = new HeaderSet();
         try {
             BluetoothPbapObexServer.logHeader(headerSet);
@@ -300,15 +301,13 @@ public class BluetoothPbapObexServerTest {
     }
 
     @Test
-    public void testOnSetPath_whenIoExceptionIsThrownFromGettingNameHeader()
-            throws Exception {
+    public void testOnSetPath_whenIoExceptionIsThrownFromGettingNameHeader() throws Exception {
         HeaderSet request = new HeaderSet();
         HeaderSet reply = new HeaderSet();
         boolean backup = true;
         boolean create = true;
 
-        doThrow(IOException.class).when(mPbapMethodProxy)
-                .getHeader(request, HeaderSet.NAME);
+        doThrow(IOException.class).when(mPbapMethodProxy).getHeader(request, HeaderSet.NAME);
 
         assertThat(mServer.onSetPath(request, reply, backup, create))
                 .isEqualTo(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR);
@@ -361,7 +360,8 @@ public class BluetoothPbapObexServerTest {
         HeaderSet headerSet = new HeaderSet();
         when(operation.getReceivedHeader()).thenReturn(headerSet);
 
-        doThrow(IOException.class).when(mPbapMethodProxy)
+        doThrow(IOException.class)
+                .when(mPbapMethodProxy)
                 .getHeader(headerSet, HeaderSet.APPLICATION_PARAMETER);
 
         assertThat(mServer.onGet(operation)).isEqualTo(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR);
@@ -626,8 +626,12 @@ public class BluetoothPbapObexServerTest {
         BluetoothPbapObexServer.writeVCardEntry(vcfIndex, nameWithSpecialChars, stringBuilder);
         String result = stringBuilder.toString();
 
-        String expectedResult = "";
+        String expectedResult =
+                "";
         assertThat(result).isEqualTo(expectedResult);
     }
 
@@ -635,8 +639,7 @@ public class BluetoothPbapObexServerTest {
     public void getDatabaseIdentifier() {
         long databaseIdentifierLow = 1;
         BluetoothPbapUtils.sDbIdentifier.set(databaseIdentifierLow);
-        byte[] expected = new byte[] {0, 0, 0, 0, 0, 0, 0, 0,
-                0, 0, 0, 0, 0, 0, 0, 1}; // Big-endian
+        byte[] expected = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; // Big-endian
 
         assertThat(mServer.getDatabaseIdentifier()).isEqualTo(expected);
     }
@@ -645,8 +648,7 @@ public class BluetoothPbapObexServerTest {
     public void getPBPrimaryFolderVersion() {
         long primaryVersion = 5;
         BluetoothPbapUtils.sPrimaryVersionCounter = primaryVersion;
-        byte[] expected = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-                0, 0, 0, 5}; // Big-endian
+        byte[] expected = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5}; // Big-endian
 
         assertThat(BluetoothPbapObexServer.getPBPrimaryFolderVersion()).isEqualTo(expected);
     }
@@ -655,8 +657,7 @@ public class BluetoothPbapObexServerTest {
     public void getPBSecondaryFolderVersion() {
         long secondaryVersion = 5;
         BluetoothPbapUtils.sSecondaryVersionCounter = secondaryVersion;
-        byte[] expected = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-                0, 0, 0, 5}; // Big-endian
+        byte[] expected = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5}; // Big-endian
 
         assertThat(BluetoothPbapObexServer.getPBSecondaryFolderVersion()).isEqualTo(expected);
     }
@@ -681,8 +682,11 @@ public class BluetoothPbapObexServerTest {
 
         byte[] result = param.getHeader();
         assertThat(result).isNotNull();
-        int expectedLength = 2 + ApplicationParameter.TRIPLET_LENGTH.PRIMARYVERSIONCOUNTER_LENGTH
-                + 2 + ApplicationParameter.TRIPLET_LENGTH.SECONDARYVERSIONCOUNTER_LENGTH;
+        int expectedLength =
+                2
+                        + ApplicationParameter.TRIPLET_LENGTH.PRIMARYVERSIONCOUNTER_LENGTH
+                        + 2
+                        + ApplicationParameter.TRIPLET_LENGTH.SECONDARYVERSIONCOUNTER_LENGTH;
         assertThat(result.length).isEqualTo(expectedLength);
     }
 
@@ -690,17 +694,50 @@ public class BluetoothPbapObexServerTest {
     public void setCallversionCounters() {
         ApplicationParameter param = new ApplicationParameter();
         AppParamValue value = new AppParamValue();
-        value.callHistoryVersionCounter = new byte[]
-                {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
+        value.callHistoryVersionCounter =
+                new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
 
         BluetoothPbapObexServer.setCallversionCounters(param, value);
 
-        byte[] expectedResult = new byte[] {
-                PRIMARYVERSIONCOUNTER_TAGID, PRIMARYVERSIONCOUNTER_LENGTH,
-                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
-                SECONDARYVERSIONCOUNTER_TAGID, SECONDARYVERSIONCOUNTER_LENGTH,
-                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
-        };
+        byte[] expectedResult =
+                new byte[] {
+                    PRIMARYVERSIONCOUNTER_TAGID,
+                    PRIMARYVERSIONCOUNTER_LENGTH,
+                    1,
+                    2,
+                    3,
+                    4,
+                    5,
+                    6,
+                    7,
+                    8,
+                    9,
+                    10,
+                    11,
+                    12,
+                    13,
+                    14,
+                    15,
+                    16,
+                    SECONDARYVERSIONCOUNTER_TAGID,
+                    SECONDARYVERSIONCOUNTER_LENGTH,
+                    1,
+                    2,
+                    3,
+                    4,
+                    5,
+                    6,
+                    7,
+                    8,
+                    9,
+                    10,
+                    11,
+                    12,
+                    13,
+                    14,
+                    15,
+                    16
+                };
         assertThat(param.getHeader()).isEqualTo(expectedResult);
     }
 
@@ -750,8 +787,19 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withPropertySelectorTagid() {
-        byte[] rawBytes = new byte[] {PROPERTY_SELECTOR_TAGID, PROPERTY_SELECTOR_LENGTH,
-                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; // non-zero value uses filter
+        byte[] rawBytes =
+                new byte[] {
+                    PROPERTY_SELECTOR_TAGID,
+                    PROPERTY_SELECTOR_LENGTH,
+                    0x01,
+                    0x02,
+                    0x03,
+                    0x04,
+                    0x05,
+                    0x06,
+                    0x07,
+                    0x08
+                }; // non-zero value uses filter
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -760,8 +808,10 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withSupportedFeatureTagid() {
-        byte[] rawBytes = new byte[] {SUPPORTEDFEATURE_TAGID, SUPPORTEDFEATURE_LENGTH,
-                0x01, 0x02, 0x03, 0x04};
+        byte[] rawBytes =
+                new byte[] {
+                    SUPPORTEDFEATURE_TAGID, SUPPORTEDFEATURE_LENGTH, 0x01, 0x02, 0x03, 0x04
+                };
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -771,8 +821,7 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withOrderTagid() {
-        byte[] rawBytes = new byte[] {ORDER_TAGID, ORDER_LENGTH,
-                ORDER_BY_ALPHANUMERIC};
+        byte[] rawBytes = new byte[] {ORDER_TAGID, ORDER_LENGTH, ORDER_BY_ALPHANUMERIC};
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -782,8 +831,7 @@ public class BluetoothPbapObexServerTest {
     @Test
     public void parseApplicationParameter_withSearchValueTagid() {
         int searchLength = 4;
-        byte[] rawBytes = new byte[] {SEARCH_VALUE_TAGID, (byte) searchLength,
-                'a', 'b', 'c', 'd' };
+        byte[] rawBytes = new byte[] {SEARCH_VALUE_TAGID, (byte) searchLength, 'a', 'b', 'c', 'd'};
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -792,8 +840,7 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withSearchAttributeTagid() {
-        byte[] rawBytes = new byte[] {SEARCH_ATTRIBUTE_TAGID, SEARCH_ATTRIBUTE_LENGTH,
-                0x05};
+        byte[] rawBytes = new byte[] {SEARCH_ATTRIBUTE_TAGID, SEARCH_ATTRIBUTE_LENGTH, 0x05};
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -802,8 +849,7 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withMaxListCountTagid() {
-        byte[] rawBytes = new byte[] {MAXLISTCOUNT_TAGID, SEARCH_ATTRIBUTE_LENGTH,
-                0x01, 0x02};
+        byte[] rawBytes = new byte[] {MAXLISTCOUNT_TAGID, SEARCH_ATTRIBUTE_LENGTH, 0x01, 0x02};
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -812,8 +858,7 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withListStartOffsetTagid() {
-        byte[] rawBytes = new byte[] {LISTSTARTOFFSET_TAGID, LISTSTARTOFFSET_LENGTH,
-                0x01, 0x02};
+        byte[] rawBytes = new byte[] {LISTSTARTOFFSET_TAGID, LISTSTARTOFFSET_LENGTH, 0x01, 0x02};
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -822,8 +867,7 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withFormatTagid() {
-        byte[] rawBytes = new byte[] {FORMAT_TAGID, FORMAT_LENGTH,
-                0x01};
+        byte[] rawBytes = new byte[] {FORMAT_TAGID, FORMAT_LENGTH, 0x01};
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -832,8 +876,19 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withVCardSelectorTagid() {
-        byte[] rawBytes = new byte[] {VCARDSELECTOR_TAGID, VCARDSELECTOR_LENGTH,
-                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
+        byte[] rawBytes =
+                new byte[] {
+                    VCARDSELECTOR_TAGID,
+                    VCARDSELECTOR_LENGTH,
+                    0x01,
+                    0x02,
+                    0x03,
+                    0x04,
+                    0x05,
+                    0x06,
+                    0x07,
+                    0x08
+                };
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
@@ -843,8 +898,8 @@ public class BluetoothPbapObexServerTest {
 
     @Test
     public void parseApplicationParameter_withVCardSelectorOperatorTagid() {
-        byte[] rawBytes = new byte[] {VCARDSELECTOROPERATOR_TAGID, VCARDSELECTOROPERATOR_LENGTH,
-                0x01};
+        byte[] rawBytes =
+                new byte[] {VCARDSELECTOROPERATOR_TAGID, VCARDSELECTOROPERATOR_LENGTH, 0x01};
         AppParamValue appParamValue = new AppParamValue();
 
         assertThat(mServer.parseApplicationParameter(rawBytes, appParamValue)).isTrue();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java
index 116fe9e7430..ff52feeb8fc 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java
@@ -40,8 +40,7 @@ public class BluetoothPbapServiceBinderTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private BluetoothPbapService mService;
+    @Mock private BluetoothPbapService mService;
 
     BluetoothDevice mRemoteDevice;
 
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
index b509e7e7c4c..013d5dc9200 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
@@ -171,9 +171,11 @@ public class BluetoothPbapServiceTest {
     @Test
     public void broadcastReceiver_onReceive_withActionConnectionAccessReply() {
         Intent intent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY);
-        intent.putExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE,
+        intent.putExtra(
+                BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE,
                 BluetoothDevice.REQUEST_TYPE_PHONEBOOK_ACCESS);
-        intent.putExtra(BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT,
+        intent.putExtra(
+                BluetoothDevice.EXTRA_CONNECTION_ACCESS_RESULT,
                 BluetoothDevice.CONNECTION_ACCESS_YES);
         intent.putExtra(BluetoothDevice.EXTRA_ALWAYS_ALLOWED, true);
         intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mRemoteDevice);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java
index 2e46515c565..d9cb6b3e61f 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java
@@ -64,8 +64,7 @@ public class BluetoothPbapSimVcardManagerTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Spy
-    BluetoothMethodProxy mPbapMethodProxy = BluetoothMethodProxy.getInstance();
+    @Spy BluetoothMethodProxy mPbapMethodProxy = BluetoothMethodProxy.getInstance();
 
     Context mContext;
     BluetoothPbapSimVcardManager mManager;
@@ -75,7 +74,7 @@ public class BluetoothPbapSimVcardManagerTest {
     @Before
     public void setUp() {
         BluetoothMethodProxy.setInstanceForTesting(mPbapMethodProxy);
-        mContext =  InstrumentationRegistry.getTargetContext();
+        mContext = InstrumentationRegistry.getTargetContext();
         mManager = new BluetoothPbapSimVcardManager(mContext);
     }
 
@@ -86,19 +85,18 @@ public class BluetoothPbapSimVcardManagerTest {
 
     @Test
     public void testInit_whenUriIsUnsupported() {
-        assertThat(mManager.init(WRONG_URI, null, null, null))
-                .isFalse();
+        assertThat(mManager.init(WRONG_URI, null, null, null)).isFalse();
         assertThat(mManager.getErrorReason())
                 .isEqualTo(BluetoothPbapSimVcardManager.FAILURE_REASON_UNSUPPORTED_URI);
     }
 
     @Test
     public void testInit_whenCursorIsNull() {
-        doReturn(null).when(mPbapMethodProxy)
+        doReturn(null)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
-        assertThat(mManager.init(BluetoothPbapSimVcardManager.SIM_URI, null, null, null))
-                .isFalse();
+        assertThat(mManager.init(BluetoothPbapSimVcardManager.SIM_URI, null, null, null)).isFalse();
         assertThat(mManager.getErrorReason())
                 .isEqualTo(BluetoothPbapSimVcardManager.FAILURE_REASON_FAILED_TO_GET_DATABASE_INFO);
     }
@@ -107,11 +105,11 @@ public class BluetoothPbapSimVcardManagerTest {
     public void testInit_whenCursorHasNoEntry() {
         Cursor cursor = mock(Cursor.class);
         when(cursor.getCount()).thenReturn(0);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
-        assertThat(mManager.init(BluetoothPbapSimVcardManager.SIM_URI, null, null, null))
-                .isFalse();
+        assertThat(mManager.init(BluetoothPbapSimVcardManager.SIM_URI, null, null, null)).isFalse();
         verify(cursor).close();
         assertThat(mManager.getErrorReason())
                 .isEqualTo(BluetoothPbapSimVcardManager.FAILURE_REASON_NO_ENTRY);
@@ -122,11 +120,11 @@ public class BluetoothPbapSimVcardManagerTest {
         Cursor cursor = mock(Cursor.class);
         when(cursor.getCount()).thenReturn(1);
         when(cursor.moveToFirst()).thenReturn(true);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
-        assertThat(mManager.init(BluetoothPbapSimVcardManager.SIM_URI, null, null, null))
-                .isTrue();
+        assertThat(mManager.init(BluetoothPbapSimVcardManager.SIM_URI, null, null, null)).isTrue();
         assertThat(mManager.getErrorReason()).isEqualTo(BluetoothPbapSimVcardManager.NO_ERROR);
     }
 
@@ -185,8 +183,8 @@ public class BluetoothPbapSimVcardManagerTest {
     @Test
     public void testMoveToPosition_beforeInit() {
         try {
-            mManager.moveToPosition(0, /*sortByAlphabet=*/ true);
-            mManager.moveToPosition(0, /*sortByAlphabet=*/ false);
+            mManager.moveToPosition(0, /* sortByAlphabet= */ true);
+            mManager.moveToPosition(0, /* sortByAlphabet= */ false);
         } catch (Exception e) {
             assertWithMessage("This should not throw exception").fail();
         }
@@ -200,23 +198,35 @@ public class BluetoothPbapSimVcardManagerTest {
         // Implement Cursor iteration
         final int size = nameList.size();
         AtomicInteger currentPosition = new AtomicInteger(0);
-        when(cursor.moveToFirst()).then((Answer) i -> {
-            currentPosition.set(0);
-            return true;
-        });
-        when(cursor.isAfterLast()).then((Answer) i -> {
-            return currentPosition.get() >= size;
-        });
-        when(cursor.moveToNext()).then((Answer) i -> {
-            int pos = currentPosition.addAndGet(1);
-            return pos < size;
-        });
-        when(cursor.getString(anyInt())).then((Answer) i -> {
-            return nameList.get(currentPosition.get());
-        });
+        when(cursor.moveToFirst())
+                .then(
+                        (Answer)
+                                i -> {
+                                    currentPosition.set(0);
+                                    return true;
+                                });
+        when(cursor.isAfterLast())
+                .then(
+                        (Answer)
+                                i -> {
+                                    return currentPosition.get() >= size;
+                                });
+        when(cursor.moveToNext())
+                .then(
+                        (Answer)
+                                i -> {
+                                    int pos = currentPosition.addAndGet(1);
+                                    return pos < size;
+                                });
+        when(cursor.getString(anyInt()))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return nameList.get(currentPosition.get());
+                                });
         // Find first one in alphabetical order ("A")
         int position = 0;
-        mManager.moveToPosition(position, /*sortByAlphabet=*/ true);
+        mManager.moveToPosition(position, /* sortByAlphabet= */ true);
 
         assertThat(currentPosition.get()).isEqualTo(2);
     }
@@ -226,7 +236,7 @@ public class BluetoothPbapSimVcardManagerTest {
         Cursor cursor = initManager();
         int position = 3;
 
-        mManager.moveToPosition(position, /*sortByAlphabet=*/ false);
+        mManager.moveToPosition(position, /* sortByAlphabet= */ false);
 
         verify(cursor).moveToPosition(position);
     }
@@ -253,23 +263,35 @@ public class BluetoothPbapSimVcardManagerTest {
             // Implement Cursor iteration
             final int size = nameList.size();
             AtomicInteger currentPosition = new AtomicInteger(0);
-            when(cursor.moveToFirst()).then((Answer) i -> {
-                currentPosition.set(0);
-                return true;
-            });
-            when(cursor.isAfterLast()).then((Answer) i -> {
-                return currentPosition.get() >= size;
-            });
-            when(cursor.moveToNext()).then((Answer) i -> {
-                int pos = currentPosition.addAndGet(1);
-                return pos < size;
-            });
-            when(cursor.getString(anyInt())).then((Answer) i -> {
-                return nameList.get(currentPosition.get());
-            });
-
-            ArrayList result = mManager.getSIMPhonebookNameList(
-                    BluetoothPbapObexServer.ORDER_BY_INDEXED);
+            when(cursor.moveToFirst())
+                    .then(
+                            (Answer)
+                                    i -> {
+                                        currentPosition.set(0);
+                                        return true;
+                                    });
+            when(cursor.isAfterLast())
+                    .then(
+                            (Answer)
+                                    i -> {
+                                        return currentPosition.get() >= size;
+                                    });
+            when(cursor.moveToNext())
+                    .then(
+                            (Answer)
+                                    i -> {
+                                        int pos = currentPosition.addAndGet(1);
+                                        return pos < size;
+                                    });
+            when(cursor.getString(anyInt()))
+                    .then(
+                            (Answer)
+                                    i -> {
+                                        return nameList.get(currentPosition.get());
+                                    });
+
+            ArrayList result =
+                    mManager.getSIMPhonebookNameList(BluetoothPbapObexServer.ORDER_BY_INDEXED);
 
             ArrayList expectedResult = new ArrayList<>();
             expectedResult.add(localPhoneName);
@@ -293,23 +315,35 @@ public class BluetoothPbapSimVcardManagerTest {
             // Implement Cursor iteration
             final int size = nameList.size();
             AtomicInteger currentPosition = new AtomicInteger(0);
-            when(cursor.moveToFirst()).then((Answer) i -> {
-                currentPosition.set(0);
-                return true;
-            });
-            when(cursor.isAfterLast()).then((Answer) i -> {
-                return currentPosition.get() >= size;
-            });
-            when(cursor.moveToNext()).then((Answer) i -> {
-                int pos = currentPosition.addAndGet(1);
-                return pos < size;
-            });
-            when(cursor.getString(anyInt())).then((Answer) i -> {
-                return nameList.get(currentPosition.get());
-            });
-
-            List result = mManager.getSIMPhonebookNameList(
-                    BluetoothPbapObexServer.ORDER_BY_ALPHABETICAL);
+            when(cursor.moveToFirst())
+                    .then(
+                            (Answer)
+                                    i -> {
+                                        currentPosition.set(0);
+                                        return true;
+                                    });
+            when(cursor.isAfterLast())
+                    .then(
+                            (Answer)
+                                    i -> {
+                                        return currentPosition.get() >= size;
+                                    });
+            when(cursor.moveToNext())
+                    .then(
+                            (Answer)
+                                    i -> {
+                                        int pos = currentPosition.addAndGet(1);
+                                        return pos < size;
+                                    });
+            when(cursor.getString(anyInt()))
+                    .then(
+                            (Answer)
+                                    i -> {
+                                        return nameList.get(currentPosition.get());
+                                    });
+
+            List result =
+                    mManager.getSIMPhonebookNameList(BluetoothPbapObexServer.ORDER_BY_ALPHABETICAL);
 
             List expectedResult = new ArrayList<>(nameList);
             Collections.sort(expectedResult, String.CASE_INSENSITIVE_ORDER);
@@ -325,35 +359,45 @@ public class BluetoothPbapSimVcardManagerTest {
     public void testGetSIMContactNamesByNumber() {
         Cursor cursor = initManager();
         List nameList = Arrays.asList("A", "B", "C", "D");
-        List numberList = Arrays.asList(
-                "000123456789",
-                "123456789000",
-                "000111111000",
-                "123456789123");
+        List numberList =
+                Arrays.asList("000123456789", "123456789000", "000111111000", "123456789123");
         final String query = "000";
 
         // Implement Cursor iteration
         final int size = nameList.size();
         AtomicInteger currentPosition = new AtomicInteger(0);
-        when(cursor.moveToFirst()).then((Answer) i -> {
-            currentPosition.set(0);
-            return true;
-        });
-        when(cursor.isAfterLast()).then((Answer) i -> {
-            return currentPosition.get() >= size;
-        });
-        when(cursor.moveToNext()).then((Answer) i -> {
-            int pos = currentPosition.addAndGet(1);
-            return pos < size;
-        });
-        when(cursor.getString(BluetoothPbapSimVcardManager.NAME_COLUMN_INDEX)).then(
-                (Answer) i -> {
-                    return nameList.get(currentPosition.get());
-                });
-        when(cursor.getString(BluetoothPbapSimVcardManager.NUMBER_COLUMN_INDEX)).then(
-                (Answer) i -> {
-                    return numberList.get(currentPosition.get());
-                });
+        when(cursor.moveToFirst())
+                .then(
+                        (Answer)
+                                i -> {
+                                    currentPosition.set(0);
+                                    return true;
+                                });
+        when(cursor.isAfterLast())
+                .then(
+                        (Answer)
+                                i -> {
+                                    return currentPosition.get() >= size;
+                                });
+        when(cursor.moveToNext())
+                .then(
+                        (Answer)
+                                i -> {
+                                    int pos = currentPosition.addAndGet(1);
+                                    return pos < size;
+                                });
+        when(cursor.getString(BluetoothPbapSimVcardManager.NAME_COLUMN_INDEX))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return nameList.get(currentPosition.get());
+                                });
+        when(cursor.getString(BluetoothPbapSimVcardManager.NUMBER_COLUMN_INDEX))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return numberList.get(currentPosition.get());
+                                });
 
         // Find the names whose number ends with 'query', and then
         // also the names whose number starts with 'query'.
@@ -367,8 +411,14 @@ public class BluetoothPbapSimVcardManagerTest {
         Operation operation = mock(Operation.class);
         final int incorrectStartPoint = 0; // Should be greater than zero
 
-        int result = BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookVcards(mContext,
-                operation, incorrectStartPoint, 0, /*vcardType21=*/false, /*ownerVCard=*/null);
+        int result =
+                BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookVcards(
+                        mContext,
+                        operation,
+                        incorrectStartPoint,
+                        0,
+                        /* vcardType21= */ false,
+                        /* ownerVCard= */ null);
         assertThat(result).isEqualTo(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR);
     }
 
@@ -378,8 +428,14 @@ public class BluetoothPbapSimVcardManagerTest {
         final int startPoint = 1;
         final int endPoint = 0; // Should be equal or greater than startPoint
 
-        int result = BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookVcards(mContext,
-                operation, startPoint, endPoint, /*vcardType21=*/false, /*ownerVCard=*/null);
+        int result =
+                BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookVcards(
+                        mContext,
+                        operation,
+                        startPoint,
+                        endPoint,
+                        /* vcardType21= */ false,
+                        /* ownerVCard= */ null);
         assertThat(result).isEqualTo(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR);
     }
 
@@ -388,11 +444,18 @@ public class BluetoothPbapSimVcardManagerTest {
         Operation operation = mock(Operation.class);
         final int startPoint = 1;
         final int endPoint = 1;
-        doReturn(null).when(mPbapMethodProxy)
+        doReturn(null)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
-        int result = BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookVcards(mContext,
-                operation, startPoint, endPoint, /*vcardType21=*/false, /*ownerVCard=*/null);
+        int result =
+                BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookVcards(
+                        mContext,
+                        operation,
+                        startPoint,
+                        endPoint,
+                        /* vcardType21= */ false,
+                        /* ownerVCard= */ null);
         assertThat(result).isEqualTo(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR);
     }
 
@@ -402,7 +465,8 @@ public class BluetoothPbapSimVcardManagerTest {
         when(cursor.getCount()).thenReturn(10);
         when(cursor.moveToFirst()).thenReturn(true);
         when(cursor.isAfterLast()).thenReturn(false);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
         Operation operation = mock(Operation.class);
         OutputStream outputStream = mock(OutputStream.class);
@@ -411,8 +475,14 @@ public class BluetoothPbapSimVcardManagerTest {
         final int endPoint = 1;
         final String testOwnerVcard = "owner_v_card";
 
-        int result = BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookVcards(mContext,
-                operation, startPoint, endPoint, /*vcardType21=*/false, testOwnerVcard);
+        int result =
+                BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookVcards(
+                        mContext,
+                        operation,
+                        startPoint,
+                        endPoint,
+                        /* vcardType21= */ false,
+                        testOwnerVcard);
         assertThat(result).isEqualTo(ResponseCodes.OBEX_HTTP_OK);
     }
 
@@ -421,9 +491,14 @@ public class BluetoothPbapSimVcardManagerTest {
         Operation operation = mock(Operation.class);
         final int offset = 0; // Should be greater than zero
 
-        int result = BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookOneVcard(mContext,
-                operation, offset, /*vcardType21=*/false, /*ownerVCard=*/null,
-                BluetoothPbapObexServer.ORDER_BY_INDEXED);
+        int result =
+                BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookOneVcard(
+                        mContext,
+                        operation,
+                        offset,
+                        /* vcardType21= */ false,
+                        /* ownerVCard= */ null,
+                        BluetoothPbapObexServer.ORDER_BY_INDEXED);
         assertThat(result).isEqualTo(ResponseCodes.OBEX_HTTP_INTERNAL_ERROR);
     }
 
@@ -433,7 +508,8 @@ public class BluetoothPbapSimVcardManagerTest {
         when(cursor.getCount()).thenReturn(10);
         when(cursor.moveToFirst()).thenReturn(true);
         when(cursor.isAfterLast()).thenReturn(false);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
         Operation operation = mock(Operation.class);
         OutputStream outputStream = mock(OutputStream.class);
@@ -441,9 +517,14 @@ public class BluetoothPbapSimVcardManagerTest {
         final int offset = 1;
         final String testOwnerVcard = "owner_v_card";
 
-        int result = BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookOneVcard(mContext,
-                operation, offset, /*vcardType21=*/false, testOwnerVcard,
-                BluetoothPbapObexServer.ORDER_BY_INDEXED);
+        int result =
+                BluetoothPbapSimVcardManager.composeAndSendSIMPhonebookOneVcard(
+                        mContext,
+                        operation,
+                        offset,
+                        /* vcardType21= */ false,
+                        testOwnerVcard,
+                        BluetoothPbapObexServer.ORDER_BY_INDEXED);
         assertThat(result).isEqualTo(ResponseCodes.OBEX_HTTP_OK);
     }
 
@@ -452,7 +533,8 @@ public class BluetoothPbapSimVcardManagerTest {
         when(cursor.getCount()).thenReturn(10);
         when(cursor.moveToFirst()).thenReturn(true);
         when(cursor.isAfterLast()).thenReturn(false);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
         mManager.init(BluetoothPbapSimVcardManager.SIM_URI, null, null, null);
 
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapUtilsTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapUtilsTest.java
index a98d782fdd5..bfae8a91650 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapUtilsTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapUtilsTest.java
@@ -66,14 +66,11 @@ public class BluetoothPbapUtilsTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    Context mContext;
+    @Mock Context mContext;
 
-    @Mock
-    Resources mResources;
+    @Mock Resources mResources;
 
-    @Spy
-    BluetoothMethodProxy mProxy;
+    @Spy BluetoothMethodProxy mProxy;
 
     @Before
     public void setUp() throws Exception {
@@ -131,8 +128,17 @@ public class BluetoothPbapUtilsTest {
 
     @Test
     public void createFilteredVCardComposer_returnsNewVCardComposer() {
-        byte[] filter = new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
-                (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
+        byte[] filter =
+                new byte[] {
+                    (byte) 0xFF,
+                    (byte) 0xFF,
+                    (byte) 0xFF,
+                    (byte) 0xFF,
+                    (byte) 0xFF,
+                    (byte) 0xFF,
+                    (byte) 0xFF,
+                    (byte) 0xFF
+                };
         int vcardType = VCardConfig.VCARD_TYPE_V21_GENERIC;
 
         assertThat(BluetoothPbapUtils.createFilteredVCardComposer(mContext, vcardType, filter))
@@ -154,29 +160,27 @@ public class BluetoothPbapUtilsTest {
     public void setContactFields() {
         String contactId = "1358923";
 
-        BluetoothPbapUtils.setContactFields(BluetoothPbapUtils.TYPE_NAME, contactId,
-                "test_name");
-        BluetoothPbapUtils.setContactFields(BluetoothPbapUtils.TYPE_PHONE, contactId,
-                "0123456789");
-        BluetoothPbapUtils.setContactFields(BluetoothPbapUtils.TYPE_EMAIL, contactId,
-                "android@android.com");
-        BluetoothPbapUtils.setContactFields(BluetoothPbapUtils.TYPE_ADDRESS, contactId,
-                "SomeAddress");
+        BluetoothPbapUtils.setContactFields(BluetoothPbapUtils.TYPE_NAME, contactId, "test_name");
+        BluetoothPbapUtils.setContactFields(BluetoothPbapUtils.TYPE_PHONE, contactId, "0123456789");
+        BluetoothPbapUtils.setContactFields(
+                BluetoothPbapUtils.TYPE_EMAIL, contactId, "android@android.com");
+        BluetoothPbapUtils.setContactFields(
+                BluetoothPbapUtils.TYPE_ADDRESS, contactId, "SomeAddress");
 
         assertThat(BluetoothPbapUtils.sContactDataset.get(contactId)).isNotNull();
     }
 
     @Test
     public void fetchAndSetContacts_whenCursorIsNull_returnsMinusOne() {
-        doReturn(null).when(mProxy).contentResolverQuery(
-                any(), any(), any(), any(), any(), any());
+        doReturn(null).when(mProxy).contentResolverQuery(any(), any(), any(), any(), any(), any());
         HandlerThread handlerThread = new HandlerThread("BluetoothPbapUtilsTest");
         handlerThread.start();
         Handler handler = new Handler(handlerThread.getLooper());
 
         try {
-            assertThat(BluetoothPbapUtils.fetchAndSetContacts(
-                    mContext, handler, null, null, null, true))
+            assertThat(
+                            BluetoothPbapUtils.fetchAndSetContacts(
+                                    mContext, handler, null, null, null, true))
                     .isEqualTo(-1);
         } finally {
             handlerThread.quit();
@@ -192,16 +196,18 @@ public class BluetoothPbapUtilsTest {
         cursor.addRow(new Object[] {"id2", StructuredName.CONTENT_ITEM_TYPE, "And Roid"});
         cursor.addRow(new Object[] {null, null, null});
 
-        doReturn(cursor).when(mProxy).contentResolverQuery(
-                any(), any(), any(), any(), any(), any());
+        doReturn(cursor)
+                .when(mProxy)
+                .contentResolverQuery(any(), any(), any(), any(), any(), any());
         HandlerThread handlerThread = new HandlerThread("BluetoothPbapUtilsTest");
         handlerThread.start();
         Handler handler = new Handler(handlerThread.getLooper());
 
         try {
             boolean isLoad = true;
-            assertThat(BluetoothPbapUtils.fetchAndSetContacts(
-                    mContext, handler, null, null, null, isLoad))
+            assertThat(
+                            BluetoothPbapUtils.fetchAndSetContacts(
+                                    mContext, handler, null, null, null, isLoad))
                     .isEqualTo(2); // Two IDs exist in sContactSet.
         } finally {
             handlerThread.quit();
@@ -217,16 +223,18 @@ public class BluetoothPbapUtilsTest {
         cursor.addRow(new Object[] {"id2", StructuredName.CONTENT_ITEM_TYPE, "And Roid"});
         cursor.addRow(new Object[] {null, null, null});
 
-        doReturn(cursor).when(mProxy).contentResolverQuery(
-                any(), any(), any(), any(), any(), any());
+        doReturn(cursor)
+                .when(mProxy)
+                .contentResolverQuery(any(), any(), any(), any(), any(), any());
         HandlerThread handlerThread = new HandlerThread("BluetoothPbapUtilsTest");
         handlerThread.start();
         Handler handler = new Handler(handlerThread.getLooper());
 
         try {
             boolean isLoad = false;
-            assertThat(BluetoothPbapUtils.fetchAndSetContacts(
-                    mContext, handler, null, null, null, isLoad))
+            assertThat(
+                            BluetoothPbapUtils.fetchAndSetContacts(
+                                    mContext, handler, null, null, null, isLoad))
                     .isEqualTo(2); // Two IDs exist in sContactSet.
             assertThat(BluetoothPbapUtils.sTotalFields).isEqualTo(1);
             assertThat(BluetoothPbapUtils.sTotalSvcFields).isEqualTo(1);
@@ -237,8 +245,7 @@ public class BluetoothPbapUtilsTest {
 
     @Test
     public void updateSecondaryVersionCounter_whenCursorIsNull_shouldNotCrash() {
-        doReturn(null).when(mProxy).contentResolverQuery(
-                any(), any(), any(), any(), any(), any());
+        doReturn(null).when(mProxy).contentResolverQuery(any(), any(), any(), any(), any(), any());
         HandlerThread handlerThread = new HandlerThread("BluetoothPbapUtilsTest");
         handlerThread.start();
         Handler handler = new Handler(handlerThread.getLooper());
@@ -254,22 +261,25 @@ public class BluetoothPbapUtilsTest {
 
     @Test
     public void updateSecondaryVersionCounter_whenContactsAreAdded() {
-        MatrixCursor contactCursor = new MatrixCursor(
-                new String[] {Contacts._ID, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP});
+        MatrixCursor contactCursor =
+                new MatrixCursor(
+                        new String[] {Contacts._ID, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP});
         contactCursor.addRow(new Object[] {"id1", Calendar.getInstance().getTimeInMillis()});
         contactCursor.addRow(new Object[] {"id2", Calendar.getInstance().getTimeInMillis()});
         contactCursor.addRow(new Object[] {"id3", Calendar.getInstance().getTimeInMillis()});
         contactCursor.addRow(new Object[] {"id4", Calendar.getInstance().getTimeInMillis()});
-        doReturn(contactCursor).when(mProxy).contentResolverQuery(
-                any(), eq(Contacts.CONTENT_URI), any(), any(), any(), any());
+        doReturn(contactCursor)
+                .when(mProxy)
+                .contentResolverQuery(any(), eq(Contacts.CONTENT_URI), any(), any(), any(), any());
 
         MatrixCursor dataCursor = new MatrixCursor(new String[] {CONTACT_ID, MIMETYPE, DATA1});
         dataCursor.addRow(new Object[] {"id1", Phone.CONTENT_ITEM_TYPE, "01234567"});
         dataCursor.addRow(new Object[] {"id1", Email.CONTENT_ITEM_TYPE, "android@android.com"});
         dataCursor.addRow(new Object[] {"id1", StructuredPostal.CONTENT_ITEM_TYPE, "01234"});
         dataCursor.addRow(new Object[] {"id2", StructuredName.CONTENT_ITEM_TYPE, "And Roid"});
-        doReturn(dataCursor).when(mProxy).contentResolverQuery(
-                any(), eq(Data.CONTENT_URI), any(), any(), any(), any());
+        doReturn(dataCursor)
+                .when(mProxy)
+                .contentResolverQuery(any(), eq(Data.CONTENT_URI), any(), any(), any(), any());
 
         HandlerThread handlerThread = new HandlerThread("BluetoothPbapUtilsTest");
         handlerThread.start();
@@ -286,14 +296,17 @@ public class BluetoothPbapUtilsTest {
 
     @Test
     public void updateSecondaryVersionCounter_whenContactsAreDeleted() {
-        MatrixCursor contactCursor = new MatrixCursor(
-                new String[] {Contacts._ID, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP});
-        doReturn(contactCursor).when(mProxy).contentResolverQuery(
-                any(), eq(Contacts.CONTENT_URI), any(), any(), any(), any());
+        MatrixCursor contactCursor =
+                new MatrixCursor(
+                        new String[] {Contacts._ID, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP});
+        doReturn(contactCursor)
+                .when(mProxy)
+                .contentResolverQuery(any(), eq(Contacts.CONTENT_URI), any(), any(), any(), any());
 
         MatrixCursor dataCursor = new MatrixCursor(new String[] {CONTACT_ID, MIMETYPE, DATA1});
-        doReturn(dataCursor).when(mProxy).contentResolverQuery(
-                any(), eq(Data.CONTENT_URI), any(), any(), any(), any());
+        doReturn(dataCursor)
+                .when(mProxy)
+                .contentResolverQuery(any(), eq(Data.CONTENT_URI), any(), any(), any(), any());
 
         HandlerThread handlerThread = new HandlerThread("BluetoothPbapUtilsTest");
         handlerThread.start();
@@ -314,24 +327,27 @@ public class BluetoothPbapUtilsTest {
 
     @Test
     public void updateSecondaryVersionCounter_whenContactsAreUpdated() {
-        MatrixCursor contactCursor = new MatrixCursor(
-                new String[] {Contacts._ID, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP});
+        MatrixCursor contactCursor =
+                new MatrixCursor(
+                        new String[] {Contacts._ID, Contacts.CONTACT_LAST_UPDATED_TIMESTAMP});
         contactCursor.addRow(new Object[] {"id1", Calendar.getInstance().getTimeInMillis()});
-        doReturn(contactCursor).when(mProxy).contentResolverQuery(
-                any(), eq(Contacts.CONTENT_URI), any(), any(), any(), any());
+        doReturn(contactCursor)
+                .when(mProxy)
+                .contentResolverQuery(any(), eq(Contacts.CONTENT_URI), any(), any(), any(), any());
 
         MatrixCursor dataCursor = new MatrixCursor(new String[] {CONTACT_ID, MIMETYPE, DATA1});
         dataCursor.addRow(new Object[] {"id1", Phone.CONTENT_ITEM_TYPE, "01234567"});
         dataCursor.addRow(new Object[] {"id1", Email.CONTENT_ITEM_TYPE, "android@android.com"});
         dataCursor.addRow(new Object[] {"id1", StructuredPostal.CONTENT_ITEM_TYPE, "01234"});
         dataCursor.addRow(new Object[] {"id1", StructuredName.CONTENT_ITEM_TYPE, "And Roid"});
-        doReturn(dataCursor).when(mProxy).contentResolverQuery(
-                any(), eq(Data.CONTENT_URI), any(), any(), any(), any());
+        doReturn(dataCursor)
+                .when(mProxy)
+                .contentResolverQuery(any(), eq(Data.CONTENT_URI), any(), any(), any(), any());
         assertThat(BluetoothPbapUtils.sSecondaryVersionCounter).isEqualTo(0);
 
         BluetoothPbapUtils.sTotalContacts = 1;
-        BluetoothPbapUtils.setContactFields(BluetoothPbapUtils.TYPE_NAME, "id1",
-                "test_previous_name_before_update");
+        BluetoothPbapUtils.setContactFields(
+                BluetoothPbapUtils.TYPE_NAME, "id1", "test_previous_name_before_update");
 
         BluetoothPbapUtils.updateSecondaryVersionCounter(mContext, null);
 
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java
index 9fab5c1d8fb..424ad9ebc5b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java
@@ -49,11 +49,9 @@ public class BluetoothPbapVcardManagerNestedClassesTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    Context mContext;
+    @Mock Context mContext;
 
-    @Mock
-    Resources mResources;
+    @Mock Resources mResources;
 
     @Before
     public void setUp() throws Exception {
@@ -79,34 +77,44 @@ public class BluetoothPbapVcardManagerNestedClassesTest {
 
     @Test
     public void VCardFilter_apply_whenFilterIsNull_returnsSameVcard() {
-        VCardFilter vCardFilter = new VCardFilter(/*filter=*/null);
+        VCardFilter vCardFilter = new VCardFilter(/* filter= */ null);
 
         String vCard = "FN:Full Name";
-        assertThat(vCardFilter.apply(vCard, /*vCardType21=*/ true)).isEqualTo(vCard);
+        assertThat(vCardFilter.apply(vCard, /* vCardType21= */ true)).isEqualTo(vCard);
     }
 
     @Test
     public void VCardFilter_apply_returnsSameVcard() {
         final String separator = System.getProperty("line.separator");
-        String vCard = "FN:Test Full Name" + separator
-                + "EMAIL:android@android.com:" + separator
-                + "X-IRMC-CALL-DATETIME:20170314T173942" + separator;
+        String vCard =
+                "FN:Test Full Name"
+                        + separator
+                        + "EMAIL:android@android.com:"
+                        + separator
+                        + "X-IRMC-CALL-DATETIME:20170314T173942"
+                        + separator;
 
         byte[] emailExcludeFilter = new byte[] {(byte) 0xFE, (byte) 0xFF};
-        VCardFilter vCardFilter = new VCardFilter(/*filter=*/ emailExcludeFilter);
-        String expectedVCard = "FN:Test Full Name" + separator
-                + "X-IRMC-CALL-DATETIME:20170314T173942" + separator;
-
-        assertThat(vCardFilter.apply(vCard, /*vCardType21=*/ true))
-                .isEqualTo(expectedVCard);
+        VCardFilter vCardFilter = new VCardFilter(/* filter= */ emailExcludeFilter);
+        String expectedVCard =
+                "FN:Test Full Name"
+                        + separator
+                        + "X-IRMC-CALL-DATETIME:20170314T173942"
+                        + separator;
+
+        assertThat(vCardFilter.apply(vCard, /* vCardType21= */ true)).isEqualTo(expectedVCard);
     }
 
     @Test
     public void PropertySelector_checkVCardSelector_atLeastOnePropertyExists_returnsTrue() {
         final String separator = System.getProperty("line.separator");
-        String vCard = "FN:Test Full Name" + separator
-                + "EMAIL:android@android.com:" + separator
-                + "TEL:0123456789" + separator;
+        String vCard =
+                "FN:Test Full Name"
+                        + separator
+                        + "EMAIL:android@android.com:"
+                        + separator
+                        + "TEL:0123456789"
+                        + separator;
 
         byte[] emailSelector = new byte[] {0x01, 0x00};
         PropertySelector selector = new PropertySelector(emailSelector);
@@ -117,9 +125,13 @@ public class BluetoothPbapVcardManagerNestedClassesTest {
     @Test
     public void PropertySelector_checkVCardSelector_atLeastOnePropertyExists_returnsFalse() {
         final String separator = System.getProperty("line.separator");
-        String vCard = "FN:Test Full Name" + separator
-                + "EMAIL:android@android.com:" + separator
-                + "TEL:0123456789" + separator;
+        String vCard =
+                "FN:Test Full Name"
+                        + separator
+                        + "EMAIL:android@android.com:"
+                        + separator
+                        + "TEL:0123456789"
+                        + separator;
 
         byte[] organizationSelector = new byte[] {0x01, 0x00, 0x00};
         PropertySelector selector = new PropertySelector(organizationSelector);
@@ -130,9 +142,13 @@ public class BluetoothPbapVcardManagerNestedClassesTest {
     @Test
     public void PropertySelector_checkVCardSelector_allPropertiesExist_returnsTrue() {
         final String separator = System.getProperty("line.separator");
-        String vCard = "FN:Test Full Name" + separator
-                + "EMAIL:android@android.com:" + separator
-                + "TEL:0123456789" + separator;
+        String vCard =
+                "FN:Test Full Name"
+                        + separator
+                        + "EMAIL:android@android.com:"
+                        + separator
+                        + "TEL:0123456789"
+                        + separator;
 
         byte[] fullNameAndEmailSelector = new byte[] {0x01, 0x02};
         PropertySelector selector = new PropertySelector(fullNameAndEmailSelector);
@@ -143,9 +159,13 @@ public class BluetoothPbapVcardManagerNestedClassesTest {
     @Test
     public void PropertySelector_checkVCardSelector_allPropertiesExist_returnsFalse() {
         final String separator = System.getProperty("line.separator");
-        String vCard = "FN:Test Full Name" + separator
-                + "EMAIL:android@android.com:" + separator
-                + "TEL:0123456789" + separator;
+        String vCard =
+                "FN:Test Full Name"
+                        + separator
+                        + "EMAIL:android@android.com:"
+                        + separator
+                        + "TEL:0123456789"
+                        + separator;
 
         byte[] fullNameAndOrganizationSelector = new byte[] {0x01, 0x00, 0x02};
         PropertySelector selector = new PropertySelector(fullNameAndOrganizationSelector);
@@ -162,13 +182,15 @@ public class BluetoothPbapVcardManagerNestedClassesTest {
 
         long[] contactIds = new long[] {1001, 1001, 1002, 1002, 1003, 1003, 1004};
         AtomicInteger currentPos = new AtomicInteger(-1);
-        when(contactCursor.moveToNext()).thenAnswer(invocation -> {
-            if (currentPos.get() < contactIds.length - 1) {
-                currentPos.incrementAndGet();
-                return true;
-            }
-            return false;
-        });
+        when(contactCursor.moveToNext())
+                .thenAnswer(
+                        invocation -> {
+                            if (currentPos.get() < contactIds.length - 1) {
+                                currentPos.incrementAndGet();
+                                return true;
+                            }
+                            return false;
+                        });
         when(contactCursor.getLong(contactIdColumn))
                 .thenAnswer(invocation -> contactIds[currentPos.get()]);
 
@@ -189,20 +211,22 @@ public class BluetoothPbapVcardManagerNestedClassesTest {
 
         long[] contactIds = new long[] {1001, 1001, 1002, 1002, 1003, 1003, 1004};
         AtomicInteger currentPos = new AtomicInteger(-1);
-        when(contactCursor.moveToNext()).thenAnswer(invocation -> {
-            if (currentPos.get() < contactIds.length - 1) {
-                currentPos.incrementAndGet();
-                return true;
-            }
-            return false;
-        });
+        when(contactCursor.moveToNext())
+                .thenAnswer(
+                        invocation -> {
+                            if (currentPos.get() < contactIds.length - 1) {
+                                currentPos.incrementAndGet();
+                                return true;
+                            }
+                            return false;
+                        });
         when(contactCursor.getLong(contactIdColumn))
                 .thenAnswer(invocation -> contactIds[currentPos.get()]);
 
         int startPoint = 2;
         int endPoint = 4;
-        Cursor resultCursor = ContactCursorFilter.filterByRange(
-                contactCursor, startPoint, endPoint);
+        Cursor resultCursor =
+                ContactCursorFilter.filterByRange(contactCursor, startPoint, endPoint);
 
         // Should return cursor containing [1002, 1003, 1004]
         assertThat(resultCursor.getCount()).isEqualTo(3);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerTest.java
index 3c623679f5f..a0e5268282b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerTest.java
@@ -59,8 +59,7 @@ public class BluetoothPbapVcardManagerTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Spy
-    BluetoothMethodProxy mPbapMethodProxy = BluetoothMethodProxy.getInstance();
+    @Spy BluetoothMethodProxy mPbapMethodProxy = BluetoothMethodProxy.getInstance();
 
     Context mContext;
     BluetoothPbapVcardManager mManager;
@@ -81,7 +80,7 @@ public class BluetoothPbapVcardManagerTest {
     public void testGetOwnerPhoneNumberVcard_whenUseProfileForOwnerVcard() {
         BluetoothPbapConfig.setIncludePhotosInVcard(true);
 
-        assertThat(mManager.getOwnerPhoneNumberVcard(/*vcardType21=*/true, /*filter=*/null))
+        assertThat(mManager.getOwnerPhoneNumberVcard(/* vcardType21= */ true, /* filter= */ null))
                 .isNotNull();
     }
 
@@ -89,14 +88,15 @@ public class BluetoothPbapVcardManagerTest {
     public void testGetOwnerPhoneNumberVcard_whenNotUseProfileForOwnerVcard() {
         BluetoothPbapConfig.setIncludePhotosInVcard(false);
 
-        assertThat(mManager.getOwnerPhoneNumberVcard(/*vcardType21=*/true, /*filter=*/null))
+        assertThat(mManager.getOwnerPhoneNumberVcard(/* vcardType21= */ true, /* filter= */ null))
                 .isNotNull();
     }
 
     @Test
     public void testGetPhonebookSize_whenTypeIsPhonebook() {
         Cursor cursor = mock(Cursor.class);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
         // 5 distinct contact IDs.
@@ -105,18 +105,28 @@ public class BluetoothPbapVcardManagerTest {
         // Implement Cursor iteration
         final int size = contactIdsWithDuplicates.size();
         AtomicInteger currentPosition = new AtomicInteger(0);
-        when(cursor.moveToPosition(anyInt())).then((Answer) i -> {
-            int position = i.getArgument(0);
-            currentPosition.set(position);
-            return true;
-        });
-        when(cursor.moveToNext()).then((Answer) i -> {
-            int pos = currentPosition.addAndGet(1);
-            return pos < size;
-        });
-        when(cursor.getLong(anyInt())).then((Answer) i -> {
-            return (long) contactIdsWithDuplicates.get(currentPosition.get());
-        });
+        when(cursor.moveToPosition(anyInt()))
+                .then(
+                        (Answer)
+                                i -> {
+                                    int position = i.getArgument(0);
+                                    currentPosition.set(position);
+                                    return true;
+                                });
+        when(cursor.moveToNext())
+                .then(
+                        (Answer)
+                                i -> {
+                                    int pos = currentPosition.addAndGet(1);
+                                    return pos < size;
+                                });
+        when(cursor.getLong(anyInt()))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return (long)
+                                            contactIdsWithDuplicates.get(currentPosition.get());
+                                });
 
         // 5 distinct contact IDs + self (which is only included for phonebook)
         final int expectedSize = 5 + 1;
@@ -128,30 +138,49 @@ public class BluetoothPbapVcardManagerTest {
     @Test
     public void testGetPhonebookSize_whenTypeIsFavorites() {
         Cursor cursor = mock(Cursor.class);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
         // 5 distinct contact IDs.
-        final List contactIdsWithDuplicates = Arrays.asList(
-                0, 1, 1, 2,     // starred
-                2, 3, 3, 4, 4   // not starred
-        );
+        final List contactIdsWithDuplicates =
+                Arrays.asList(
+                        0,
+                        1,
+                        1,
+                        2, // starred
+                        2,
+                        3,
+                        3,
+                        4,
+                        4 // not starred
+                        );
 
         // Implement Cursor iteration
         final int starredSize = 4;
         AtomicInteger currentPosition = new AtomicInteger(0);
-        when(cursor.moveToPosition(anyInt())).then((Answer) i -> {
-            int position = i.getArgument(0);
-            currentPosition.set(position);
-            return true;
-        });
-        when(cursor.moveToNext()).then((Answer) i -> {
-            int pos = currentPosition.addAndGet(1);
-            return pos < starredSize;
-        });
-        when(cursor.getLong(anyInt())).then((Answer) i -> {
-            return (long) contactIdsWithDuplicates.get(currentPosition.get());
-        });
+        when(cursor.moveToPosition(anyInt()))
+                .then(
+                        (Answer)
+                                i -> {
+                                    int position = i.getArgument(0);
+                                    currentPosition.set(position);
+                                    return true;
+                                });
+        when(cursor.moveToNext())
+                .then(
+                        (Answer)
+                                i -> {
+                                    int pos = currentPosition.addAndGet(1);
+                                    return pos < starredSize;
+                                });
+        when(cursor.getLong(anyInt()))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return (long)
+                                            contactIdsWithDuplicates.get(currentPosition.get());
+                                });
 
         // Among 4 starred contact Ids, there are 3 distinct contact IDs
         final int expectedSize = 3;
@@ -163,14 +192,17 @@ public class BluetoothPbapVcardManagerTest {
     @Test
     public void testGetPhonebookSize_whenTypeIsSimPhonebook() {
         Cursor cursor = mock(Cursor.class);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
         final int expectedSize = 10;
         when(cursor.getCount()).thenReturn(expectedSize);
         BluetoothPbapSimVcardManager simVcardManager = mock(BluetoothPbapSimVcardManager.class);
 
-        assertThat(mManager.getPhonebookSize(BluetoothPbapObexServer.ContentType.SIM_PHONEBOOK,
-                simVcardManager)).isEqualTo(expectedSize);
+        assertThat(
+                        mManager.getPhonebookSize(
+                                BluetoothPbapObexServer.ContentType.SIM_PHONEBOOK, simVcardManager))
+                .isEqualTo(expectedSize);
         verify(simVcardManager).getSIMContactsSize();
     }
 
@@ -179,60 +211,81 @@ public class BluetoothPbapVcardManagerTest {
         final int historySize = 10;
         Cursor cursor = mock(Cursor.class);
         when(cursor.getCount()).thenReturn(historySize);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
-        assertThat(mManager.getPhonebookSize(
-                BluetoothPbapObexServer.ContentType.INCOMING_CALL_HISTORY, null))
+        assertThat(
+                        mManager.getPhonebookSize(
+                                BluetoothPbapObexServer.ContentType.INCOMING_CALL_HISTORY, null))
                 .isEqualTo(historySize);
     }
 
     @Test
     public void testLoadCallHistoryList() {
         Cursor cursor = mock(Cursor.class);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
         List nameList = Arrays.asList("A", "B", "", "");
         List numberList = Arrays.asList("0000", "1111", "2222", "3333");
-        List presentationAllowedList = Arrays.asList(
-                CallLog.Calls.PRESENTATION_ALLOWED,
-                CallLog.Calls.PRESENTATION_ALLOWED,
-                CallLog.Calls.PRESENTATION_ALLOWED,
-                CallLog.Calls.PRESENTATION_UNKNOWN); // The number "3333" should not be shown.
+        List presentationAllowedList =
+                Arrays.asList(
+                        CallLog.Calls.PRESENTATION_ALLOWED,
+                        CallLog.Calls.PRESENTATION_ALLOWED,
+                        CallLog.Calls.PRESENTATION_ALLOWED,
+                        CallLog.Calls
+                                .PRESENTATION_UNKNOWN); // The number "3333" should not be shown.
 
-        List expectedResult = Arrays.asList(
-                "A", "B", "2222", mContext.getString(R.string.unknownNumber));
+        List expectedResult =
+                Arrays.asList("A", "B", "2222", mContext.getString(R.string.unknownNumber));
 
         // Implement Cursor iteration
         final int size = nameList.size();
         AtomicInteger currentPosition = new AtomicInteger(0);
-        when(cursor.moveToFirst()).then((Answer) i -> {
-            currentPosition.set(0);
-            return true;
-        });
-        when(cursor.isAfterLast()).then((Answer) i -> {
-            return currentPosition.get() >= size;
-        });
-        when(cursor.moveToNext()).then((Answer) i -> {
-            int pos = currentPosition.addAndGet(1);
-            return pos < size;
-        });
+        when(cursor.moveToFirst())
+                .then(
+                        (Answer)
+                                i -> {
+                                    currentPosition.set(0);
+                                    return true;
+                                });
+        when(cursor.isAfterLast())
+                .then(
+                        (Answer)
+                                i -> {
+                                    return currentPosition.get() >= size;
+                                });
+        when(cursor.moveToNext())
+                .then(
+                        (Answer)
+                                i -> {
+                                    int pos = currentPosition.addAndGet(1);
+                                    return pos < size;
+                                });
         when(cursor.getString(BluetoothPbapVcardManager.CALLS_NAME_COLUMN_INDEX))
-                .then((Answer) i -> {
-            return nameList.get(currentPosition.get());
-        });
+                .then(
+                        (Answer)
+                                i -> {
+                                    return nameList.get(currentPosition.get());
+                                });
         when(cursor.getString(BluetoothPbapVcardManager.CALLS_NUMBER_COLUMN_INDEX))
-                .then((Answer) i -> {
-            return numberList.get(currentPosition.get());
-        });
+                .then(
+                        (Answer)
+                                i -> {
+                                    return numberList.get(currentPosition.get());
+                                });
         when(cursor.getInt(BluetoothPbapVcardManager.CALLS_NUMBER_PRESENTATION_COLUMN_INDEX))
-                .then((Answer) i -> {
-            return presentationAllowedList.get(currentPosition.get());
-        });
-
-        assertThat(mManager.loadCallHistoryList(
-                BluetoothPbapObexServer.ContentType.INCOMING_CALL_HISTORY))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return presentationAllowedList.get(currentPosition.get());
+                                });
+
+        assertThat(
+                        mManager.loadCallHistoryList(
+                                BluetoothPbapObexServer.ContentType.INCOMING_CALL_HISTORY))
                 .isEqualTo(expectedResult);
     }
 
@@ -242,43 +295,57 @@ public class BluetoothPbapVcardManagerTest {
         BluetoothPbapService.setLocalPhoneName(localPhoneName);
 
         Cursor cursor = mock(Cursor.class);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
         List nameList = Arrays.asList("A", "B", "C", "");
         List contactIdList = Arrays.asList(0, 1, 2, 3);
 
-        List expectedResult = Arrays.asList(
-                localPhoneName,
-                "A,0",
-                "B,1",
-                "C,2",
-                mContext.getString(android.R.string.unknownName) + ",3");
+        List expectedResult =
+                Arrays.asList(
+                        localPhoneName,
+                        "A,0",
+                        "B,1",
+                        "C,2",
+                        mContext.getString(android.R.string.unknownName) + ",3");
 
         // Implement Cursor iteration
         final int size = nameList.size();
         AtomicInteger currentPosition = new AtomicInteger(0);
-        when(cursor.moveToPosition(anyInt())).then((Answer) i -> {
-            int position = i.getArgument(0);
-            currentPosition.set(position);
-            return true;
-        });
-        when(cursor.moveToNext()).then((Answer) i -> {
-            int pos = currentPosition.addAndGet(1);
-            return pos < size;
-        });
+        when(cursor.moveToPosition(anyInt()))
+                .then(
+                        (Answer)
+                                i -> {
+                                    int position = i.getArgument(0);
+                                    currentPosition.set(position);
+                                    return true;
+                                });
+        when(cursor.moveToNext())
+                .then(
+                        (Answer)
+                                i -> {
+                                    int pos = currentPosition.addAndGet(1);
+                                    return pos < size;
+                                });
 
         final int contactIdColumn = 0;
         final int nameColumn = 1;
         when(cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID)).thenReturn(contactIdColumn);
         when(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)).thenReturn(nameColumn);
 
-        when(cursor.getLong(contactIdColumn)).then((Answer) i -> {
-            return (long) contactIdList.get(currentPosition.get());
-        });
-        when(cursor.getString(nameColumn)).then((Answer) i -> {
-            return nameList.get(currentPosition.get());
-        });
+        when(cursor.getLong(contactIdColumn))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return (long) contactIdList.get(currentPosition.get());
+                                });
+        when(cursor.getString(nameColumn))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return nameList.get(currentPosition.get());
+                                });
 
         assertThat(mManager.getPhonebookNameList(BluetoothPbapObexServer.ORDER_BY_ALPHABETICAL))
                 .isEqualTo(expectedResult);
@@ -287,45 +354,58 @@ public class BluetoothPbapVcardManagerTest {
     @Test
     public void testGetContactNamesByNumber_whenNumberIsNull() {
         Cursor cursor = mock(Cursor.class);
-        doReturn(cursor).when(mPbapMethodProxy)
+        doReturn(cursor)
+                .when(mPbapMethodProxy)
                 .contentResolverQuery(any(), any(), any(), any(), any(), any());
 
         List nameList = Arrays.asList("A", "B", "C", "");
         List contactIdList = Arrays.asList(0, 1, 2, 3);
 
-        List expectedResult = Arrays.asList(
-                "A,0",
-                "B,1",
-                "C,2",
-                mContext.getString(android.R.string.unknownName) + ",3");
+        List expectedResult =
+                Arrays.asList(
+                        "A,0",
+                        "B,1",
+                        "C,2",
+                        mContext.getString(android.R.string.unknownName) + ",3");
 
         // Implement Cursor iteration
         final int size = nameList.size();
         AtomicInteger currentPosition = new AtomicInteger(0);
-        when(cursor.moveToPosition(anyInt())).then((Answer) i -> {
-            int position = i.getArgument(0);
-            currentPosition.set(position);
-            return true;
-        });
-        when(cursor.moveToNext()).then((Answer) i -> {
-            int pos = currentPosition.addAndGet(1);
-            return pos < size;
-        });
+        when(cursor.moveToPosition(anyInt()))
+                .then(
+                        (Answer)
+                                i -> {
+                                    int position = i.getArgument(0);
+                                    currentPosition.set(position);
+                                    return true;
+                                });
+        when(cursor.moveToNext())
+                .then(
+                        (Answer)
+                                i -> {
+                                    int pos = currentPosition.addAndGet(1);
+                                    return pos < size;
+                                });
 
         final int contactIdColumn = 0;
         final int nameColumn = 1;
         when(cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID)).thenReturn(contactIdColumn);
         when(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)).thenReturn(nameColumn);
 
-        when(cursor.getLong(contactIdColumn)).then((Answer) i -> {
-            return (long) contactIdList.get(currentPosition.get());
-        });
-        when(cursor.getString(nameColumn)).then((Answer) i -> {
-            return nameList.get(currentPosition.get());
-        });
-
-        assertThat(mManager.getContactNamesByNumber(null))
-                .isEqualTo(expectedResult);
+        when(cursor.getLong(contactIdColumn))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return (long) contactIdList.get(currentPosition.get());
+                                });
+        when(cursor.getString(nameColumn))
+                .then(
+                        (Answer)
+                                i -> {
+                                    return nameList.get(currentPosition.get());
+                                });
+
+        assertThat(mManager.getContactNamesByNumber(null)).isEqualTo(expectedResult);
     }
 
     @Test
@@ -340,9 +420,13 @@ public class BluetoothPbapVcardManagerTest {
     @Test
     public void getNameFromVCard() {
         final String separator = System.getProperty("line.separator");
-        String vCard = "N:Test Name" + separator
-                + "FN:Test Full Name" + separator
-                + "EMAIL:android@android.com:" + separator;
+        String vCard =
+                "N:Test Name"
+                        + separator
+                        + "FN:Test Full Name"
+                        + separator
+                        + "EMAIL:android@android.com:"
+                        + separator;
 
         assertThat(BluetoothPbapVcardManager.getNameFromVCard(vCard)).isEqualTo("Test Name");
     }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/HandlerForStringBufferTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/HandlerForStringBufferTest.java
index 6c1e252aabf..9c9ee8967f8 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/HandlerForStringBufferTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/HandlerForStringBufferTest.java
@@ -46,11 +46,9 @@ public class HandlerForStringBufferTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private Operation mOperation;
+    @Mock private Operation mOperation;
 
-    @Mock
-    private OutputStream mOutputStream;
+    @Mock private OutputStream mOutputStream;
 
     @Before
     public void setUp() throws Exception {
@@ -110,7 +108,8 @@ public class HandlerForStringBufferTest {
     @Test
     public void writeVCard_withIOExceptionWhenWritingToStream_returnsFalse() throws Exception {
         doThrow(new IOException()).when(mOutputStream).write(any(byte[].class));
-        HandlerForStringBuffer buffer = new HandlerForStringBuffer(mOperation, /*ownerVcard=*/null);
+        HandlerForStringBuffer buffer =
+                new HandlerForStringBuffer(mOperation, /* ownerVcard= */ null);
         buffer.init();
 
         String newVCard = "newVCard";
@@ -128,4 +127,4 @@ public class HandlerForStringBufferTest {
 
         verify(mOutputStream).close();
     }
-}
\ No newline at end of file
+}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java
index 068cb864595..16cc324c37b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java
@@ -98,60 +98,57 @@ public class PbapStateMachineTest {
         TestUtils.clearAdapterService(mAdapterService);
     }
 
-    /**
-     * Test that initial state is WaitingForAuth
-     */
+    /** Test that initial state is WaitingForAuth */
     @Test
     public void testInitialState() {
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
-                mPbapStateMachine.getConnectionState());
-        Assert.assertThat(mPbapStateMachine.getCurrentState(),
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTING, mPbapStateMachine.getConnectionState());
+        Assert.assertThat(
+                mPbapStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(PbapStateMachine.WaitingForAuth.class));
     }
 
-    /**
-     * Test state transition from WaitingForAuth to Finished when the user rejected
-     */
+    /** Test state transition from WaitingForAuth to Finished when the user rejected */
     @Ignore("Class BluetoothSocket is final and cannot be mocked. b/71512958: re-enable it.")
     @Test
     public void testStateTransition_WaitingForAuthToFinished() throws Exception {
         mPbapStateMachine.sendMessage(PbapStateMachine.REJECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
-                mPbapStateMachine.getConnectionState());
-        Assert.assertThat(mPbapStateMachine.getCurrentState(),
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED, mPbapStateMachine.getConnectionState());
+        Assert.assertThat(
+                mPbapStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(PbapStateMachine.Finished.class));
     }
 
-    /**
-     * Test state transition from WaitingForAuth to Finished when the user rejected
-     */
+    /** Test state transition from WaitingForAuth to Finished when the user rejected */
     @Ignore("Class BluetoothSocket is final and cannot be mocked. b/71512958: re-enable it.")
     @Test
     public void testStateTransition_WaitingForAuthToConnected() throws Exception {
         mPbapStateMachine.sendMessage(PbapStateMachine.AUTHORIZED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mPbapStateMachine.getConnectionState());
-        Assert.assertThat(mPbapStateMachine.getCurrentState(),
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTED, mPbapStateMachine.getConnectionState());
+        Assert.assertThat(
+                mPbapStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(PbapStateMachine.Connected.class));
     }
 
-    /**
-     * Test state transition from Connected to Finished when the OBEX server is done
-     */
+    /** Test state transition from Connected to Finished when the OBEX server is done */
     @Ignore("Class BluetoothSocket is final and cannot be mocked. b/71512958: re-enable it.")
     @Test
     public void testStateTransition_ConnectedToFinished() throws Exception {
         mPbapStateMachine.sendMessage(PbapStateMachine.AUTHORIZED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mPbapStateMachine.getConnectionState());
-        Assert.assertThat(mPbapStateMachine.getCurrentState(),
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTED, mPbapStateMachine.getConnectionState());
+        Assert.assertThat(
+                mPbapStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(PbapStateMachine.Connected.class));
 
         // PBAP OBEX transport is done.
         mPbapStateMachine.sendMessage(PbapStateMachine.DISCONNECT);
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
-                mPbapStateMachine.getConnectionState());
-        Assert.assertThat(mPbapStateMachine.getCurrentState(),
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED, mPbapStateMachine.getConnectionState());
+        Assert.assertThat(
+                mPbapStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(PbapStateMachine.Finished.class));
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/AuthenticationServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/AuthenticationServiceTest.java
index e07a9c8abb5..54645313bb9 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/AuthenticationServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/AuthenticationServiceTest.java
@@ -42,8 +42,7 @@ public class AuthenticationServiceTest {
 
     Context mTargetContext;
 
-    @Rule
-    public final ServiceTestRule mServiceRule = new ServiceTestRule();
+    @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule();
 
     @Before
     public void setUp() {
@@ -65,11 +64,11 @@ public class AuthenticationServiceTest {
     }
 
     private void enableService(boolean enable) {
-        int enabledState = enable ? COMPONENT_ENABLED_STATE_ENABLED
-                : COMPONENT_ENABLED_STATE_DEFAULT;
-        ComponentName serviceName = new ComponentName(
-                mTargetContext, AuthenticationService.class);
-        mTargetContext.getPackageManager().setComponentEnabledSetting(
-                serviceName, enabledState, DONT_KILL_APP);
+        int enabledState =
+                enable ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DEFAULT;
+        ComponentName serviceName = new ComponentName(mTargetContext, AuthenticationService.class);
+        mTargetContext
+                .getPackageManager()
+                .setComponentEnabledSetting(serviceName, enabledState, DONT_KILL_APP);
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/AuthenticatorTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/AuthenticatorTest.java
index dd332ac85b6..8ebce0a69e5 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/AuthenticatorTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/AuthenticatorTest.java
@@ -42,11 +42,9 @@ public class AuthenticatorTest {
     private Context mTargetContext;
     private Authenticator mAuthenticator;
 
-    @Mock
-    AccountAuthenticatorResponse mResponse;
+    @Mock AccountAuthenticatorResponse mResponse;
 
-    @Mock
-    Account mAccount;
+    @Mock Account mAccount;
 
     @Before
     public void setUp() throws Exception {
@@ -56,13 +54,15 @@ public class AuthenticatorTest {
 
     @Test
     public void editProperties_throwsUnsupportedOperationException() {
-        assertThrows(UnsupportedOperationException.class,
+        assertThrows(
+                UnsupportedOperationException.class,
                 () -> mAuthenticator.editProperties(mResponse, null));
     }
 
     @Test
     public void addAccount_throwsUnsupportedOperationException() {
-        assertThrows(UnsupportedOperationException.class,
+        assertThrows(
+                UnsupportedOperationException.class,
                 () -> mAuthenticator.addAccount(mResponse, null, null, null, null));
     }
 
@@ -73,7 +73,8 @@ public class AuthenticatorTest {
 
     @Test
     public void getAuthToken_throwsUnsupportedOperationException() {
-        assertThrows(UnsupportedOperationException.class,
+        assertThrows(
+                UnsupportedOperationException.class,
                 () -> mAuthenticator.getAuthToken(mResponse, mAccount, null, null));
     }
 
@@ -92,4 +93,4 @@ public class AuthenticatorTest {
         Bundle result = mAuthenticator.hasFeatures(mResponse, mAccount, null);
         assertThat(result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)).isFalse();
     }
-}
\ No newline at end of file
+}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapObexAuthenticatorTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapObexAuthenticatorTest.java
index 1fefeaf4ab8..64711da3558 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapObexAuthenticatorTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapObexAuthenticatorTest.java
@@ -41,8 +41,11 @@ public class BluetoothPbapObexAuthenticatorTest {
     @Test
     public void onAuthenticationChallenge() {
         // Note: onAuthenticationChallenge() does not use any arguments
-        PasswordAuthentication passwordAuthentication = mAuthenticator.onAuthenticationChallenge(
-                /*description=*/ null, /*isUserIdRequired=*/ false, /*isFullAccess=*/ false);
+        PasswordAuthentication passwordAuthentication =
+                mAuthenticator.onAuthenticationChallenge(
+                        /* description= */ null,
+                        /* isUserIdRequired= */ false,
+                        /* isFullAccess= */ false);
 
         assertThat(passwordAuthentication.getPassword())
                 .isEqualTo(mAuthenticator.mSessionKey.getBytes());
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookSizeTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookSizeTest.java
index 68be55dbdbf..35209b8b3b9 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookSizeTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookSizeTest.java
@@ -36,7 +36,9 @@ public class BluetoothPbapRequestPullPhoneBookSizeTest {
 
     @Before
     public void setUp() {
-        mRequest = new BluetoothPbapRequestPullPhoneBookSize(/*pbName=*/"phonebook", /*filter=*/1);
+        mRequest =
+                new BluetoothPbapRequestPullPhoneBookSize(
+                        /* pbName= */ "phonebook", /* filter= */ 1);
     }
 
     @Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookTest.java
index 35d14027836..c2ef8ceac32 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookTest.java
@@ -50,9 +50,16 @@ public class BluetoothPbapRequestPullPhoneBookTest {
 
         final int wrongMaxListCount = -1;
 
-        assertThrows(IllegalArgumentException.class, () ->
-                new BluetoothPbapRequestPullPhoneBook(PB_NAME, ACCOUNT, filter, format,
-                        wrongMaxListCount, listStartOffset));
+        assertThrows(
+                IllegalArgumentException.class,
+                () ->
+                        new BluetoothPbapRequestPullPhoneBook(
+                                PB_NAME,
+                                ACCOUNT,
+                                filter,
+                                format,
+                                wrongMaxListCount,
+                                listStartOffset));
     }
 
     @Test
@@ -63,9 +70,16 @@ public class BluetoothPbapRequestPullPhoneBookTest {
 
         final int wrongListStartOffset = -1;
 
-        assertThrows(IllegalArgumentException.class, () ->
-                new BluetoothPbapRequestPullPhoneBook(PB_NAME, ACCOUNT, filter, format,
-                        maxListCount, wrongListStartOffset));
+        assertThrows(
+                IllegalArgumentException.class,
+                () ->
+                        new BluetoothPbapRequestPullPhoneBook(
+                                PB_NAME,
+                                ACCOUNT,
+                                filter,
+                                format,
+                                maxListCount,
+                                wrongListStartOffset));
     }
 
     @Test
@@ -74,25 +88,27 @@ public class BluetoothPbapRequestPullPhoneBookTest {
         final byte format = 0; // Will be properly handled as VCARD_TYPE_21.
         final int maxListCount = 0; // Will be specially handled as 65535.
         final int listStartOffset = 10;
-        BluetoothPbapRequestPullPhoneBook request = new BluetoothPbapRequestPullPhoneBook(
-                PB_NAME, ACCOUNT, filter, format, maxListCount, listStartOffset);
-
-        final InputStream is = new InputStream() {
-            @Override
-            public int read() throws IOException {
-                throw new IOException();
-            }
-
-            @Override
-            public int read(byte[] b) throws IOException {
-                throw new IOException();
-            }
-
-            @Override
-            public int read(byte[] b, int off, int len) throws IOException {
-                throw new IOException();
-            }
-        };
+        BluetoothPbapRequestPullPhoneBook request =
+                new BluetoothPbapRequestPullPhoneBook(
+                        PB_NAME, ACCOUNT, filter, format, maxListCount, listStartOffset);
+
+        final InputStream is =
+                new InputStream() {
+                    @Override
+                    public int read() throws IOException {
+                        throw new IOException();
+                    }
+
+                    @Override
+                    public int read(byte[] b) throws IOException {
+                        throw new IOException();
+                    }
+
+                    @Override
+                    public int read(byte[] b, int off, int len) throws IOException {
+                        throw new IOException();
+                    }
+                };
 
         assertThrows(IOException.class, () -> request.readResponse(is));
     }
@@ -103,8 +119,9 @@ public class BluetoothPbapRequestPullPhoneBookTest {
         final byte format = 0; // Will be properly handled as VCARD_TYPE_21.
         final int maxListCount = 0; // Will be specially handled as 65535.
         final int listStartOffset = 10;
-        BluetoothPbapRequestPullPhoneBook request = new BluetoothPbapRequestPullPhoneBook(
-                PB_NAME, ACCOUNT, filter, format, maxListCount, listStartOffset);
+        BluetoothPbapRequestPullPhoneBook request =
+                new BluetoothPbapRequestPullPhoneBook(
+                        PB_NAME, ACCOUNT, filter, format, maxListCount, listStartOffset);
 
         try {
             HeaderSet headerSet = new HeaderSet();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestTest.java
index b947c62dc2a..8a5a5d515f5 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestTest.java
@@ -47,8 +47,7 @@ public class BluetoothPbapRequestTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private ObexTransport mObexTransport;
+    @Mock private ObexTransport mObexTransport;
 
     @Before
     public void setUp() throws Exception {
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapVcardListTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapVcardListTest.java
index 3dd2e20abf3..38825604004 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapVcardListTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/BluetoothPbapVcardListTest.java
@@ -49,60 +49,75 @@ public class BluetoothPbapVcardListTest {
     @Test
     public void constructor_withInputStreamThatThrowsIoeWhenRead_throwsIOException() {
 
-        final InputStream is = new InputStream() {
-            @Override
-            public int read() throws IOException {
-                throw new IOException();
-            }
-
-            @Override
-            public int read(byte[] b) throws IOException {
-                throw new IOException();
-            }
-
-            @Override
-            public int read(byte[] b, int off, int len) throws IOException {
-                throw new IOException();
-            }
-        };
-
-        assertThrows(IOException.class, () ->
-                new BluetoothPbapVcardList(ACCOUNT, is, PbapClientConnectionHandler.VCARD_TYPE_30));
-        assertThrows(IOException.class, () ->
-                new BluetoothPbapVcardList(ACCOUNT, is, PbapClientConnectionHandler.VCARD_TYPE_21));
+        final InputStream is =
+                new InputStream() {
+                    @Override
+                    public int read() throws IOException {
+                        throw new IOException();
+                    }
+
+                    @Override
+                    public int read(byte[] b) throws IOException {
+                        throw new IOException();
+                    }
+
+                    @Override
+                    public int read(byte[] b, int off, int len) throws IOException {
+                        throw new IOException();
+                    }
+                };
+
+        assertThrows(
+                IOException.class,
+                () ->
+                        new BluetoothPbapVcardList(
+                                ACCOUNT, is, PbapClientConnectionHandler.VCARD_TYPE_30));
+        assertThrows(
+                IOException.class,
+                () ->
+                        new BluetoothPbapVcardList(
+                                ACCOUNT, is, PbapClientConnectionHandler.VCARD_TYPE_21));
     }
 
     @Test
     public void constructor_withInvalidVcardType_throwsIllegalArgumentException() {
-        assertThrows(IllegalArgumentException.class, () ->
-                new BluetoothPbapVcardList(ACCOUNT,
-                new ByteArrayInputStream("Hello world".getBytes()), (byte) -1));
+        assertThrows(
+                IllegalArgumentException.class,
+                () ->
+                        new BluetoothPbapVcardList(
+                                ACCOUNT,
+                                new ByteArrayInputStream("Hello world".getBytes()),
+                                (byte) -1));
     }
 
     @Test
     public void test30ParserWith21Vcard_parsingSucceeds() throws IOException {
-        InputStream fileStream = mTestResources.openRawResource(
-                com.android.bluetooth.tests.R.raw.v21_simple);
-        BluetoothPbapVcardList result = new BluetoothPbapVcardList(ACCOUNT, fileStream,
-                PbapClientConnectionHandler.VCARD_TYPE_30);
+        InputStream fileStream =
+                mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.v21_simple);
+        BluetoothPbapVcardList result =
+                new BluetoothPbapVcardList(
+                        ACCOUNT, fileStream, PbapClientConnectionHandler.VCARD_TYPE_30);
         assertThat(result.getCount()).isEqualTo(1);
     }
 
     @Test
     public void test21ParserWith30Vcard_parsingSucceeds() throws IOException {
-        InputStream fileStream = mTestResources.openRawResource(
-                com.android.bluetooth.tests.R.raw.v30_simple);
-        BluetoothPbapVcardList result = new BluetoothPbapVcardList(ACCOUNT, fileStream,
-                PbapClientConnectionHandler.VCARD_TYPE_21);
+        InputStream fileStream =
+                mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.v30_simple);
+        BluetoothPbapVcardList result =
+                new BluetoothPbapVcardList(
+                        ACCOUNT, fileStream, PbapClientConnectionHandler.VCARD_TYPE_21);
         assertThat(result.getCount()).isEqualTo(1);
     }
 
     @Test
     public void test30ParserWithUnsupportedVcardVersion_parsingFails() throws IOException {
-        InputStream fileStream = mTestResources.openRawResource(
-                com.android.bluetooth.tests.R.raw.unsupported_version);
-        BluetoothPbapVcardList result = new BluetoothPbapVcardList(ACCOUNT, fileStream,
-                PbapClientConnectionHandler.VCARD_TYPE_30);
+        InputStream fileStream =
+                mTestResources.openRawResource(
+                        com.android.bluetooth.tests.R.raw.unsupported_version);
+        BluetoothPbapVcardList result =
+                new BluetoothPbapVcardList(
+                        ACCOUNT, fileStream, PbapClientConnectionHandler.VCARD_TYPE_30);
         assertThat(result.getCount()).isEqualTo(0);
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java
index 6a5440ad740..a7331606e17 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java
@@ -60,8 +60,7 @@ public class CallLogPullRequestTest {
     private Context mTargetContext;
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Spy
-    private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance();
+    @Spy private BluetoothMethodProxy mMapMethodProxy = BluetoothMethodProxy.getInstance();
 
     @Before
     public void setUp() {
@@ -77,8 +76,8 @@ public class CallLogPullRequestTest {
     @Test
     public void testToString() {
         final String path = PbapClientConnectionHandler.ICH_PATH;
-        final CallLogPullRequest request = new CallLogPullRequest(
-                mTargetContext, path, mCallCounter, mAccount);
+        final CallLogPullRequest request =
+                new CallLogPullRequest(mTargetContext, path, mCallCounter, mAccount);
 
         assertThat(request.toString()).isNotEmpty();
     }
@@ -86,8 +85,8 @@ public class CallLogPullRequestTest {
     @Test
     public void onPullComplete_whenResultsAreNull() {
         final String path = PbapClientConnectionHandler.ICH_PATH;
-        final CallLogPullRequest request = new CallLogPullRequest(
-                mTargetContext, path, mCallCounter, mAccount);
+        final CallLogPullRequest request =
+                new CallLogPullRequest(mTargetContext, path, mCallCounter, mAccount);
         request.setResults(null);
 
         request.onPullComplete();
@@ -99,8 +98,8 @@ public class CallLogPullRequestTest {
     @Test
     public void onPullComplete_whenPathIsInvalid() {
         final String invalidPath = "invalidPath";
-        final CallLogPullRequest request = new CallLogPullRequest(
-                mTargetContext, invalidPath, mCallCounter, mAccount);
+        final CallLogPullRequest request =
+                new CallLogPullRequest(mTargetContext, invalidPath, mCallCounter, mAccount);
         List results = new ArrayList<>();
         request.setResults(results);
 
@@ -113,8 +112,8 @@ public class CallLogPullRequestTest {
     @Test
     public void onPullComplete_whenResultsAreEmpty() {
         final String path = PbapClientConnectionHandler.ICH_PATH;
-        final CallLogPullRequest request = new CallLogPullRequest(
-                mTargetContext, path, mCallCounter, mAccount);
+        final CallLogPullRequest request =
+                new CallLogPullRequest(mTargetContext, path, mCallCounter, mAccount);
         List results = new ArrayList<>();
         request.setResults(results);
 
@@ -127,8 +126,8 @@ public class CallLogPullRequestTest {
     @Test
     public void onPullComplete_whenThereIsNoPhoneProperty() {
         final String path = PbapClientConnectionHandler.MCH_PATH;
-        final CallLogPullRequest request = new CallLogPullRequest(
-                mTargetContext, path, mCallCounter, mAccount);
+        final CallLogPullRequest request =
+                new CallLogPullRequest(mTargetContext, path, mCallCounter, mAccount);
 
         // Add some property which is NOT a phone number
         VCardProperty property = new VCardProperty();
@@ -151,8 +150,8 @@ public class CallLogPullRequestTest {
     @Test
     public void onPullComplete_success() {
         final String path = PbapClientConnectionHandler.OCH_PATH;
-        final CallLogPullRequest request = new CallLogPullRequest(
-                mTargetContext, path, mCallCounter, mAccount);
+        final CallLogPullRequest request =
+                new CallLogPullRequest(mTargetContext, path, mCallCounter, mAccount);
         List results = new ArrayList<>();
 
         final String phoneNum = "tel:0123456789";
@@ -180,15 +179,16 @@ public class CallLogPullRequestTest {
     @Test
     public void updateTimesContacted_cursorIsClosed() {
         final String path = PbapClientConnectionHandler.OCH_PATH;
-        final CallLogPullRequest request = new CallLogPullRequest(
-                mTargetContext, path, mCallCounter, mAccount);
+        final CallLogPullRequest request =
+                new CallLogPullRequest(mTargetContext, path, mCallCounter, mAccount);
         mCallCounter.put("key", 1);
 
-        MatrixCursor cursor = new MatrixCursor(
-                new String[] {ContactsContract.PhoneLookup.CONTACT_ID});
+        MatrixCursor cursor =
+                new MatrixCursor(new String[] {ContactsContract.PhoneLookup.CONTACT_ID});
         cursor.addRow(new Object[] {"contact_id"});
-        doReturn(cursor).when(mMapMethodProxy).contentResolverQuery(any(), any(), eq(null),
-                eq(null), eq(null));
+        doReturn(cursor)
+                .when(mMapMethodProxy)
+                .contentResolverQuery(any(), any(), eq(null), eq(null), eq(null));
         assertThat(cursor.isClosed()).isFalse();
 
         request.updateTimesContacted();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java
index fd9932d67b2..04626d5591b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java
@@ -65,11 +65,9 @@ public class PbapClientConnectionHandlerTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private AdapterService mAdapterService;
+    @Mock private AdapterService mAdapterService;
 
-    @Mock
-    private DatabaseManager mDatabaseManager;
+    @Mock private DatabaseManager mDatabaseManager;
 
     private BluetoothAdapter mAdapter;
 
@@ -81,8 +79,10 @@ public class PbapClientConnectionHandlerTest {
 
     @Before
     public void setUp() throws Exception {
-        mTargetContext = spy(new ContextWrapper(
-                InstrumentationRegistry.getInstrumentation().getTargetContext()));
+        mTargetContext =
+                spy(
+                        new ContextWrapper(
+                                InstrumentationRegistry.getInstrumentation().getTargetContext()));
 
         if (Looper.myLooper() == null) {
             Looper.prepare();
@@ -102,12 +102,13 @@ public class PbapClientConnectionHandlerTest {
 
         when(mStateMachine.getContext()).thenReturn(mTargetContext);
 
-        mHandler = new PbapClientConnectionHandler.Builder()
-                .setLooper(mLooper)
-                .setClientSM(mStateMachine)
-                .setContext(mTargetContext)
-                .setRemoteDevice(mRemoteDevice)
-                .build();
+        mHandler =
+                new PbapClientConnectionHandler.Builder()
+                        .setLooper(mLooper)
+                        .setClientSM(mStateMachine)
+                        .setContext(mTargetContext)
+                        .setRemoteDevice(mRemoteDevice)
+                        .build();
     }
 
     @After
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
index e495bd119f8..fec23ebad97 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
@@ -128,15 +128,19 @@ public class PbapClientServiceTest {
 
     @Test
     public void testSetConnectionPolicy_withNullDevice_throwsIAE() {
-        assertThrows(IllegalArgumentException.class, () -> mService.setConnectionPolicy(
-                null, BluetoothProfile.CONNECTION_POLICY_ALLOWED));
+        assertThrows(
+                IllegalArgumentException.class,
+                () ->
+                        mService.setConnectionPolicy(
+                                null, BluetoothProfile.CONNECTION_POLICY_ALLOWED));
     }
 
     @Test
     public void testSetConnectionPolicy() {
         int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
         when(mDatabaseManager.setProfileConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.PBAP_CLIENT, connectionPolicy)).thenReturn(true);
+                        mRemoteDevice, BluetoothProfile.PBAP_CLIENT, connectionPolicy))
+                .thenReturn(true);
 
         assertThat(mService.setConnectionPolicy(mRemoteDevice, connectionPolicy)).isTrue();
     }
@@ -150,7 +154,8 @@ public class PbapClientServiceTest {
     public void testGetConnectionPolicy() {
         int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
         when(mDatabaseManager.getProfileConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.PBAP_CLIENT)).thenReturn(connectionPolicy);
+                        mRemoteDevice, BluetoothProfile.PBAP_CLIENT))
+                .thenReturn(connectionPolicy);
 
         assertThat(mService.getConnectionPolicy(mRemoteDevice)).isEqualTo(connectionPolicy);
     }
@@ -164,7 +169,8 @@ public class PbapClientServiceTest {
     public void testConnect_whenPolicyIsForbidden_returnsFalse() {
         int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
         when(mDatabaseManager.getProfileConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.PBAP_CLIENT)).thenReturn(connectionPolicy);
+                        mRemoteDevice, BluetoothProfile.PBAP_CLIENT))
+                .thenReturn(connectionPolicy);
 
         assertThat(mService.connect(mRemoteDevice)).isFalse();
     }
@@ -173,7 +179,8 @@ public class PbapClientServiceTest {
     public void testConnect_whenPolicyIsAllowed_returnsTrue() {
         int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
         when(mDatabaseManager.getProfileConnectionPolicy(
-                mRemoteDevice, BluetoothProfile.PBAP_CLIENT)).thenReturn(connectionPolicy);
+                        mRemoteDevice, BluetoothProfile.PBAP_CLIENT))
+                .thenReturn(connectionPolicy);
 
         assertThat(mService.connect(mRemoteDevice)).isTrue();
     }
@@ -361,8 +368,12 @@ public class PbapClientServiceTest {
                 BluetoothProfile.STATE_DISCONNECTED);
 
         ArgumentCaptor selectionArgsCaptor = ArgumentCaptor.forClass(Object.class);
-        verify(methodProxy).contentResolverDelete(any(), eq(CallLog.Calls.CONTENT_URI), any(),
-                (String[]) selectionArgsCaptor.capture());
+        verify(methodProxy)
+                .contentResolverDelete(
+                        any(),
+                        eq(CallLog.Calls.CONTENT_URI),
+                        any(),
+                        (String[]) selectionArgsCaptor.capture());
 
         assertThat(((String[]) selectionArgsCaptor.getValue())[0])
                 .isEqualTo(mRemoteDevice.getAddress());
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java
index d40aa8d5d10..beb817402ad 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java
@@ -49,26 +49,22 @@ import org.mockito.junit.MockitoRule;
 
 @MediumTest
 @RunWith(AndroidJUnit4.class)
-public class PbapClientStateMachineTest{
+public class PbapClientStateMachineTest {
     private static final String TAG = "PbapClientStateMachineTest";
 
     private PbapClientStateMachine mPbapClientStateMachine = null;
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private PbapClientService mMockPbapClientService;
-    @Mock
-    private UserManager mMockUserManager;
-    @Mock
-    private PbapClientConnectionHandler mMockHandler;
+    @Mock private PbapClientService mMockPbapClientService;
+    @Mock private UserManager mMockUserManager;
+    @Mock private PbapClientConnectionHandler mMockHandler;
 
     private BluetoothDevice mTestDevice;
     private BluetoothAdapter mAdapter;
 
     private ArgumentCaptor mIntentArgument = ArgumentCaptor.forClass(Intent.class);
 
-
     static final int DISCONNECT_TIMEOUT = 5000;
 
     @Before
@@ -82,8 +78,8 @@ public class PbapClientStateMachineTest{
                 .thenReturn(Context.USER_SERVICE);
         when(mMockPbapClientService.getSystemService(UserManager.class))
                 .thenReturn(mMockUserManager);
-        mPbapClientStateMachine = new PbapClientStateMachine(mMockPbapClientService, mTestDevice,
-                mMockHandler);
+        mPbapClientStateMachine =
+                new PbapClientStateMachine(mMockPbapClientService, mTestDevice, mMockHandler);
         mPbapClientStateMachine.start();
     }
 
@@ -94,23 +90,21 @@ public class PbapClientStateMachineTest{
         }
     }
 
-    /**
-     * Test that default state is STATE_CONNECTING
-     */
+    /** Test that default state is STATE_CONNECTING */
     @Test
     public void testDefaultConnectingState() {
         Log.i(TAG, "in testDefaultConnectingState");
         // it appears that enter and exit can overlap sometimes when calling doQuit()
         // currently solved by waiting for looper to finish task
-        TestUtils.waitForLooperToFinishScheduledTask(mPbapClientStateMachine.getHandler()
-                .getLooper());
+        TestUtils.waitForLooperToFinishScheduledTask(
+                mPbapClientStateMachine.getHandler().getLooper());
         assertThat(mPbapClientStateMachine.getConnectionState())
                 .isEqualTo(BluetoothProfile.STATE_CONNECTING);
     }
 
     /**
-     * Test transition from STATE_CONNECTING to STATE_DISCONNECTING
-     * and then to STATE_DISCONNECTED after timeout.
+     * Test transition from STATE_CONNECTING to STATE_DISCONNECTING and then to STATE_DISCONNECTED
+     * after timeout.
      */
     @Test
     public void testStateTransitionFromConnectingToDisconnected() {
@@ -119,15 +113,17 @@ public class PbapClientStateMachineTest{
 
         mPbapClientStateMachine.disconnect(mTestDevice);
 
-        TestUtils.waitForLooperToFinishScheduledTask(mPbapClientStateMachine.getHandler()
-                .getLooper());
+        TestUtils.waitForLooperToFinishScheduledTask(
+                mPbapClientStateMachine.getHandler().getLooper());
         assertThat(mPbapClientStateMachine.getConnectionState())
                 .isEqualTo(BluetoothProfile.STATE_DISCONNECTING);
 
-        //wait until timeout occurs
+        // wait until timeout occurs
         Mockito.clearInvocations(mMockPbapClientService);
         verify(mMockPbapClientService, timeout(DISCONNECT_TIMEOUT))
-                .sendBroadcastMultiplePermissions(mIntentArgument.capture(), any(String[].class),
+                .sendBroadcastMultiplePermissions(
+                        mIntentArgument.capture(),
+                        any(String[].class),
                         any(BroadcastOptions.class));
         assertThat(mPbapClientStateMachine.getConnectionState())
                 .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapParserTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapParserTest.java
index d86f8bede96..09a40840569 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapParserTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapParserTest.java
@@ -51,8 +51,10 @@ public class PbapParserTest {
     @Before
     public void setUp() {
         mTargetContext = InstrumentationRegistry.getTargetContext();
-        mAccount = new Account(TEST_ACCOUNT_NAME,
-                mTargetContext.getString(com.android.bluetooth.R.string.pbap_account_type));
+        mAccount =
+                new Account(
+                        TEST_ACCOUNT_NAME,
+                        mTargetContext.getString(com.android.bluetooth.R.string.pbap_account_type));
         mTestResources = TestUtils.getTestApplicationResources(mTargetContext);
         cleanupCallLog();
         cleanupPhonebook();
@@ -62,14 +64,19 @@ public class PbapParserTest {
     @Test
     public void testNoTimestamp() throws IOException {
         InputStream fileStream;
-        fileStream = mTestResources.openRawResource(
-                com.android.bluetooth.tests.R.raw.no_timestamp_call_log);
-        BluetoothPbapVcardList pbapVCardList = new BluetoothPbapVcardList(mAccount, fileStream,
-                PbapClientConnectionHandler.VCARD_TYPE_30);
+        fileStream =
+                mTestResources.openRawResource(
+                        com.android.bluetooth.tests.R.raw.no_timestamp_call_log);
+        BluetoothPbapVcardList pbapVCardList =
+                new BluetoothPbapVcardList(
+                        mAccount, fileStream, PbapClientConnectionHandler.VCARD_TYPE_30);
         Assert.assertEquals(1, pbapVCardList.getCount());
         CallLogPullRequest processor =
-                new CallLogPullRequest(mTargetContext, PbapClientConnectionHandler.MCH_PATH,
-                    new HashMap<>(), mAccount);
+                new CallLogPullRequest(
+                        mTargetContext,
+                        PbapClientConnectionHandler.MCH_PATH,
+                        new HashMap<>(),
+                        mAccount);
         processor.setResults(pbapVCardList.getList());
 
         // Verify that these entries aren't in the call log to start.
@@ -84,14 +91,19 @@ public class PbapParserTest {
     @Test
     public void testMissedCall() throws IOException {
         InputStream fileStream;
-        fileStream = mTestResources.openRawResource(
-                com.android.bluetooth.tests.R.raw.single_missed_call);
-        BluetoothPbapVcardList pbapVCardList = new BluetoothPbapVcardList(mAccount, fileStream,
-                PbapClientConnectionHandler.VCARD_TYPE_30);
+        fileStream =
+                mTestResources.openRawResource(
+                        com.android.bluetooth.tests.R.raw.single_missed_call);
+        BluetoothPbapVcardList pbapVCardList =
+                new BluetoothPbapVcardList(
+                        mAccount, fileStream, PbapClientConnectionHandler.VCARD_TYPE_30);
         Assert.assertEquals(1, pbapVCardList.getCount());
         CallLogPullRequest processor =
-                new CallLogPullRequest(mTargetContext, PbapClientConnectionHandler.MCH_PATH,
-                    new HashMap<>(), mAccount);
+                new CallLogPullRequest(
+                        mTargetContext,
+                        PbapClientConnectionHandler.MCH_PATH,
+                        new HashMap<>(),
+                        mAccount);
         processor.setResults(pbapVCardList.getList());
 
         // Verify that these entries aren't in the call log to start.
@@ -105,14 +117,19 @@ public class PbapParserTest {
     @Test
     public void testUnknownCall() throws IOException {
         InputStream fileStream;
-        fileStream = mTestResources.openRawResource(
-                com.android.bluetooth.tests.R.raw.unknown_number_call);
-        BluetoothPbapVcardList pbapVCardList = new BluetoothPbapVcardList(mAccount, fileStream,
-                PbapClientConnectionHandler.VCARD_TYPE_30);
+        fileStream =
+                mTestResources.openRawResource(
+                        com.android.bluetooth.tests.R.raw.unknown_number_call);
+        BluetoothPbapVcardList pbapVCardList =
+                new BluetoothPbapVcardList(
+                        mAccount, fileStream, PbapClientConnectionHandler.VCARD_TYPE_30);
         Assert.assertEquals(2, pbapVCardList.getCount());
         CallLogPullRequest processor =
-                new CallLogPullRequest(mTargetContext, PbapClientConnectionHandler.MCH_PATH,
-                    new HashMap<>(), mAccount);
+                new CallLogPullRequest(
+                        mTargetContext,
+                        PbapClientConnectionHandler.MCH_PATH,
+                        new HashMap<>(),
+                        mAccount);
         processor.setResults(pbapVCardList.getList());
 
         // Verify that these entries aren't in the call log to start.
@@ -128,10 +145,10 @@ public class PbapParserTest {
     @Test
     public void testPullPhoneBook() throws IOException {
         InputStream fileStream;
-        fileStream = mTestResources.openRawResource(
-                com.android.bluetooth.tests.R.raw.v30_simple);
-        BluetoothPbapVcardList pbapVCardList = new BluetoothPbapVcardList(mAccount, fileStream,
-                PbapClientConnectionHandler.VCARD_TYPE_30);
+        fileStream = mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.v30_simple);
+        BluetoothPbapVcardList pbapVCardList =
+                new BluetoothPbapVcardList(
+                        mAccount, fileStream, PbapClientConnectionHandler.VCARD_TYPE_30);
         Assert.assertEquals(1, pbapVCardList.getCount());
         PhonebookPullRequest processor = new PhonebookPullRequest(mTargetContext);
         processor.setResults(pbapVCardList.getList());
@@ -145,17 +162,24 @@ public class PbapParserTest {
     }
 
     private void cleanupPhonebook() {
-        mTargetContext.getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI,
-                null, null);
+        mTargetContext
+                .getContentResolver()
+                .delete(ContactsContract.RawContacts.CONTENT_URI, null, null);
     }
 
     // Find Entries in call log with type matching number and date.
     // If number or date is null it will match any number or date respectively.
     private boolean verifyCallLog(String number, String date, String type) {
-        String[] query = new String[]{Calls.NUMBER, Calls.DATE, Calls.TYPE};
-        Cursor cursor = mTargetContext.getContentResolver()
-                .query(Calls.CONTENT_URI, query, Calls.TYPE + "= " + type, null,
-                        Calls.DATE + ", " + Calls.NUMBER);
+        String[] query = new String[] {Calls.NUMBER, Calls.DATE, Calls.TYPE};
+        Cursor cursor =
+                mTargetContext
+                        .getContentResolver()
+                        .query(
+                                Calls.CONTENT_URI,
+                                query,
+                                Calls.TYPE + "= " + type,
+                                null,
+                                Calls.DATE + ", " + Calls.NUMBER);
         if (date != null) {
             date = adjDate(date);
         }
@@ -163,8 +187,8 @@ public class PbapParserTest {
             while (cursor.moveToNext()) {
                 String foundNumber = cursor.getString(cursor.getColumnIndex(Calls.NUMBER));
                 String foundDate = cursor.getString(cursor.getColumnIndex(Calls.DATE));
-                if ((number == null || number.equals(foundNumber)) && (date == null || date.equals(
-                        foundDate))) {
+                if ((number == null || number.equals(foundNumber))
+                        && (date == null || date.equals(foundDate))) {
                     return true;
                 }
             }
@@ -181,18 +205,18 @@ public class PbapParserTest {
     }
 
     private boolean verifyPhonebook(String name, String number) {
-        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
-                Uri.encode(number));
+        Uri uri =
+                Uri.withAppendedPath(
+                        ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
         Cursor c = mTargetContext.getContentResolver().query(uri, null, null, null);
         if (c != null && c.getCount() > 0) {
             c.moveToNext();
-            String displayName = c.getString(
-                    c.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
+            String displayName =
+                    c.getString(c.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
             if (displayName.equals(name)) {
                 return true;
             }
         }
         return false;
     }
-
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java
index 3b0b7114597..e7ef894ffa4 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java
@@ -76,10 +76,10 @@ public class SapMessageTest {
         int cardReaderStatus = STATUS_CARD_INSERTED;
         int statusChange = 1;
         int transportProtocol = TRANS_PROTO_T0;
-        byte[] apdu = new byte[]{0x01, 0x02};
-        byte[] apdu7816 = new byte[]{0x03, 0x04};
-        byte[] apduResp = new byte[]{0x05, 0x06};
-        byte[] atr = new byte[]{0x07, 0x08};
+        byte[] apdu = new byte[] {0x01, 0x02};
+        byte[] apdu7816 = new byte[] {0x03, 0x04};
+        byte[] apduResp = new byte[] {0x05, 0x06};
+        byte[] atr = new byte[] {0x07, 0x08};
         boolean sendToRil = true;
         boolean clearRilQueue = true;
         int testMode = TEST_MODE_ENABLE;
@@ -130,7 +130,7 @@ public class SapMessageTest {
 
     @Test
     public void getNumPendingRilMessages() {
-        SapMessage.sOngoingRequests.put(/*rilSerial=*/10000, ID_CONNECT_REQ);
+        SapMessage.sOngoingRequests.put(/* rilSerial= */ 10000, ID_CONNECT_REQ);
         assertThat(SapMessage.getNumPendingRilMessages()).isEqualTo(1);
 
         SapMessage.resetPendingRilMessages();
@@ -147,10 +147,10 @@ public class SapMessageTest {
         int cardReaderStatus = STATUS_CARD_INSERTED;
         int statusChange = 1;
         int transportProtocol = TRANS_PROTO_T0;
-        byte[] apdu = new byte[]{0x01, 0x02};
-        byte[] apdu7816 = new byte[]{0x03, 0x04};
-        byte[] apduResp = new byte[]{0x05, 0x06};
-        byte[] atr = new byte[]{0x07, 0x08};
+        byte[] apdu = new byte[] {0x01, 0x02};
+        byte[] apdu7816 = new byte[] {0x03, 0x04};
+        byte[] apduResp = new byte[] {0x05, 0x06};
+        byte[] atr = new byte[] {0x07, 0x08};
 
         mMessage.setMsgType(msgType);
         mMessage.setMaxMsgSize(maxMsgSize);
@@ -195,8 +195,8 @@ public class SapMessageTest {
     @Test
     public void send() throws Exception {
         int maxMsgSize = 512;
-        byte[] apdu = new byte[]{0x01, 0x02};
-        byte[] apdu7816 = new byte[]{0x03, 0x04};
+        byte[] apdu = new byte[] {0x01, 0x02};
+        byte[] apdu7816 = new byte[] {0x03, 0x04};
 
         ISapRilReceiver sapProxy = mock(ISapRilReceiver.class);
         mMessage.setClearRilQueue(true);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java
index 42fc15d7a06..094b9d67ec4 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java
@@ -81,16 +81,13 @@ public class SapRilReceiverHidlTest {
     private HandlerThread mHandlerThread;
     private Handler mServerMsgHandler;
 
-    @Spy
-    private TestHandlerCallback mCallback = new TestHandlerCallback();
+    @Spy private TestHandlerCallback mCallback = new TestHandlerCallback();
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private Handler mServiceHandler;
+    @Mock private Handler mServiceHandler;
 
-    @Mock
-    private ISap mSapProxy;
+    @Mock private ISap mSapProxy;
 
     private SapRilReceiverHidl mReceiver;
 
@@ -144,9 +141,9 @@ public class SapRilReceiverHidlTest {
         mReceiver.mSapProxyDeathRecipient.serviceDied(cookie);
 
         verify(mCallback, timeout(ISAP_GET_SERVICE_DELAY_MILLIS + TIMEOUT_MS))
-                .receiveMessage(eq(SAP_PROXY_DEAD), argThat(
-                        arg -> (arg instanceof Long) && ((Long) arg == cookie)
-                ));
+                .receiveMessage(
+                        eq(SAP_PROXY_DEAD),
+                        argThat(arg -> (arg instanceof Long) && ((Long) arg == cookie)));
     }
 
     @Test
@@ -156,19 +153,21 @@ public class SapRilReceiverHidlTest {
         int maxMsgSize = 512;
         mReceiver.mSapCallback.connectResponse(token, sapConnectRsp, maxMsgSize);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_CONNECT_RESP
-                                && sapMsg.getConnectionStatus() == sapConnectRsp;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_CONNECT_RESP
+                                                && sapMsg.getConnectionStatus() == sapConnectRsp;
+                                    }
+                                }));
     }
 
     @Test
@@ -176,18 +175,20 @@ public class SapRilReceiverHidlTest {
         int token = 1;
         mReceiver.mSapCallback.disconnectResponse(token);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_DISCONNECT_RESP;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_DISCONNECT_RESP;
+                                    }
+                                }));
     }
 
     @Test
@@ -196,26 +197,28 @@ public class SapRilReceiverHidlTest {
         int disconnectType = DISC_GRACEFULL;
         mReceiver.mSapCallback.disconnectIndication(token, disconnectType);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RIL_IND), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_RIL_UNSOL_DISCONNECT_IND
-                                && sapMsg.getDisconnectionType() == disconnectType;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RIL_IND),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_RIL_UNSOL_DISCONNECT_IND
+                                                && sapMsg.getDisconnectionType() == disconnectType;
+                                    }
+                                }));
     }
 
     @Test
     public void callback_apduResponse() throws Exception {
         int token = 1;
         int resultCode = RESULT_OK;
-        byte[] apduRsp = new byte[]{0x03, 0x04};
+        byte[] apduRsp = new byte[] {0x03, 0x04};
         ArrayList apduRspList = new ArrayList<>();
         for (byte b : apduRsp) {
             apduRspList.add(b);
@@ -223,27 +226,29 @@ public class SapRilReceiverHidlTest {
 
         mReceiver.mSapCallback.apduResponse(token, resultCode, apduRspList);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_TRANSFER_APDU_RESP
-                                && sapMsg.getResultCode() == resultCode
-                                && Arrays.equals(sapMsg.getApduResp(), apduRsp);
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_TRANSFER_APDU_RESP
+                                                && sapMsg.getResultCode() == resultCode
+                                                && Arrays.equals(sapMsg.getApduResp(), apduRsp);
+                                    }
+                                }));
     }
 
     @Test
     public void callback_transferAtrResponse() throws Exception {
         int token = 1;
         int resultCode = RESULT_OK;
-        byte[] atr = new byte[]{0x03, 0x04};
+        byte[] atr = new byte[] {0x03, 0x04};
         ArrayList atrList = new ArrayList<>();
         for (byte b : atr) {
             atrList.add(b);
@@ -251,20 +256,22 @@ public class SapRilReceiverHidlTest {
 
         mReceiver.mSapCallback.transferAtrResponse(token, resultCode, atrList);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_TRANSFER_ATR_RESP
-                                && sapMsg.getResultCode() == resultCode
-                                && Arrays.equals(sapMsg.getAtr(), atr);
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_TRANSFER_ATR_RESP
+                                                && sapMsg.getResultCode() == resultCode
+                                                && Arrays.equals(sapMsg.getAtr(), atr);
+                                    }
+                                }));
     }
 
     @Test
@@ -277,19 +284,21 @@ public class SapRilReceiverHidlTest {
 
         mReceiver.mSapCallback.powerResponse(token, resultCode);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_POWER_SIM_OFF_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_POWER_SIM_OFF_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     @Test
@@ -302,19 +311,21 @@ public class SapRilReceiverHidlTest {
 
         mReceiver.mSapCallback.powerResponse(token, resultCode);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_POWER_SIM_ON_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_POWER_SIM_ON_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     @Test
@@ -324,19 +335,21 @@ public class SapRilReceiverHidlTest {
 
         mReceiver.mSapCallback.resetSimResponse(token, resultCode);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_RESET_SIM_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_RESET_SIM_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     @Test
@@ -346,19 +359,21 @@ public class SapRilReceiverHidlTest {
 
         mReceiver.mSapCallback.statusIndication(token, statusChange);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_STATUS_IND
-                                && sapMsg.getStatusChange() == statusChange;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_STATUS_IND
+                                                && sapMsg.getStatusChange() == statusChange;
+                                    }
+                                }));
     }
 
     @Test
@@ -370,19 +385,22 @@ public class SapRilReceiverHidlTest {
         mReceiver.mSapCallback.transferCardReaderStatusResponse(
                 token, resultCode, cardReaderStatus);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_TRANSFER_CARD_READER_STATUS_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType()
+                                                        == ID_TRANSFER_CARD_READER_STATUS_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     @Test
@@ -391,18 +409,20 @@ public class SapRilReceiverHidlTest {
 
         mReceiver.mSapCallback.errorResponse(token);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RIL_IND), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_RIL_UNKNOWN;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RIL_IND),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_RIL_UNKNOWN;
+                                    }
+                                }));
     }
 
     @Test
@@ -412,19 +432,21 @@ public class SapRilReceiverHidlTest {
 
         mReceiver.mSapCallback.transferProtocolResponse(token, resultCode);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_SET_TRANSPORT_PROTOCOL_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_SET_TRANSPORT_PROTOCOL_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     public static class TestHandlerCallback implements Handler.Callback {
@@ -435,7 +457,6 @@ public class SapRilReceiverHidlTest {
             return true;
         }
 
-        public void receiveMessage(int what, Object obj) {
-        }
+        public void receiveMessage(int what, Object obj) {}
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java
index 293b892a7d1..50199e4fd37 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java
@@ -83,16 +83,13 @@ public class SapRilReceiverTest {
     private HandlerThread mHandlerThread;
     private Handler mServerMsgHandler;
 
-    @Spy
-    private TestHandlerCallback mCallback = new TestHandlerCallback();
+    @Spy private TestHandlerCallback mCallback = new TestHandlerCallback();
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private Handler mServiceHandler;
+    @Mock private Handler mServiceHandler;
 
-    @Mock
-    private ISap mSapProxy;
+    @Mock private ISap mSapProxy;
 
     private SapRilReceiver mReceiver;
 
@@ -149,9 +146,9 @@ public class SapRilReceiverTest {
         mReceiver.mSapProxyDeathRecipient.binderDied();
 
         verify(mCallback, timeout(ISAP_GET_SERVICE_DELAY_MILLIS + TIMEOUT_MS))
-                .receiveMessage(eq(SAP_PROXY_DEAD), argThat(
-                        arg -> (arg instanceof Long) && ((Long) arg == 0)
-                ));
+                .receiveMessage(
+                        eq(SAP_PROXY_DEAD),
+                        argThat(arg -> (arg instanceof Long) && ((Long) arg == 0)));
     }
 
     @Test
@@ -161,19 +158,21 @@ public class SapRilReceiverTest {
         int maxMsgSize = 512;
         mReceiver.mSapCallback.connectResponse(token, sapConnectRsp, maxMsgSize);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_CONNECT_RESP
-                                && sapMsg.getConnectionStatus() == sapConnectRsp;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_CONNECT_RESP
+                                                && sapMsg.getConnectionStatus() == sapConnectRsp;
+                                    }
+                                }));
     }
 
     @Test
@@ -181,18 +180,20 @@ public class SapRilReceiverTest {
         int token = 1;
         mReceiver.mSapCallback.disconnectResponse(token);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_DISCONNECT_RESP;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_DISCONNECT_RESP;
+                                    }
+                                }));
     }
 
     @Test
@@ -201,67 +202,73 @@ public class SapRilReceiverTest {
         int disconnectType = DISC_GRACEFULL;
         mReceiver.mSapCallback.disconnectIndication(token, disconnectType);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RIL_IND), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_RIL_UNSOL_DISCONNECT_IND
-                                && sapMsg.getDisconnectionType() == disconnectType;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RIL_IND),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_RIL_UNSOL_DISCONNECT_IND
+                                                && sapMsg.getDisconnectionType() == disconnectType;
+                                    }
+                                }));
     }
 
     @Test
     public void callback_apduResponse() throws Exception {
         int token = 1;
         int resultCode = RESULT_OK;
-        byte[] apduRsp = new byte[]{0x03, 0x04};
+        byte[] apduRsp = new byte[] {0x03, 0x04};
 
         mReceiver.mSapCallback.apduResponse(token, resultCode, apduRsp);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_TRANSFER_APDU_RESP
-                                && sapMsg.getResultCode() == resultCode
-                                && Arrays.equals(sapMsg.getApduResp(), apduRsp);
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_TRANSFER_APDU_RESP
+                                                && sapMsg.getResultCode() == resultCode
+                                                && Arrays.equals(sapMsg.getApduResp(), apduRsp);
+                                    }
+                                }));
     }
 
     @Test
     public void callback_transferAtrResponse() throws Exception {
         int token = 1;
         int resultCode = RESULT_OK;
-        byte[] atr = new byte[]{0x03, 0x04};
+        byte[] atr = new byte[] {0x03, 0x04};
 
         mReceiver.mSapCallback.transferAtrResponse(token, resultCode, atr);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_TRANSFER_ATR_RESP
-                                && sapMsg.getResultCode() == resultCode
-                                && Arrays.equals(sapMsg.getAtr(), atr);
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_TRANSFER_ATR_RESP
+                                                && sapMsg.getResultCode() == resultCode
+                                                && Arrays.equals(sapMsg.getAtr(), atr);
+                                    }
+                                }));
     }
 
     @Test
@@ -274,19 +281,21 @@ public class SapRilReceiverTest {
 
         mReceiver.mSapCallback.powerResponse(token, resultCode);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_POWER_SIM_OFF_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_POWER_SIM_OFF_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     @Test
@@ -299,19 +308,21 @@ public class SapRilReceiverTest {
 
         mReceiver.mSapCallback.powerResponse(token, resultCode);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_POWER_SIM_ON_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_POWER_SIM_ON_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     @Test
@@ -321,19 +332,21 @@ public class SapRilReceiverTest {
 
         mReceiver.mSapCallback.resetSimResponse(token, resultCode);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_RESET_SIM_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_RESET_SIM_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     @Test
@@ -343,19 +356,21 @@ public class SapRilReceiverTest {
 
         mReceiver.mSapCallback.statusIndication(token, statusChange);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_STATUS_IND
-                                && sapMsg.getStatusChange() == statusChange;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_STATUS_IND
+                                                && sapMsg.getStatusChange() == statusChange;
+                                    }
+                                }));
     }
 
     @Test
@@ -367,19 +382,22 @@ public class SapRilReceiverTest {
         mReceiver.mSapCallback.transferCardReaderStatusResponse(
                 token, resultCode, cardReaderStatus);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_TRANSFER_CARD_READER_STATUS_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType()
+                                                        == ID_TRANSFER_CARD_READER_STATUS_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     @Test
@@ -388,18 +406,20 @@ public class SapRilReceiverTest {
 
         mReceiver.mSapCallback.errorResponse(token);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RIL_IND), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_RIL_UNKNOWN;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RIL_IND),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_RIL_UNKNOWN;
+                                    }
+                                }));
     }
 
     @Test
@@ -409,19 +429,21 @@ public class SapRilReceiverTest {
 
         mReceiver.mSapCallback.transferProtocolResponse(token, resultCode);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        if (!(arg instanceof SapMessage)) {
-                            return false;
-                        }
-                        SapMessage sapMsg = (SapMessage) arg;
-                        return sapMsg.getMsgType() == ID_SET_TRANSPORT_PROTOCOL_RESP
-                                && sapMsg.getResultCode() == resultCode;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        if (!(arg instanceof SapMessage)) {
+                                            return false;
+                                        }
+                                        SapMessage sapMsg = (SapMessage) arg;
+                                        return sapMsg.getMsgType() == ID_SET_TRANSPORT_PROTOCOL_RESP
+                                                && sapMsg.getResultCode() == resultCode;
+                                    }
+                                }));
     }
 
     public static class TestHandlerCallback implements Handler.Callback {
@@ -432,7 +454,6 @@ public class SapRilReceiverTest {
             return true;
         }
 
-        public void receiveMessage(int what, Object obj) {
-        }
+        public void receiveMessage(int what, Object obj) {}
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java
index 0de1343d3a9..819ff6cfcd8 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java
@@ -97,16 +97,13 @@ public class SapServerTest {
     private Context mTargetContext =
             new ContextWrapper(InstrumentationRegistry.getInstrumentation().getTargetContext());
 
-    @Spy
-    private TestHandlerCallback mCallback = new TestHandlerCallback();
+    @Spy private TestHandlerCallback mCallback = new TestHandlerCallback();
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private InputStream mInputStream;
+    @Mock private InputStream mInputStream;
 
-    @Mock
-    private OutputStream mOutputStream;
+    @Mock private OutputStream mOutputStream;
 
     private SapServer mSapServer;
 
@@ -182,9 +179,13 @@ public class SapServerTest {
         mSapServer.changeState(SapServer.SAP_STATE.CONNECTED);
         mSapServer.onConnectRequest(mock(SapMessage.class));
 
-        verify(mSapServer).sendClientMessage(argThat(
-                sapMsg -> sapMsg.getMsgType() == ID_CONNECT_RESP
-                        && sapMsg.getConnectionStatus() == CON_STATUS_ERROR_CONNECTION));
+        verify(mSapServer)
+                .sendClientMessage(
+                        argThat(
+                                sapMsg ->
+                                        sapMsg.getMsgType() == ID_CONNECT_RESP
+                                                && sapMsg.getConnectionStatus()
+                                                        == CON_STATUS_ERROR_CONNECTION));
     }
 
     @Test
@@ -194,9 +195,13 @@ public class SapServerTest {
         mSapServer.changeState(SapServer.SAP_STATE.CONNECTING_CALL_ONGOING);
         mSapServer.onConnectRequest(mock(SapMessage.class));
 
-        verify(mSapServer, atLeastOnce()).sendClientMessage(argThat(
-                sapMsg -> sapMsg.getMsgType() == ID_CONNECT_RESP
-                        && sapMsg.getConnectionStatus() == CON_STATUS_ERROR_CONNECTION));
+        verify(mSapServer, atLeastOnce())
+                .sendClientMessage(
+                        argThat(
+                                sapMsg ->
+                                        sapMsg.getMsgType() == ID_CONNECT_RESP
+                                                && sapMsg.getConnectionStatus()
+                                                        == CON_STATUS_ERROR_CONNECTION));
     }
 
     @Test
@@ -243,8 +248,8 @@ public class SapServerTest {
         SapMessage msg = mock(SapMessage.class);
         mSapServer.sendRilMessage(msg);
 
-        verify(mSapServer).sendClientMessage(
-                argThat(sapMsg -> sapMsg.getMsgType() == ID_ERROR_RESP));
+        verify(mSapServer)
+                .sendClientMessage(argThat(sapMsg -> sapMsg.getMsgType() == ID_ERROR_RESP));
     }
 
     @Test
@@ -259,8 +264,8 @@ public class SapServerTest {
         doThrow(new IllegalArgumentException()).when(msg).send(any());
         mSapServer.sendRilMessage(msg);
 
-        verify(mSapServer).sendClientMessage(
-                argThat(sapMsg -> sapMsg.getMsgType() == ID_ERROR_RESP));
+        verify(mSapServer)
+                .sendClientMessage(argThat(sapMsg -> sapMsg.getMsgType() == ID_ERROR_RESP));
     }
 
     @Test
@@ -277,8 +282,8 @@ public class SapServerTest {
         doThrow(new RemoteException()).when(msg).send(any());
         mSapServer.sendRilMessage(msg);
 
-        verify(mSapServer).sendClientMessage(
-                argThat(sapMsg -> sapMsg.getMsgType() == ID_ERROR_RESP));
+        verify(mSapServer)
+                .sendClientMessage(argThat(sapMsg -> sapMsg.getMsgType() == ID_ERROR_RESP));
         verify(mockReceiver).notifyShutdown();
         verify(mockReceiver).resetSapProxy();
     }
@@ -303,9 +308,13 @@ public class SapServerTest {
         mSapServer.changeState(SapServer.SAP_STATE.CONNECTED);
         mSapServer.handleRilInd(msg);
 
-        verify(mSapServer).sendClientMessage(argThat(
-                sapMsg -> sapMsg.getMsgType() == ID_DISCONNECT_IND
-                        && sapMsg.getDisconnectionType() == disconnectionType));
+        verify(mSapServer)
+                .sendClientMessage(
+                        argThat(
+                                sapMsg ->
+                                        sapMsg.getMsgType() == ID_DISCONNECT_IND
+                                                && sapMsg.getDisconnectionType()
+                                                        == disconnectionType));
     }
 
     @Test
@@ -479,14 +488,16 @@ public class SapServerTest {
         SapMessage msg = new SapMessage(ID_STATUS_IND);
         mSapServer.sendRilThreadMessage(msg);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RIL_REQ), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        return msg == arg;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RIL_REQ),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        return msg == arg;
+                                    }
+                                }));
     }
 
     @Test
@@ -496,14 +507,16 @@ public class SapServerTest {
         SapMessage msg = new SapMessage(ID_STATUS_IND);
         mSapServer.sendClientMessage(msg);
 
-        verify(mCallback, timeout(TIMEOUT_MS)).receiveMessage(eq(SAP_MSG_RFC_REPLY), argThat(
-                new ArgumentMatcher() {
-                    @Override
-                    public boolean matches(Object arg) {
-                        return msg == arg;
-                    }
-                }
-        ));
+        verify(mCallback, timeout(TIMEOUT_MS))
+                .receiveMessage(
+                        eq(SAP_MSG_RFC_REPLY),
+                        argThat(
+                                new ArgumentMatcher() {
+                                    @Override
+                                    public boolean matches(Object arg) {
+                                        return msg == arg;
+                                    }
+                                }));
     }
 
     // TODO: Find a good way to run() method.
@@ -553,8 +566,8 @@ public class SapServerTest {
         try {
             mSapServer.handleMessage(message);
 
-            verify(mSapServer).sendRilMessage(
-                    argThat(sapMsg -> sapMsg.getMsgType() == ID_CONNECT_REQ));
+            verify(mSapServer)
+                    .sendRilMessage(argThat(sapMsg -> sapMsg.getMsgType() == ID_CONNECT_REQ));
         } finally {
             message.recycle();
         }
@@ -652,8 +665,8 @@ public class SapServerTest {
         assertThat(mSapServer.mState).isEqualTo(SapServer.SAP_STATE.CONNECTING_CALL_ONGOING);
         mSapServer.mIntentReceiver.onReceive(mTargetContext, intent);
 
-        verify(mSapServer).onConnectRequest(
-                argThat(sapMsg -> sapMsg.getMsgType() == ID_CONNECT_REQ));
+        verify(mSapServer)
+                .onConnectRequest(argThat(sapMsg -> sapMsg.getMsgType() == ID_CONNECT_REQ));
     }
 
     @Test
@@ -701,8 +714,6 @@ public class SapServerTest {
             return true;
         }
 
-        public void receiveMessage(int what, Object obj) {
-        }
+        public void receiveMessage(int what, Object obj) {}
     }
 }
-
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
index 6e3071ea4ee..48ca06618f6 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
@@ -85,9 +85,7 @@ public class SapServiceTest {
         assertThat(mService.getConnectedDevices()).isEmpty();
     }
 
-    /**
-     * Test stop SAP Service
-     */
+    /** Test stop SAP Service */
     @Test
     public void testStopSapService() throws Exception {
         // SAP Service is already running: test stop(). Note: must be done on the main thread
@@ -108,14 +106,12 @@ public class SapServiceTest {
         assertThat(mService.getConnectionPolicy(mDevice))
                 .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
 
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
         assertThat(mService.getConnectionPolicy(mDevice))
                 .isEqualTo(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
 
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
 
         assertThat(mService.getConnectionPolicy(mDevice))
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java b/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java
index 95812204101..f7cd7f86d58 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java
@@ -91,19 +91,26 @@ public class DipTest {
         SdpManagerNativeInterface.setInstance(null);
     }
 
-    private void verifyDipSdpRecordIntent(ArgumentCaptor intentArgument,
-            int status, BluetoothDevice device,
-            byte[] uuid,  int specificationId,
-            int vendorId, int vendorIdSource,
-            int productId, int version,
+    private void verifyDipSdpRecordIntent(
+            ArgumentCaptor intentArgument,
+            int status,
+            BluetoothDevice device,
+            byte[] uuid,
+            int specificationId,
+            int vendorId,
+            int vendorIdSource,
+            int productId,
+            int version,
             boolean primaryRecord) {
         Intent intent = intentArgument.getValue();
 
         assertThat(intent).isNotEqualTo(null);
         assertThat(intent.getAction()).isEqualTo(BluetoothDevice.ACTION_SDP_RECORD);
         assertThat(device).isEqualTo(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));
-        assertThat(Utils.byteArrayToUuid(uuid)[0]).isEqualTo(intent.getParcelableExtra(BluetoothDevice.EXTRA_UUID));
-        assertThat(status).isEqualTo(intent.getIntExtra(BluetoothDevice.EXTRA_SDP_SEARCH_STATUS, -1));
+        assertThat(Utils.byteArrayToUuid(uuid)[0])
+                .isEqualTo(intent.getParcelableExtra(BluetoothDevice.EXTRA_UUID));
+        assertThat(status)
+                .isEqualTo(intent.getIntExtra(BluetoothDevice.EXTRA_SDP_SEARCH_STATUS, -1));
 
         SdpDipRecord record = intent.getParcelableExtra(BluetoothDevice.EXTRA_SDP_RECORD);
         assertThat(record).isNotEqualTo(null);
@@ -115,9 +122,7 @@ public class DipTest {
         assertThat(primaryRecord).isEqualTo(record.getPrimaryRecord());
     }
 
-    /**
-     * Test that an outgoing connection/disconnection succeeds
-     */
+    /** Test that an outgoing connection/disconnection succeeds */
     @Test
     @SmallTest
     public void testDipCallbackSuccess() {
@@ -132,12 +137,32 @@ public class DipTest {
         boolean moreResults = false;
 
         mSdpManager.sdpSearch(mTestDevice, BluetoothUuid.DIP);
-        mSdpManager.sdpDipRecordFoundCallback(AbstractionLayer.BT_STATUS_SUCCESS,
-                Utils.getByteAddress(mTestDevice), uuid, specificationId,
-                vendorId, vendorIdSource, productId, version, primaryRecord, moreResults);
-        verify(mAdapterService).sendBroadcast(mIntentArgument.capture(), mStringArgument.capture(),
-                mBundleArgument.capture());
-        verifyDipSdpRecordIntent(mIntentArgument, AbstractionLayer.BT_STATUS_SUCCESS, mTestDevice,
-                uuid, specificationId, vendorId, vendorIdSource, productId, version, primaryRecord);
+        mSdpManager.sdpDipRecordFoundCallback(
+                AbstractionLayer.BT_STATUS_SUCCESS,
+                Utils.getByteAddress(mTestDevice),
+                uuid,
+                specificationId,
+                vendorId,
+                vendorIdSource,
+                productId,
+                version,
+                primaryRecord,
+                moreResults);
+        verify(mAdapterService)
+                .sendBroadcast(
+                        mIntentArgument.capture(),
+                        mStringArgument.capture(),
+                        mBundleArgument.capture());
+        verifyDipSdpRecordIntent(
+                mIntentArgument,
+                AbstractionLayer.BT_STATUS_SUCCESS,
+                mTestDevice,
+                uuid,
+                specificationId,
+                vendorId,
+                vendorIdSource,
+                productId,
+                version,
+                primaryRecord);
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java b/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java
index d619b6136ff..564fc2f4b94 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java
@@ -75,20 +75,14 @@ public class TbsGattTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private AdapterService mAdapterService;
-    @Mock
-    private BluetoothGattServerProxy mMockGattServer;
-    @Mock
-    private TbsGatt.Callback mMockTbsGattCallback;
-    @Mock
-    private TbsService mMockTbsService;
+    @Mock private AdapterService mAdapterService;
+    @Mock private BluetoothGattServerProxy mMockGattServer;
+    @Mock private TbsGatt.Callback mMockTbsGattCallback;
+    @Mock private TbsService mMockTbsService;
 
-    @Rule
-    public final ServiceTestRule mServiceRule = new ServiceTestRule();
+    @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule();
 
-    @Captor
-    private ArgumentCaptor mGattServiceCaptor;
+    @Captor private ArgumentCaptor mGattServiceCaptor;
 
     @Before
     public void setUp() throws Exception {
@@ -98,13 +92,13 @@ public class TbsGattTest {
 
         getInstrumentation().getUiAutomation().adoptShellPermissionIdentity();
 
-
         TestUtils.setAdapterService(mAdapterService);
         mAdapter = BluetoothAdapter.getDefaultAdapter();
 
         doReturn(true).when(mMockGattServer).addService(any(BluetoothGattService.class));
         doReturn(true).when(mMockGattServer).open(any(BluetoothGattServerCallback.class));
-        doReturn(BluetoothDevice.ACCESS_ALLOWED).when(mMockTbsService)
+        doReturn(BluetoothDevice.ACCESS_ALLOWED)
+                .when(mMockTbsService)
                 .getDeviceAuthorization(any(BluetoothDevice.class));
 
         mTbsGatt = new TbsGatt(mMockTbsService);
@@ -113,8 +107,8 @@ public class TbsGattTest {
         mFirstDevice = TestUtils.getTestDevice(mAdapter, 0);
         mSecondDevice = TestUtils.getTestDevice(mAdapter, 1);
 
-        when(mMockTbsService.getDeviceAuthorization(any(BluetoothDevice.class))).thenReturn(
-                BluetoothDevice.ACCESS_ALLOWED);
+        when(mMockTbsService.getDeviceAuthorization(any(BluetoothDevice.class)))
+                .thenReturn(BluetoothDevice.ACCESS_ALLOWED);
     }
 
     @After
@@ -132,8 +126,16 @@ public class TbsGattTest {
         mCurrentProviderName = "unknown";
         mCurrentTechnology = 0x00;
 
-        Assert.assertTrue(mTbsGatt.init(mCurrentCcid, mCurrentUci, mCurrentUriSchemes, true, true,
-                mCurrentProviderName, mCurrentTechnology, mMockTbsGattCallback));
+        Assert.assertTrue(
+                mTbsGatt.init(
+                        mCurrentCcid,
+                        mCurrentUci,
+                        mCurrentUriSchemes,
+                        true,
+                        true,
+                        mCurrentProviderName,
+                        mCurrentTechnology,
+                        mMockTbsGattCallback));
         Assert.assertNotNull(mMockGattServer);
 
         verify(mMockGattServer).addService(mGattServiceCaptor.capture());
@@ -149,22 +151,33 @@ public class TbsGattTest {
         return characteristic;
     }
 
-    private void configureNotifications(BluetoothDevice device,
-            BluetoothGattCharacteristic characteristic, boolean enable) {
+    private void configureNotifications(
+            BluetoothDevice device, BluetoothGattCharacteristic characteristic, boolean enable) {
         BluetoothGattDescriptor descriptor =
                 characteristic.getDescriptor(TbsGatt.UUID_CLIENT_CHARACTERISTIC_CONFIGURATION);
         Assert.assertNotNull(descriptor);
 
-        mTbsGatt.mGattServerCallback.onDescriptorWriteRequest(device, 1, descriptor, false, true, 0,
-                enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
+        mTbsGatt.mGattServerCallback.onDescriptorWriteRequest(
+                device,
+                1,
+                descriptor,
+                false,
+                true,
+                0,
+                enable
+                        ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                         : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
-        verify(mMockGattServer).sendResponse(eq(device), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0), any());
+        verify(mMockGattServer)
+                .sendResponse(eq(device), eq(1), eq(BluetoothGatt.GATT_SUCCESS), eq(0), any());
         reset(mMockGattServer);
     }
 
-    private void verifySetValue(BluetoothGattCharacteristic characteristic, Object value,
-            boolean shouldNotify, BluetoothDevice device, boolean clearGattMock) {
+    private void verifySetValue(
+            BluetoothGattCharacteristic characteristic,
+            Object value,
+            boolean shouldNotify,
+            BluetoothDevice device,
+            boolean clearGattMock) {
         boolean notifyWithValue = false;
 
         if (characteristic.getUuid().equals(TbsGatt.UUID_BEARER_PROVIDER_NAME)) {
@@ -178,10 +191,12 @@ public class TbsGattTest {
 
         } else if (characteristic.getUuid().equals(TbsGatt.UUID_BEARER_TECHNOLOGY)) {
             Assert.assertTrue(mTbsGatt.setBearerTechnology((Integer) value));
-            Assert.assertEquals((Integer) value,
+            Assert.assertEquals(
+                    (Integer) value,
                     characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));
 
-        } else if (characteristic.getUuid()
+        } else if (characteristic
+                .getUuid()
                 .equals(TbsGatt.UUID_BEARER_URI_SCHEMES_SUPPORTED_LIST)) {
             String valueString = String.join(",", (List) value);
             boolean valueChanged = !characteristic.getStringValue(0).equals(valueString);
@@ -236,8 +251,10 @@ public class TbsGattTest {
                     mTbsGatt.setTerminationReason(indexReasonPair.first, indexReasonPair.second));
             Assert.assertTrue(
                     Arrays.equals(
-                            new byte[] {(byte) indexReasonPair.first.byteValue(),
-                                    indexReasonPair.second.byteValue()},
+                            new byte[] {
+                                (byte) indexReasonPair.first.byteValue(),
+                                indexReasonPair.second.byteValue()
+                            },
                             characteristic.getValue()));
 
         } else if (characteristic.getUuid().equals(TbsGatt.UUID_INCOMING_CALL)) {
@@ -248,10 +265,12 @@ public class TbsGattTest {
                 Pair indexStrPair = (Pair) value;
                 Assert.assertTrue(
                         mTbsGatt.setIncomingCall(indexStrPair.first, indexStrPair.second));
-                Assert.assertTrue(Arrays.equals(
-                        Bytes.concat(new byte[] {(byte) indexStrPair.first.byteValue()},
-                                indexStrPair.second.getBytes(StandardCharsets.UTF_8)),
-                        characteristic.getValue()));
+                Assert.assertTrue(
+                        Arrays.equals(
+                                Bytes.concat(
+                                        new byte[] {(byte) indexStrPair.first.byteValue()},
+                                        indexStrPair.second.getBytes(StandardCharsets.UTF_8)),
+                                characteristic.getValue()));
             }
 
         } else if (characteristic.getUuid().equals(TbsGatt.UUID_CALL_FRIENDLY_NAME)) {
@@ -262,29 +281,33 @@ public class TbsGattTest {
                 Pair indexNamePair = (Pair) value;
                 Assert.assertTrue(
                         mTbsGatt.setCallFriendlyName(indexNamePair.first, indexNamePair.second));
-                Assert.assertTrue(Arrays.equals(
-                        Bytes.concat(new byte[] {(byte) indexNamePair.first.byteValue()},
-                                indexNamePair.second.getBytes(StandardCharsets.UTF_8)),
-                        characteristic.getValue()));
+                Assert.assertTrue(
+                        Arrays.equals(
+                                Bytes.concat(
+                                        new byte[] {(byte) indexNamePair.first.byteValue()},
+                                        indexNamePair.second.getBytes(StandardCharsets.UTF_8)),
+                                characteristic.getValue()));
             }
         }
 
         if (shouldNotify) {
-                if (notifyWithValue) {
-                        verify(mMockGattServer).notifyCharacteristicChanged(eq(device),
-                                eq(characteristic), eq(false), any());
-                } else {
-                        verify(mMockGattServer).notifyCharacteristicChanged(eq(device),
-                                eq(characteristic), eq(false));
-                }
+            if (notifyWithValue) {
+                verify(mMockGattServer)
+                        .notifyCharacteristicChanged(
+                                eq(device), eq(characteristic), eq(false), any());
+            } else {
+                verify(mMockGattServer)
+                        .notifyCharacteristicChanged(eq(device), eq(characteristic), eq(false));
+            }
         } else {
-                if (notifyWithValue) {
-                        verify(mMockGattServer, times(0)).notifyCharacteristicChanged(eq(device),
-                                eq(characteristic), anyBoolean(), any());
-                } else {
-                        verify(mMockGattServer, times(0)).notifyCharacteristicChanged(eq(device),
-                                eq(characteristic), anyBoolean());
-                }
+            if (notifyWithValue) {
+                verify(mMockGattServer, times(0))
+                        .notifyCharacteristicChanged(
+                                eq(device), eq(characteristic), anyBoolean(), any());
+            } else {
+                verify(mMockGattServer, times(0))
+                        .notifyCharacteristicChanged(eq(device), eq(characteristic), anyBoolean());
+            }
         }
 
         if (clearGattMock) {
@@ -330,13 +353,21 @@ public class TbsGattTest {
 
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
-        verifySetValue(characteristic, new ArrayList<>(Arrays.asList("uri2", "uri3")), true,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new ArrayList<>(Arrays.asList("uri2", "uri3")),
+                true,
+                mFirstDevice,
+                true);
 
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
-        verifySetValue(characteristic, new ArrayList<>(Arrays.asList("uri4", "uri5")), false,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new ArrayList<>(Arrays.asList("uri4", "uri5")),
+                false,
+                mFirstDevice,
+                true);
     }
 
     @Test
@@ -348,50 +379,104 @@ public class TbsGattTest {
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
         Map callsMap = new TreeMap<>();
-        callsMap.put(0x0A, TbsCall.create(
-                new BluetoothLeCall(UUID.randomUUID(), "tel:123456789", "John Doe", 0x03, 0x00)));
-        byte[] packetExpected = new byte[] {
-                // First call
-                (byte) 0x10, // Length of this entry (incl. URI length, excl. this length field
-                             // byte)
-                0x0A, // Call index
-                0x03, // Active call state
-                0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
-                      // Bit2:0-provided-by-netw.,1-withheld-by-netw.
-                0x74, 0x65, 0x6c, 0x3a, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
-                // URI: tel:123456789
-        };
-        verifySetValue(characteristic,
-                new Pair, byte[]>(callsMap, packetExpected), true,
-                mFirstDevice, true);
+        callsMap.put(
+                0x0A,
+                TbsCall.create(
+                        new BluetoothLeCall(
+                                UUID.randomUUID(), "tel:123456789", "John Doe", 0x03, 0x00)));
+        byte[] packetExpected =
+                new byte[] {
+                    // First call
+                    (byte) 0x10, // Length of this entry (incl. URI length, excl. this length field
+                    // byte)
+                    0x0A, // Call index
+                    0x03, // Active call state
+                    0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
+                    // Bit2:0-provided-by-netw.,1-withheld-by-netw.
+                    0x74,
+                    0x65,
+                    0x6c,
+                    0x3a,
+                    0x31,
+                    0x32,
+                    0x33,
+                    0x34,
+                    0x35,
+                    0x36,
+                    0x37,
+                    0x38,
+                    0x39,
+                    // URI: tel:123456789
+                };
+        verifySetValue(
+                characteristic,
+                new Pair, byte[]>(callsMap, packetExpected),
+                true,
+                mFirstDevice,
+                true);
 
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
-        callsMap.put(0x0B, TbsCall.create(new BluetoothLeCall(UUID.randomUUID(), "tel:987654321",
-                "Kate", 0x01, BluetoothLeCall.FLAG_OUTGOING_CALL)));
-        packetExpected = new byte[] {
-                // First call
-                (byte) 0x10, // Length of this entry (incl. URI length, excl. this length field
-                             // byte)
-                0x0A, // Call index
-                0x03, // Active call state
-                0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
-                      // Bit2:0-provided-by-netw.,1-withheld-by-netw.
-                0x74, 0x65, 0x6c, 0x3a, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
-                // URI: tel:123456789
-                // Second call
-                (byte) 0x10, // Length of this entry (incl. URI length, excl. this length field
-                             // byte)
-                0x0B, // Call index
-                0x01, // Dialing call state
-                0x01, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
-                      // Bit2:0-provided-by-netw.,1-withheld-by-netw.
-                0x74, 0x65, 0x6c, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31,
-                // URI: tel:987654321
-        };
-        verifySetValue(characteristic,
-                new Pair, byte[]>(callsMap, packetExpected), false,
-                mFirstDevice, true);
+        callsMap.put(
+                0x0B,
+                TbsCall.create(
+                        new BluetoothLeCall(
+                                UUID.randomUUID(),
+                                "tel:987654321",
+                                "Kate",
+                                0x01,
+                                BluetoothLeCall.FLAG_OUTGOING_CALL)));
+        packetExpected =
+                new byte[] {
+                    // First call
+                    (byte) 0x10, // Length of this entry (incl. URI length, excl. this length field
+                    // byte)
+                    0x0A, // Call index
+                    0x03, // Active call state
+                    0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
+                    // Bit2:0-provided-by-netw.,1-withheld-by-netw.
+                    0x74,
+                    0x65,
+                    0x6c,
+                    0x3a,
+                    0x31,
+                    0x32,
+                    0x33,
+                    0x34,
+                    0x35,
+                    0x36,
+                    0x37,
+                    0x38,
+                    0x39,
+                    // URI: tel:123456789
+                    // Second call
+                    (byte) 0x10, // Length of this entry (incl. URI length, excl. this length field
+                    // byte)
+                    0x0B, // Call index
+                    0x01, // Dialing call state
+                    0x01, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
+                    // Bit2:0-provided-by-netw.,1-withheld-by-netw.
+                    0x74,
+                    0x65,
+                    0x6c,
+                    0x3a,
+                    0x39,
+                    0x38,
+                    0x37,
+                    0x36,
+                    0x35,
+                    0x34,
+                    0x33,
+                    0x32,
+                    0x31,
+                    // URI: tel:987654321
+                };
+        verifySetValue(
+                characteristic,
+                new Pair, byte[]>(callsMap, packetExpected),
+                false,
+                mFirstDevice,
+                true);
     }
 
     @Test
@@ -401,18 +486,27 @@ public class TbsGattTest {
 
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
-        verifySetValue(characteristic,
+        verifySetValue(
+                characteristic,
                 new Pair(TbsGatt.STATUS_FLAG_INBAND_RINGTONE_ENABLED, true),
-                true, mFirstDevice, true);
-        verifySetValue(characteristic,
-                new Pair(TbsGatt.STATUS_FLAG_SILENT_MODE_ENABLED, true), true,
-                mFirstDevice, true);
+                true,
+                mFirstDevice,
+                true);
+        verifySetValue(
+                characteristic,
+                new Pair(TbsGatt.STATUS_FLAG_SILENT_MODE_ENABLED, true),
+                true,
+                mFirstDevice,
+                true);
 
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
-        verifySetValue(characteristic,
-                new Pair(TbsGatt.STATUS_FLAG_SILENT_MODE_ENABLED, false), false,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new Pair(TbsGatt.STATUS_FLAG_SILENT_MODE_ENABLED, false),
+                false,
+                mFirstDevice,
+                true);
     }
 
     @Test
@@ -422,34 +516,50 @@ public class TbsGattTest {
 
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
-        byte[] packetExpected = new byte[] {(byte) 0x0A, // Call index
-                0x03, // Active call state
-                0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
-                      // Bit2:0-provided-by-netw.,1-withheld-by-netw.
-        };
+        byte[] packetExpected =
+                new byte[] {
+                    (byte) 0x0A, // Call index
+                    0x03, // Active call state
+                    0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
+                    // Bit2:0-provided-by-netw.,1-withheld-by-netw.
+                };
         Map callsMap = new TreeMap<>();
-        callsMap.put(0x0A, TbsCall.create(
-                new BluetoothLeCall(UUID.randomUUID(), "tel:123456789", "John Doe", 0x03, 0x00)));
-        verifySetValue(characteristic,
-                new Pair, byte[]>(callsMap, packetExpected), true,
-                mFirstDevice, true);
+        callsMap.put(
+                0x0A,
+                TbsCall.create(
+                        new BluetoothLeCall(
+                                UUID.randomUUID(), "tel:123456789", "John Doe", 0x03, 0x00)));
+        verifySetValue(
+                characteristic,
+                new Pair, byte[]>(callsMap, packetExpected),
+                true,
+                mFirstDevice,
+                true);
 
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
-        packetExpected = new byte[] {(byte) 0x0A, // Call index
-                0x03, // Active call state
-                0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
-                      // Bit2:0-provided-by-netw.,1-withheld-by-netw.
-                (byte) 0x0B, // Call index
-                0x04, // Locally Held call state
-                0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
-                      // Bit2:0-provided-by-netw.,1-withheld-by-netw.
-        };
-        callsMap.put(0x0B, TbsCall.create(
-                new BluetoothLeCall(UUID.randomUUID(), "tel:987654321", "Kate", 0x04, 0x00)));
-        verifySetValue(characteristic,
-                new Pair, byte[]>(callsMap, packetExpected), false,
-                mFirstDevice, true);
+        packetExpected =
+                new byte[] {
+                    (byte) 0x0A, // Call index
+                    0x03, // Active call state
+                    0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
+                    // Bit2:0-provided-by-netw.,1-withheld-by-netw.
+                    (byte) 0x0B, // Call index
+                    0x04, // Locally Held call state
+                    0x00, // Bit0:0-incoming,1-outgoing | Bit1:0-not-withheld,1-withheld |
+                    // Bit2:0-provided-by-netw.,1-withheld-by-netw.
+                };
+        callsMap.put(
+                0x0B,
+                TbsCall.create(
+                        new BluetoothLeCall(
+                                UUID.randomUUID(), "tel:987654321", "Kate", 0x04, 0x00)));
+        verifySetValue(
+                characteristic,
+                new Pair, byte[]>(callsMap, packetExpected),
+                false,
+                mFirstDevice,
+                true);
     }
 
     @Test
@@ -465,11 +575,16 @@ public class TbsGattTest {
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
         mTbsGatt.setCallControlPointResult(mFirstDevice, requestedOpcode, callIndex, result);
-        Assert.assertTrue(Arrays.equals(characteristic.getValue(),
-                new byte[] {(byte) (requestedOpcode & 0xff), (byte) (callIndex & 0xff),
-                        (byte) (result & 0xff)}));
-        verify(mMockGattServer, after(2000)).notifyCharacteristicChanged(eq(mFirstDevice),
-                eq(characteristic), eq(false));
+        Assert.assertTrue(
+                Arrays.equals(
+                        characteristic.getValue(),
+                        new byte[] {
+                            (byte) (requestedOpcode & 0xff),
+                            (byte) (callIndex & 0xff),
+                            (byte) (result & 0xff)
+                        }));
+        verify(mMockGattServer, after(2000))
+                .notifyCharacteristicChanged(eq(mFirstDevice), eq(characteristic), eq(false));
         reset(mMockGattServer);
 
         callIndex = 0x02;
@@ -477,11 +592,16 @@ public class TbsGattTest {
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
         mTbsGatt.setCallControlPointResult(mFirstDevice, requestedOpcode, callIndex, result);
-        Assert.assertTrue(Arrays.equals(characteristic.getValue(),
-                new byte[] {(byte) (requestedOpcode & 0xff), (byte) (callIndex & 0xff),
-                        (byte) (result & 0xff)}));
-        verify(mMockGattServer, after(2000).times(0)).notifyCharacteristicChanged(any(), any(),
-                anyBoolean());
+        Assert.assertTrue(
+                Arrays.equals(
+                        characteristic.getValue(),
+                        new byte[] {
+                            (byte) (requestedOpcode & 0xff),
+                            (byte) (callIndex & 0xff),
+                            (byte) (result & 0xff)
+                        }));
+        verify(mMockGattServer, after(2000).times(0))
+                .notifyCharacteristicChanged(any(), any(), anyBoolean());
     }
 
     @Test
@@ -491,18 +611,18 @@ public class TbsGattTest {
                 getCharacteristic(TbsGatt.UUID_TERMINATION_REASON);
 
         // Check with no CCC configured
-        verifySetValue(characteristic, new Pair(0x0A, 0x01), false, mFirstDevice,
-                true);
+        verifySetValue(
+                characteristic, new Pair(0x0A, 0x01), false, mFirstDevice, true);
 
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
-        verifySetValue(characteristic, new Pair(0x0B, 0x02), true, mFirstDevice,
-                true);
+        verifySetValue(
+                characteristic, new Pair(0x0B, 0x02), true, mFirstDevice, true);
 
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
-        verifySetValue(characteristic, new Pair(0x0C, 0x02), false, mFirstDevice,
-                true);
+        verifySetValue(
+                characteristic, new Pair(0x0C, 0x02), false, mFirstDevice, true);
     }
 
     @Test
@@ -511,21 +631,33 @@ public class TbsGattTest {
         BluetoothGattCharacteristic characteristic = getCharacteristic(TbsGatt.UUID_INCOMING_CALL);
 
         // Check with no CCC configured
-        verifySetValue(characteristic, new Pair(0x0A, "tel:123456789"), false,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new Pair(0x0A, "tel:123456789"),
+                false,
+                mFirstDevice,
+                true);
 
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
-        verifySetValue(characteristic, new Pair(0x0A, "tel:987654321"), true,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new Pair(0x0A, "tel:987654321"),
+                true,
+                mFirstDevice,
+                true);
 
         // No incoming call (should not send any notification)
         verifySetValue(characteristic, null, false, mFirstDevice, true);
 
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
-        verifySetValue(characteristic, new Pair(0x0A, "tel:123456789"), false,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new Pair(0x0A, "tel:123456789"),
+                false,
+                mFirstDevice,
+                true);
     }
 
     @Test
@@ -535,21 +667,33 @@ public class TbsGattTest {
                 getCharacteristic(TbsGatt.UUID_CALL_FRIENDLY_NAME);
 
         // Check with no CCC configured
-        verifySetValue(characteristic, new Pair(0x0A, "PersonA"), false,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new Pair(0x0A, "PersonA"),
+                false,
+                mFirstDevice,
+                true);
 
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
-        verifySetValue(characteristic, new Pair(0x0B, "PersonB"), true,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new Pair(0x0B, "PersonB"),
+                true,
+                mFirstDevice,
+                true);
 
         // Clear freindly name (should not send any notification)
         verifySetValue(characteristic, null, false, mFirstDevice, true);
 
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
-        verifySetValue(characteristic, new Pair(0x0C, "PersonC"), false,
-                mFirstDevice, true);
+        verifySetValue(
+                characteristic,
+                new Pair(0x0C, "PersonC"),
+                false,
+                mFirstDevice,
+                true);
     }
 
     @Test
@@ -560,15 +704,20 @@ public class TbsGattTest {
 
         // Call the internal GATT callback as if peer device accepts the call
         byte[] value = new byte[] {0x00 /* opcode */, 0x0A /* argument */};
-        mTbsGatt.mGattServerCallback.onCharacteristicWriteRequest(mFirstDevice, 1, characteristic,
-                false, true, 0, value);
+        mTbsGatt.mGattServerCallback.onCharacteristicWriteRequest(
+                mFirstDevice, 1, characteristic, false, true, 0, value);
 
-        verify(mMockGattServer).sendResponse(eq(mFirstDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0), aryEq(new byte[] {0x00, 0x0A}));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        aryEq(new byte[] {0x00, 0x0A}));
 
         // Verify the higher layer callback call
-        verify(mMockTbsGattCallback).onCallControlPointRequest(eq(mFirstDevice), eq(0x00),
-                aryEq(new byte[] {0x0A}));
+        verify(mMockTbsGattCallback)
+                .onCallControlPointRequest(eq(mFirstDevice), eq(0x00), aryEq(new byte[] {0x0A}));
     }
 
     @Test
@@ -579,11 +728,16 @@ public class TbsGattTest {
 
         // Call the internal GATT callback as if peer device accepts the call
         byte[] value = new byte[] {0x00 /* opcode */};
-        mTbsGatt.mGattServerCallback.onCharacteristicWriteRequest(mFirstDevice, 1, characteristic,
-                false, true, 0, value);
+        mTbsGatt.mGattServerCallback.onCharacteristicWriteRequest(
+                mFirstDevice, 1, characteristic, false, true, 0, value);
 
-        verify(mMockGattServer).sendResponse(eq(mFirstDevice), eq(1),
-                eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH), eq(0), aryEq(new byte[] {0x00}));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH),
+                        eq(0),
+                        aryEq(new byte[] {0x00}));
     }
 
     @Test
@@ -604,15 +758,17 @@ public class TbsGattTest {
         mTbsGatt.setInbandRingtoneFlag(mFirstDevice);
         mTbsGatt.setInbandRingtoneFlag(mFirstDevice);
 
-        verify(mMockGattServer, times(1)).notifyCharacteristicChanged(eq(mFirstDevice),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(1))
+                .notifyCharacteristicChanged(
+                        eq(mFirstDevice), eq(characteristic), eq(false), eq(valueBytes));
 
         reset(mMockGattServer);
         mTbsGatt.setInbandRingtoneFlag(mSecondDevice);
         mTbsGatt.setInbandRingtoneFlag(mSecondDevice);
 
-        verify(mMockGattServer, times(1)).notifyCharacteristicChanged(eq(mSecondDevice),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(1))
+                .notifyCharacteristicChanged(
+                        eq(mSecondDevice), eq(characteristic), eq(false), eq(valueBytes));
     }
 
     @Test
@@ -628,16 +784,17 @@ public class TbsGattTest {
         valueBytes[0] = (byte) (statusFlagValue & 0xFF);
         valueBytes[1] = (byte) ((statusFlagValue >> 8) & 0xFF);
 
-
         mTbsGatt.setInbandRingtoneFlag(mFirstDevice);
-        verify(mMockGattServer, times(1)).notifyCharacteristicChanged(eq(mFirstDevice),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(1))
+                .notifyCharacteristicChanged(
+                        eq(mFirstDevice), eq(characteristic), eq(false), eq(valueBytes));
 
         reset(mMockGattServer);
 
         mTbsGatt.setInbandRingtoneFlag(mSecondDevice);
-        verify(mMockGattServer, times(1)).notifyCharacteristicChanged(eq(mSecondDevice),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(1))
+                .notifyCharacteristicChanged(
+                        eq(mSecondDevice), eq(characteristic), eq(false), eq(valueBytes));
 
         reset(mMockGattServer);
 
@@ -648,14 +805,16 @@ public class TbsGattTest {
 
         mTbsGatt.clearInbandRingtoneFlag(mFirstDevice);
         mTbsGatt.clearInbandRingtoneFlag(mFirstDevice);
-        verify(mMockGattServer, times(1)).notifyCharacteristicChanged(eq(mFirstDevice),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(1))
+                .notifyCharacteristicChanged(
+                        eq(mFirstDevice), eq(characteristic), eq(false), eq(valueBytes));
 
         reset(mMockGattServer);
         mTbsGatt.clearInbandRingtoneFlag(mSecondDevice);
         mTbsGatt.clearInbandRingtoneFlag(mSecondDevice);
-        verify(mMockGattServer, times(1)).notifyCharacteristicChanged(eq(mSecondDevice),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(1))
+                .notifyCharacteristicChanged(
+                        eq(mSecondDevice), eq(characteristic), eq(false), eq(valueBytes));
     }
 
     @Test
@@ -675,26 +834,29 @@ public class TbsGattTest {
         mTbsGatt.setSilentModeFlag();
         mTbsGatt.setSilentModeFlag();
         mTbsGatt.setSilentModeFlag();
-        verify(mMockGattServer, times(2)).notifyCharacteristicChanged(any(),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(2))
+                .notifyCharacteristicChanged(any(), eq(characteristic), eq(false), eq(valueBytes));
 
         reset(mMockGattServer);
 
-        statusFlagValue = TbsGatt.STATUS_FLAG_INBAND_RINGTONE_ENABLED
-                                        | TbsGatt.STATUS_FLAG_SILENT_MODE_ENABLED;
+        statusFlagValue =
+                TbsGatt.STATUS_FLAG_INBAND_RINGTONE_ENABLED
+                        | TbsGatt.STATUS_FLAG_SILENT_MODE_ENABLED;
         valueBytes[0] = (byte) (statusFlagValue & 0xFF);
         valueBytes[1] = (byte) ((statusFlagValue >> 8) & 0xFF);
 
         mTbsGatt.setInbandRingtoneFlag(mFirstDevice);
 
-        verify(mMockGattServer, times(1)).notifyCharacteristicChanged(eq(mFirstDevice),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(1))
+                .notifyCharacteristicChanged(
+                        eq(mFirstDevice), eq(characteristic), eq(false), eq(valueBytes));
 
         reset(mMockGattServer);
         mTbsGatt.setInbandRingtoneFlag(mSecondDevice);
 
-        verify(mMockGattServer, times(1)).notifyCharacteristicChanged(eq(mSecondDevice),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(1))
+                .notifyCharacteristicChanged(
+                        eq(mSecondDevice), eq(characteristic), eq(false), eq(valueBytes));
         reset(mMockGattServer);
 
         statusFlagValue = TbsGatt.STATUS_FLAG_INBAND_RINGTONE_ENABLED;
@@ -705,18 +867,17 @@ public class TbsGattTest {
         mTbsGatt.clearSilentModeFlag();
         mTbsGatt.clearSilentModeFlag();
         mTbsGatt.clearSilentModeFlag();
-        verify(mMockGattServer, times(2)).notifyCharacteristicChanged(any(),
-                                eq(characteristic), eq(false), eq(valueBytes));
+        verify(mMockGattServer, times(2))
+                .notifyCharacteristicChanged(any(), eq(characteristic), eq(false), eq(valueBytes));
     }
 
     @Test
     public void testHandleIsInbandRingtoneEnabled() {
         prepareDefaultService();
-        BluetoothGattCharacteristic characteristic =
-                getCharacteristic(TbsGatt.UUID_STATUS_FLAGS);
+        BluetoothGattCharacteristic characteristic = getCharacteristic(TbsGatt.UUID_STATUS_FLAGS);
 
-        mTbsGatt.mGattServerCallback.onCharacteristicReadRequest(mFirstDevice, 1, 0,
-                characteristic);
+        mTbsGatt.mGattServerCallback.onCharacteristicReadRequest(
+                mFirstDevice, 1, 0, characteristic);
         // Verify the higher layer callback call
         verify(mMockTbsGattCallback).isInbandRingtoneEnabled(eq(mFirstDevice));
     }
@@ -732,25 +893,37 @@ public class TbsGattTest {
 
         // Check with no configuration
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mFirstDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mFirstDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
         reset(mMockGattServer);
 
         // Check with notifications enabled
         configureNotifications(mFirstDevice, characteristic, true);
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mFirstDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mFirstDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
         reset(mMockGattServer);
 
         // Check with notifications disabled
         configureNotifications(mFirstDevice, characteristic, false);
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mFirstDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mFirstDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
     }
 
     @Test
@@ -764,67 +937,94 @@ public class TbsGattTest {
 
         // Check with no configuration
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mFirstDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mFirstDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
 
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mSecondDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mSecondDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mSecondDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
         reset(mMockGattServer);
 
         // Check with notifications enabled for first device
         configureNotifications(mFirstDevice, characteristic, true);
         verifySetValue(characteristic, 4, true, mFirstDevice, true);
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mFirstDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mFirstDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
         reset(mMockGattServer);
 
         // Check if second device is still not subscribed for notifications and will not get it
         verifySetValue(characteristic, 5, false, mSecondDevice, false);
-        verify(mMockGattServer).notifyCharacteristicChanged(eq(mFirstDevice),
-                                eq(characteristic), eq(false));
+        verify(mMockGattServer)
+                .notifyCharacteristicChanged(eq(mFirstDevice), eq(characteristic), eq(false));
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mSecondDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mSecondDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mSecondDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
         reset(mMockGattServer);
 
         // Check with notifications enabled for first and second device
         configureNotifications(mSecondDevice, characteristic, true);
         verifySetValue(characteristic, 6, true, mSecondDevice, false);
-        verify(mMockGattServer).notifyCharacteristicChanged(eq(mFirstDevice),
-                                eq(characteristic), eq(false));
+        verify(mMockGattServer)
+                .notifyCharacteristicChanged(eq(mFirstDevice), eq(characteristic), eq(false));
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mSecondDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mSecondDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mSecondDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE));
         reset(mMockGattServer);
 
         // Disable notification for first device, check if second will get notification
         configureNotifications(mFirstDevice, characteristic, false);
         verifySetValue(characteristic, 7, false, mFirstDevice, false);
-        verify(mMockGattServer).notifyCharacteristicChanged(eq(mSecondDevice),
-                                eq(characteristic), eq(false));
+        verify(mMockGattServer)
+                .notifyCharacteristicChanged(eq(mSecondDevice), eq(characteristic), eq(false));
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mFirstDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mFirstDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
         reset(mMockGattServer);
 
         // Check with notifications disabled of both device
         configureNotifications(mSecondDevice, characteristic, false);
         verifySetValue(characteristic, 4, false, mFirstDevice, false);
-        verify(mMockGattServer, times(0)).notifyCharacteristicChanged(eq(mSecondDevice),
-                                eq(characteristic), eq(false));
+        verify(mMockGattServer, times(0))
+                .notifyCharacteristicChanged(eq(mSecondDevice), eq(characteristic), eq(false));
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mSecondDevice, 1, 0, descriptor);
-        verify(mMockGattServer).sendResponse(eq(mSecondDevice), eq(1),
-                eq(BluetoothGatt.GATT_SUCCESS), eq(0),
-                eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
-
+        verify(mMockGattServer)
+                .sendResponse(
+                        eq(mSecondDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_SUCCESS),
+                        eq(0),
+                        eq(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE));
     }
 
     @Test
@@ -842,8 +1042,12 @@ public class TbsGattTest {
                 mFirstDevice, 1, 0, characteristic);
 
         verify(mMockGattServer)
-                .sendResponse(eq(mFirstDevice), eq(1),
-                        eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), eq(0), any());
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION),
+                        eq(0),
+                        any());
     }
 
     @Test
@@ -919,14 +1123,21 @@ public class TbsGattTest {
                 .when(mMockTbsService)
                 .getDeviceAuthorization(any(BluetoothDevice.class));
 
-        byte[] value = new byte[] {0x00, /* opcode */ 0x0A, /* argument */ };
+        byte[] value =
+                new byte[] {
+                    0x00, /* opcode */ 0x0A, /* argument */
+                };
 
         mTbsGatt.mGattServerCallback.onCharacteristicWriteRequest(
                 mFirstDevice, 1, characteristic, false, true, 0, value);
 
         verify(mMockGattServer)
-                .sendResponse(eq(mFirstDevice), eq(1),
-                        eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), eq(0), any());
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION),
+                        eq(0),
+                        any());
     }
 
     @Test
@@ -940,7 +1151,10 @@ public class TbsGattTest {
                 .when(mMockTbsService)
                 .getDeviceAuthorization(any(BluetoothDevice.class));
 
-        byte[] value = new byte[] {0x00, /* opcode */ 0x0A, /* argument */ };
+        byte[] value =
+                new byte[] {
+                    0x00, /* opcode */ 0x0A, /* argument */
+                };
 
         mTbsGatt.mGattServerCallback.onCharacteristicWriteRequest(
                 mFirstDevice, 1, characteristic, false, true, 0, value);
@@ -964,8 +1178,12 @@ public class TbsGattTest {
         mTbsGatt.mGattServerCallback.onDescriptorReadRequest(mFirstDevice, 1, 0, descriptor);
 
         verify(mMockGattServer)
-                .sendResponse(eq(mFirstDevice), eq(1),
-                        eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), eq(0), any());
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION),
+                        eq(0),
+                        any());
     }
 
     @Test
@@ -999,14 +1217,21 @@ public class TbsGattTest {
                 .when(mMockTbsService)
                 .getDeviceAuthorization(any(BluetoothDevice.class));
 
-        byte[] value = new byte[] {0x00, /* opcode */ 0x0A, /* argument */ };
+        byte[] value =
+                new byte[] {
+                    0x00, /* opcode */ 0x0A, /* argument */
+                };
 
         mTbsGatt.mGattServerCallback.onDescriptorWriteRequest(
                 mFirstDevice, 1, descriptor, false, true, 0, value);
 
         verify(mMockGattServer)
-                .sendResponse(eq(mFirstDevice), eq(1),
-                        eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION), eq(0), any());
+                .sendResponse(
+                        eq(mFirstDevice),
+                        eq(1),
+                        eq(BluetoothGatt.GATT_INSUFFICIENT_AUTHORIZATION),
+                        eq(0),
+                        any());
     }
 
     @Test
@@ -1022,7 +1247,10 @@ public class TbsGattTest {
                 .when(mMockTbsService)
                 .getDeviceAuthorization(any(BluetoothDevice.class));
 
-        byte[] value = new byte[] {0x00, /* opcode */ 0x0A, /* argument */ };
+        byte[] value =
+                new byte[] {
+                    0x00, /* opcode */ 0x0A, /* argument */
+                };
 
         mTbsGatt.mGattServerCallback.onDescriptorWriteRequest(
                 mFirstDevice, 1, descriptor, false, true, 0, value);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGenericTest.java b/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGenericTest.java
index 7d6b512f48e..3944a12b0cd 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGenericTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGenericTest.java
@@ -81,10 +81,17 @@ public class TbsGenericTest {
         getInstrumentation().getUiAutomation().adoptShellPermissionIdentity();
 
         // Default TbsGatt mock behavior
-        doReturn(true).when(mTbsGatt).init(mGtbsCcidCaptor.capture(), mGtbsUciCaptor.capture(),
-                mDefaultGtbsUriSchemesCaptor.capture(), anyBoolean(), anyBoolean(),
-                mDefaultGtbsProviderNameCaptor.capture(), mDefaultGtbsTechnologyCaptor.capture(),
-                mTbsGattCallback.capture());
+        doReturn(true)
+                .when(mTbsGatt)
+                .init(
+                        mGtbsCcidCaptor.capture(),
+                        mGtbsUciCaptor.capture(),
+                        mDefaultGtbsUriSchemesCaptor.capture(),
+                        anyBoolean(),
+                        anyBoolean(),
+                        mDefaultGtbsProviderNameCaptor.capture(),
+                        mDefaultGtbsTechnologyCaptor.capture(),
+                        mTbsGattCallback.capture());
         doReturn(true).when(mTbsGatt).setBearerProviderName(anyString());
         doReturn(true).when(mTbsGatt).setBearerTechnology(anyInt());
         doReturn(true).when(mTbsGatt).setBearerUriSchemesSupportedList(any());
@@ -114,12 +121,21 @@ public class TbsGenericTest {
         String uci = "testUci";
         List uriSchemes = Arrays.asList("tel", "xmpp");
         Integer capabilities =
-                BluetoothLeCallControl.CAPABILITY_HOLD_CALL | BluetoothLeCallControl.CAPABILITY_JOIN_CALLS;
+                BluetoothLeCallControl.CAPABILITY_HOLD_CALL
+                        | BluetoothLeCallControl.CAPABILITY_JOIN_CALLS;
         String providerName = "testProviderName";
         int technology = 0x02;
 
-        assertThat(mTbsGeneric.addBearer("testBearer", mIBluetoothLeCallControlCallback, uci, uriSchemes,
-                capabilities, providerName, technology)).isTrue();
+        assertThat(
+                        mTbsGeneric.addBearer(
+                                "testBearer",
+                                mIBluetoothLeCallControlCallback,
+                                uci,
+                                uriSchemes,
+                                capabilities,
+                                providerName,
+                                technology))
+                .isTrue();
 
         ArgumentCaptor ccidCaptor = ArgumentCaptor.forClass(Integer.class);
         try {
@@ -180,8 +196,13 @@ public class TbsGenericTest {
         Integer ccid = prepareTestBearer();
         reset(mTbsGatt);
 
-        BluetoothLeCall tbsCall = new BluetoothLeCall(UUID.randomUUID(), "tel:987654321",
-                "aFriendlyCaller", BluetoothLeCall.STATE_INCOMING, 0);
+        BluetoothLeCall tbsCall =
+                new BluetoothLeCall(
+                        UUID.randomUUID(),
+                        "tel:987654321",
+                        "aFriendlyCaller",
+                        BluetoothLeCall.STATE_INCOMING,
+                        0);
         mTbsGeneric.callAdded(ccid, tbsCall);
 
         ArgumentCaptor callIndexCaptor = ArgumentCaptor.forClass(Integer.class);
@@ -207,8 +228,13 @@ public class TbsGenericTest {
         reset(mTbsGatt);
 
         UUID callUuid = UUID.randomUUID();
-        BluetoothLeCall tbsCall = new BluetoothLeCall(callUuid, "tel:987654321",
-                "aFriendlyCaller", BluetoothLeCall.STATE_INCOMING, 0);
+        BluetoothLeCall tbsCall =
+                new BluetoothLeCall(
+                        callUuid,
+                        "tel:987654321",
+                        "aFriendlyCaller",
+                        BluetoothLeCall.STATE_INCOMING,
+                        0);
 
         mTbsGeneric.callAdded(ccid, tbsCall);
         ArgumentCaptor callIndexCaptor = ArgumentCaptor.forClass(Integer.class);
@@ -236,8 +262,13 @@ public class TbsGenericTest {
         reset(mTbsGatt);
 
         UUID callUuid = UUID.randomUUID();
-        BluetoothLeCall tbsCall = new BluetoothLeCall(callUuid, "tel:987654321",
-                "aFriendlyCaller", BluetoothLeCall.STATE_INCOMING, 0);
+        BluetoothLeCall tbsCall =
+                new BluetoothLeCall(
+                        callUuid,
+                        "tel:987654321",
+                        "aFriendlyCaller",
+                        BluetoothLeCall.STATE_INCOMING,
+                        0);
 
         mTbsGeneric.callAdded(ccid, tbsCall);
         ArgumentCaptor callIndexCaptor = ArgumentCaptor.forClass(Integer.class);
@@ -273,10 +304,20 @@ public class TbsGenericTest {
         reset(mTbsGatt);
 
         List tbsCalls = new ArrayList<>();
-        tbsCalls.add(new BluetoothLeCall(UUID.randomUUID(), "tel:987654321", "anIncomingCaller",
-                BluetoothLeCall.STATE_INCOMING, 0));
-        tbsCalls.add(new BluetoothLeCall(UUID.randomUUID(), "tel:123456789", "anOutgoingCaller",
-                BluetoothLeCall.STATE_ALERTING, BluetoothLeCall.FLAG_OUTGOING_CALL));
+        tbsCalls.add(
+                new BluetoothLeCall(
+                        UUID.randomUUID(),
+                        "tel:987654321",
+                        "anIncomingCaller",
+                        BluetoothLeCall.STATE_INCOMING,
+                        0));
+        tbsCalls.add(
+                new BluetoothLeCall(
+                        UUID.randomUUID(),
+                        "tel:123456789",
+                        "anOutgoingCaller",
+                        BluetoothLeCall.STATE_ALERTING,
+                        BluetoothLeCall.FLAG_OUTGOING_CALL));
 
         mTbsGeneric.currentCallsList(ccid, tbsCalls);
         ArgumentCaptor currentCallsCaptor = ArgumentCaptor.forClass(Map.class);
@@ -299,8 +340,13 @@ public class TbsGenericTest {
         // Prepare the incoming call
         UUID callUuid = UUID.randomUUID();
         List tbsCalls = new ArrayList<>();
-        tbsCalls.add(new BluetoothLeCall(callUuid, "tel:987654321", "aFriendlyCaller",
-                BluetoothLeCall.STATE_INCOMING, 0));
+        tbsCalls.add(
+                new BluetoothLeCall(
+                        callUuid,
+                        "tel:987654321",
+                        "aFriendlyCaller",
+                        BluetoothLeCall.STATE_INCOMING,
+                        0));
         mTbsGeneric.currentCallsList(ccid, tbsCalls);
 
         ArgumentCaptor currentCallsCaptor = ArgumentCaptor.forClass(Map.class);
@@ -312,14 +358,16 @@ public class TbsGenericTest {
 
         byte args[] = new byte[1];
         args[0] = (byte) (callIndex & 0xFF);
-        mTbsGattCallback.getValue().onCallControlPointRequest(mCurrentDevice,
-                TbsGatt.CALL_CONTROL_POINT_OPCODE_ACCEPT, args);
+        mTbsGattCallback
+                .getValue()
+                .onCallControlPointRequest(
+                        mCurrentDevice, TbsGatt.CALL_CONTROL_POINT_OPCODE_ACCEPT, args);
 
         ArgumentCaptor requestIdCaptor = ArgumentCaptor.forClass(Integer.class);
         ArgumentCaptor callUuidCaptor = ArgumentCaptor.forClass(ParcelUuid.class);
         try {
-            verify(mIBluetoothLeCallControlCallback).onAcceptCall(requestIdCaptor.capture(),
-                    callUuidCaptor.capture());
+            verify(mIBluetoothLeCallControlCallback)
+                    .onAcceptCall(requestIdCaptor.capture(), callUuidCaptor.capture());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -328,13 +376,17 @@ public class TbsGenericTest {
         verify(leAudioService).setActiveDevice(mCurrentDevice);
 
         // Respond with requestComplete...
-        mTbsGeneric.requestResult(ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
+        mTbsGeneric.requestResult(
+                ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
         mTbsGeneric.callStateChanged(ccid, callUuid, BluetoothLeCall.STATE_ACTIVE);
 
         // ..and verify if GTBS control point is updated to notifier the peer about the result
-        verify(mTbsGatt).setCallControlPointResult(eq(mCurrentDevice),
-                eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_ACCEPT), eq(callIndex),
-                eq(BluetoothLeCallControl.RESULT_SUCCESS));
+        verify(mTbsGatt)
+                .setCallControlPointResult(
+                        eq(mCurrentDevice),
+                        eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_ACCEPT),
+                        eq(callIndex),
+                        eq(BluetoothLeCallControl.RESULT_SUCCESS));
     }
 
     @Test
@@ -346,8 +398,13 @@ public class TbsGenericTest {
         // Prepare the incoming call
         UUID callUuid = UUID.randomUUID();
         List tbsCalls = new ArrayList<>();
-        tbsCalls.add(new BluetoothLeCall(callUuid, "tel:987654321", "aFriendlyCaller",
-                BluetoothLeCall.STATE_ACTIVE, 0));
+        tbsCalls.add(
+                new BluetoothLeCall(
+                        callUuid,
+                        "tel:987654321",
+                        "aFriendlyCaller",
+                        BluetoothLeCall.STATE_ACTIVE,
+                        0));
         mTbsGeneric.currentCallsList(ccid, tbsCalls);
 
         ArgumentCaptor currentCallsCaptor = ArgumentCaptor.forClass(Map.class);
@@ -359,27 +416,33 @@ public class TbsGenericTest {
 
         byte args[] = new byte[1];
         args[0] = (byte) (callIndex & 0xFF);
-        mTbsGattCallback.getValue().onCallControlPointRequest(mCurrentDevice,
-                TbsGatt.CALL_CONTROL_POINT_OPCODE_TERMINATE, args);
+        mTbsGattCallback
+                .getValue()
+                .onCallControlPointRequest(
+                        mCurrentDevice, TbsGatt.CALL_CONTROL_POINT_OPCODE_TERMINATE, args);
 
         ArgumentCaptor requestIdCaptor = ArgumentCaptor.forClass(Integer.class);
         ArgumentCaptor callUuidCaptor = ArgumentCaptor.forClass(ParcelUuid.class);
         try {
-            verify(mIBluetoothLeCallControlCallback).onTerminateCall(requestIdCaptor.capture(),
-                    callUuidCaptor.capture());
+            verify(mIBluetoothLeCallControlCallback)
+                    .onTerminateCall(requestIdCaptor.capture(), callUuidCaptor.capture());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
         assertThat(callUuidCaptor.getValue().getUuid()).isEqualTo(callUuid);
 
         // Respond with requestComplete...
-        mTbsGeneric.requestResult(ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
+        mTbsGeneric.requestResult(
+                ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
         mTbsGeneric.callRemoved(ccid, callUuid, 0x01);
 
         // ..and verify if GTBS control point is updated to notifier the peer about the result
-        verify(mTbsGatt).setCallControlPointResult(eq(mCurrentDevice),
-                eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_TERMINATE), eq(callIndex),
-                eq(BluetoothLeCallControl.RESULT_SUCCESS));
+        verify(mTbsGatt)
+                .setCallControlPointResult(
+                        eq(mCurrentDevice),
+                        eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_TERMINATE),
+                        eq(callIndex),
+                        eq(BluetoothLeCallControl.RESULT_SUCCESS));
     }
 
     @Test
@@ -391,8 +454,13 @@ public class TbsGenericTest {
         // Prepare the incoming call
         UUID callUuid = UUID.randomUUID();
         List tbsCalls = new ArrayList<>();
-        tbsCalls.add(new BluetoothLeCall(callUuid, "tel:987654321", "aFriendlyCaller",
-                BluetoothLeCall.STATE_ACTIVE, 0));
+        tbsCalls.add(
+                new BluetoothLeCall(
+                        callUuid,
+                        "tel:987654321",
+                        "aFriendlyCaller",
+                        BluetoothLeCall.STATE_ACTIVE,
+                        0));
         mTbsGeneric.currentCallsList(ccid, tbsCalls);
 
         ArgumentCaptor currentCallsCaptor = ArgumentCaptor.forClass(Map.class);
@@ -404,27 +472,33 @@ public class TbsGenericTest {
 
         byte args[] = new byte[1];
         args[0] = (byte) (callIndex & 0xFF);
-        mTbsGattCallback.getValue().onCallControlPointRequest(mCurrentDevice,
-                TbsGatt.CALL_CONTROL_POINT_OPCODE_LOCAL_HOLD, args);
+        mTbsGattCallback
+                .getValue()
+                .onCallControlPointRequest(
+                        mCurrentDevice, TbsGatt.CALL_CONTROL_POINT_OPCODE_LOCAL_HOLD, args);
 
         ArgumentCaptor requestIdCaptor = ArgumentCaptor.forClass(Integer.class);
         ArgumentCaptor callUuidCaptor = ArgumentCaptor.forClass(ParcelUuid.class);
         try {
-            verify(mIBluetoothLeCallControlCallback).onHoldCall(requestIdCaptor.capture(),
-                    callUuidCaptor.capture());
+            verify(mIBluetoothLeCallControlCallback)
+                    .onHoldCall(requestIdCaptor.capture(), callUuidCaptor.capture());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
         assertThat(callUuidCaptor.getValue().getUuid()).isEqualTo(callUuid);
 
         // Respond with requestComplete...
-        mTbsGeneric.requestResult(ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
+        mTbsGeneric.requestResult(
+                ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
         mTbsGeneric.callStateChanged(ccid, callUuid, BluetoothLeCall.STATE_LOCALLY_HELD);
 
         // ..and verify if GTBS control point is updated to notifier the peer about the result
-        verify(mTbsGatt).setCallControlPointResult(eq(mCurrentDevice),
-                eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_LOCAL_HOLD), eq(callIndex),
-                eq(BluetoothLeCallControl.RESULT_SUCCESS));
+        verify(mTbsGatt)
+                .setCallControlPointResult(
+                        eq(mCurrentDevice),
+                        eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_LOCAL_HOLD),
+                        eq(callIndex),
+                        eq(BluetoothLeCallControl.RESULT_SUCCESS));
     }
 
     @Test
@@ -436,8 +510,13 @@ public class TbsGenericTest {
         // Prepare the incoming call
         UUID callUuid = UUID.randomUUID();
         List tbsCalls = new ArrayList<>();
-        tbsCalls.add(new BluetoothLeCall(callUuid, "tel:987654321", "aFriendlyCaller",
-                BluetoothLeCall.STATE_LOCALLY_HELD, 0));
+        tbsCalls.add(
+                new BluetoothLeCall(
+                        callUuid,
+                        "tel:987654321",
+                        "aFriendlyCaller",
+                        BluetoothLeCall.STATE_LOCALLY_HELD,
+                        0));
         mTbsGeneric.currentCallsList(ccid, tbsCalls);
 
         ArgumentCaptor currentCallsCaptor = ArgumentCaptor.forClass(Map.class);
@@ -449,27 +528,33 @@ public class TbsGenericTest {
 
         byte args[] = new byte[1];
         args[0] = (byte) (callIndex & 0xFF);
-        mTbsGattCallback.getValue().onCallControlPointRequest(mCurrentDevice,
-                TbsGatt.CALL_CONTROL_POINT_OPCODE_LOCAL_RETRIEVE, args);
+        mTbsGattCallback
+                .getValue()
+                .onCallControlPointRequest(
+                        mCurrentDevice, TbsGatt.CALL_CONTROL_POINT_OPCODE_LOCAL_RETRIEVE, args);
 
         ArgumentCaptor requestIdCaptor = ArgumentCaptor.forClass(Integer.class);
         ArgumentCaptor callUuidCaptor = ArgumentCaptor.forClass(ParcelUuid.class);
         try {
-            verify(mIBluetoothLeCallControlCallback).onUnholdCall(requestIdCaptor.capture(),
-                    callUuidCaptor.capture());
+            verify(mIBluetoothLeCallControlCallback)
+                    .onUnholdCall(requestIdCaptor.capture(), callUuidCaptor.capture());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
         assertThat(callUuidCaptor.getValue().getUuid()).isEqualTo(callUuid);
 
         // Respond with requestComplete...
-        mTbsGeneric.requestResult(ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
+        mTbsGeneric.requestResult(
+                ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
         mTbsGeneric.callStateChanged(ccid, callUuid, BluetoothLeCall.STATE_ACTIVE);
 
         // ..and verify if GTBS control point is updated to notifier the peer about the result
-        verify(mTbsGatt).setCallControlPointResult(eq(mCurrentDevice),
-                eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_LOCAL_RETRIEVE), eq(callIndex),
-                eq(BluetoothLeCallControl.RESULT_SUCCESS));
+        verify(mTbsGatt)
+                .setCallControlPointResult(
+                        eq(mCurrentDevice),
+                        eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_LOCAL_RETRIEVE),
+                        eq(callIndex),
+                        eq(BluetoothLeCallControl.RESULT_SUCCESS));
     }
 
     @Test
@@ -483,14 +568,18 @@ public class TbsGenericTest {
 
         // Act as if peer originates a call via Gtbs
         String uri = "xmpp:123456789";
-        mTbsGattCallback.getValue().onCallControlPointRequest(mCurrentDevice,
-                TbsGatt.CALL_CONTROL_POINT_OPCODE_ORIGINATE, uri.getBytes());
+        mTbsGattCallback
+                .getValue()
+                .onCallControlPointRequest(
+                        mCurrentDevice,
+                        TbsGatt.CALL_CONTROL_POINT_OPCODE_ORIGINATE,
+                        uri.getBytes());
 
         ArgumentCaptor requestIdCaptor = ArgumentCaptor.forClass(Integer.class);
         ArgumentCaptor callUuidCaptor = ArgumentCaptor.forClass(ParcelUuid.class);
         try {
-            verify(mIBluetoothLeCallControlCallback).onPlaceCall(requestIdCaptor.capture(),
-                    callUuidCaptor.capture(), eq(uri));
+            verify(mIBluetoothLeCallControlCallback)
+                    .onPlaceCall(requestIdCaptor.capture(), callUuidCaptor.capture(), eq(uri));
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -499,15 +588,24 @@ public class TbsGenericTest {
         verify(leAudioService).setActiveDevice(mCurrentDevice);
 
         // Respond with requestComplete...
-        mTbsGeneric.requestResult(ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
-        mTbsGeneric.callAdded(ccid,
-                new BluetoothLeCall(callUuidCaptor.getValue().getUuid(), uri, "anOutgoingCaller",
-                        BluetoothLeCall.STATE_ALERTING, BluetoothLeCall.FLAG_OUTGOING_CALL));
+        mTbsGeneric.requestResult(
+                ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
+        mTbsGeneric.callAdded(
+                ccid,
+                new BluetoothLeCall(
+                        callUuidCaptor.getValue().getUuid(),
+                        uri,
+                        "anOutgoingCaller",
+                        BluetoothLeCall.STATE_ALERTING,
+                        BluetoothLeCall.FLAG_OUTGOING_CALL));
 
         // ..and verify if GTBS control point is updated to notifier the peer about the result
-        verify(mTbsGatt).setCallControlPointResult(eq(mCurrentDevice),
-                eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_ORIGINATE), anyInt(),
-                eq(BluetoothLeCallControl.RESULT_SUCCESS));
+        verify(mTbsGatt)
+                .setCallControlPointResult(
+                        eq(mCurrentDevice),
+                        eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_ORIGINATE),
+                        anyInt(),
+                        eq(BluetoothLeCallControl.RESULT_SUCCESS));
     }
 
     @Test
@@ -519,10 +617,20 @@ public class TbsGenericTest {
         // Prepare the incoming call
         List callUuids = Arrays.asList(UUID.randomUUID(), UUID.randomUUID());
         List tbsCalls = new ArrayList<>();
-        tbsCalls.add(new BluetoothLeCall(callUuids.get(0), "tel:987654321", "aFriendlyCaller",
-                BluetoothLeCall.STATE_LOCALLY_HELD, 0));
-        tbsCalls.add(new BluetoothLeCall(callUuids.get(1), "tel:123456789", "a2ndFriendlyCaller",
-                BluetoothLeCall.STATE_ACTIVE, 0));
+        tbsCalls.add(
+                new BluetoothLeCall(
+                        callUuids.get(0),
+                        "tel:987654321",
+                        "aFriendlyCaller",
+                        BluetoothLeCall.STATE_LOCALLY_HELD,
+                        0));
+        tbsCalls.add(
+                new BluetoothLeCall(
+                        callUuids.get(1),
+                        "tel:123456789",
+                        "a2ndFriendlyCaller",
+                        BluetoothLeCall.STATE_ACTIVE,
+                        0));
         mTbsGeneric.currentCallsList(ccid, tbsCalls);
 
         ArgumentCaptor currentCallsCaptor = ArgumentCaptor.forClass(Map.class);
@@ -536,14 +644,16 @@ public class TbsGenericTest {
         for (Integer callIndex : capturedCurrentCalls.keySet()) {
             args[i++] = (byte) (callIndex & 0xFF);
         }
-        mTbsGattCallback.getValue().onCallControlPointRequest(mCurrentDevice,
-                TbsGatt.CALL_CONTROL_POINT_OPCODE_JOIN, args);
+        mTbsGattCallback
+                .getValue()
+                .onCallControlPointRequest(
+                        mCurrentDevice, TbsGatt.CALL_CONTROL_POINT_OPCODE_JOIN, args);
 
         ArgumentCaptor requestIdCaptor = ArgumentCaptor.forClass(Integer.class);
         ArgumentCaptor> callUuidCaptor = ArgumentCaptor.forClass(List.class);
         try {
-            verify(mIBluetoothLeCallControlCallback).onJoinCalls(requestIdCaptor.capture(),
-                    callUuidCaptor.capture());
+            verify(mIBluetoothLeCallControlCallback)
+                    .onJoinCalls(requestIdCaptor.capture(), callUuidCaptor.capture());
         } catch (RemoteException e) {
             throw e.rethrowFromSystemServer();
         }
@@ -554,12 +664,16 @@ public class TbsGenericTest {
         }
 
         // // Respond with requestComplete...
-        mTbsGeneric.requestResult(ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
+        mTbsGeneric.requestResult(
+                ccid, requestIdCaptor.getValue(), BluetoothLeCallControl.RESULT_SUCCESS);
         mTbsGeneric.callStateChanged(ccid, callUuids.get(0), BluetoothLeCall.STATE_ACTIVE);
 
         // ..and verify if GTBS control point is updated to notifier the peer about the result
-        verify(mTbsGatt).setCallControlPointResult(eq(mCurrentDevice),
-                eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_JOIN), anyInt(),
-                eq(BluetoothLeCallControl.RESULT_SUCCESS));
+        verify(mTbsGatt)
+                .setCallControlPointResult(
+                        eq(mCurrentDevice),
+                        eq(TbsGatt.CALL_CONTROL_POINT_OPCODE_JOIN),
+                        anyInt(),
+                        eq(BluetoothLeCallControl.RESULT_SUCCESS));
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothCallTest.java b/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothCallTest.java
index e06e2623b56..884b914a4f9 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothCallTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothCallTest.java
@@ -80,8 +80,8 @@ public class BluetoothCallTest {
 
     @Test
     public void getRemainingPostDialSequence_whenInnerCallIsNull_throwsNPE() {
-        assertThrows(NullPointerException.class,
-                () -> mBluetoothCall.getRemainingPostDialSequence());
+        assertThrows(
+                NullPointerException.class, () -> mBluetoothCall.getRemainingPostDialSequence());
     }
 
     @Test
@@ -116,13 +116,14 @@ public class BluetoothCallTest {
 
     @Test
     public void enterBackgroundAudioProcessing_whenInnerCallIsNull_throwsNPE() {
-        assertThrows(NullPointerException.class,
-                () -> mBluetoothCall.enterBackgroundAudioProcessing());
+        assertThrows(
+                NullPointerException.class, () -> mBluetoothCall.enterBackgroundAudioProcessing());
     }
 
     @Test
     public void exitBackgroundAudioProcessing_whenInnerCallIsNull_throwsNPE() {
-        assertThrows(NullPointerException.class,
+        assertThrows(
+                NullPointerException.class,
                 () -> mBluetoothCall.exitBackgroundAudioProcessing(true));
     }
 
@@ -143,8 +144,8 @@ public class BluetoothCallTest {
 
     @Test
     public void phoneAccountSelected_whenInnerCallIsNull_throwsNPE() {
-        assertThrows(NullPointerException.class,
-                () -> mBluetoothCall.phoneAccountSelected(null, true));
+        assertThrows(
+                NullPointerException.class, () -> mBluetoothCall.phoneAccountSelected(null, true));
     }
 
     @Test
@@ -288,7 +289,8 @@ public class BluetoothCallTest {
 
     @Test
     public void getGenericConferenceActiveChildCallId_whenInnerCallIsNull_throwsNPE() {
-        assertThrows(NullPointerException.class,
+        assertThrows(
+                NullPointerException.class,
                 () -> mBluetoothCall.getGenericConferenceActiveChildCallId());
     }
 
@@ -366,8 +368,8 @@ public class BluetoothCallTest {
 
     @Test
     public void wasConferencePreviouslyMerged_whenInnerCallIsNull_throwsNPE() {
-        assertThrows(NullPointerException.class,
-                () -> mBluetoothCall.wasConferencePreviouslyMerged());
+        assertThrows(
+                NullPointerException.class, () -> mBluetoothCall.wasConferencePreviouslyMerged());
     }
 
     @Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java
index 060fdee686e..855bf0e81ec 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java
@@ -69,9 +69,7 @@ import java.util.List;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 
-/**
- * Tests for {@link BluetoothInCallService}
- */
+/** Tests for {@link BluetoothInCallService} */
 @MediumTest
 @RunWith(AndroidJUnit4.class)
 public class BluetoothInCallServiceTest {
@@ -99,22 +97,17 @@ public class BluetoothInCallServiceTest {
     private static final int CHLD_TYPE_ADDHELDTOCONF = 3;
 
     private TestableBluetoothInCallService mBluetoothInCallService;
+
     @Rule
-    public final ServiceTestRule mServiceRule
-            = ServiceTestRule.withTimeout(1, TimeUnit.SECONDS);
+    public final ServiceTestRule mServiceRule = ServiceTestRule.withTimeout(1, TimeUnit.SECONDS);
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private BluetoothHeadsetProxy mMockBluetoothHeadset;
-    @Mock
-    private BluetoothLeCallControlProxy mMockBluetoothLeCallControl;
-    @Mock
-    private BluetoothInCallService.CallInfo mMockCallInfo;
-    @Mock
-    private TelephonyManager mMockTelephonyManager;
-    @Mock
-    private Context mContext = ApplicationProvider.getApplicationContext();
+    @Mock private BluetoothHeadsetProxy mMockBluetoothHeadset;
+    @Mock private BluetoothLeCallControlProxy mMockBluetoothLeCallControl;
+    @Mock private BluetoothInCallService.CallInfo mMockCallInfo;
+    @Mock private TelephonyManager mMockTelephonyManager;
+    @Mock private Context mContext = ApplicationProvider.getApplicationContext();
 
     public class TestableBluetoothInCallService extends BluetoothInCallService {
         @Override
@@ -129,8 +122,7 @@ public class BluetoothInCallServiceTest {
         }
 
         @Override
-        protected void enforceModifyPermission() {
-        }
+        protected void enforceModifyPermission() {}
 
         protected void setOnCreateCalled(boolean called) {
             mOnCreateCalled = called;
@@ -139,11 +131,14 @@ public class BluetoothInCallServiceTest {
 
     @Before
     public void setUp() throws Exception {
-        InstrumentationRegistry.getInstrumentation().getUiAutomation().adoptShellPermissionIdentity();
+        InstrumentationRegistry.getInstrumentation()
+                .getUiAutomation()
+                .adoptShellPermissionIdentity();
 
         // Create the service Intent.
         Intent serviceIntent =
-                new Intent(ApplicationProvider.getApplicationContext(),
+                new Intent(
+                        ApplicationProvider.getApplicationContext(),
                         TestableBluetoothInCallService.class);
         // Bind the service
         mServiceRule.bindService(serviceIntent);
@@ -151,8 +146,7 @@ public class BluetoothInCallServiceTest {
         // Ensure initialization does not actually try to access any of the CallsManager fields.
         // This also works to return null if it is not overwritten later in the test.
         doReturn(null).when(mMockCallInfo).getActiveCall();
-        doReturn(null).when(mMockCallInfo)
-                .getRingingOrSimulatedRingingCall();
+        doReturn(null).when(mMockCallInfo).getRingingOrSimulatedRingingCall();
         doReturn(null).when(mMockCallInfo).getHeldCall();
         doReturn(null).when(mMockCallInfo).getOutgoingCall();
         doReturn(0).when(mMockCallInfo).getNumHeldCalls();
@@ -260,8 +254,7 @@ public class BluetoothInCallServiceTest {
     public void testGetSubscriberNumberFallbackToTelephony() throws Exception {
         String fakeNumber = "8675309";
         when(mMockCallInfo.getBestPhoneAccount()).thenReturn(null);
-        when(mMockTelephonyManager.getLine1Number())
-                .thenReturn(fakeNumber);
+        when(mMockTelephonyManager.getLine1Number()).thenReturn(fakeNumber);
         mBluetoothInCallService.mTelephonyManager = mMockTelephonyManager;
 
         String subscriberNumber = mBluetoothInCallService.getSubscriberNumber();
@@ -282,8 +275,15 @@ public class BluetoothInCallServiceTest {
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
 
-        verify(mMockBluetoothHeadset).clccResponse(eq(1), eq(0), eq(0), eq(0), eq(false),
-                eq("555000"), eq(PhoneNumberUtils.TOA_Unknown));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        eq(1),
+                        eq(0),
+                        eq(0),
+                        eq(0),
+                        eq(false),
+                        eq("555000"),
+                        eq(PhoneNumberUtils.TOA_Unknown));
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
     }
 
@@ -304,15 +304,17 @@ public class BluetoothInCallServiceTest {
                 40, // int retransmissionCount
                 50, // int packetsNotReceiveCount
                 60 // int negativeAcknowledgementCount
-        );
+                );
 
         ArgumentCaptor bundleCaptor = ArgumentCaptor.forClass(Bundle.class);
-        verify(activeCall).sendCallEvent(
-                eq(BluetoothCallQualityReport.EVENT_BLUETOOTH_CALL_QUALITY_REPORT),
-                bundleCaptor.capture());
+        verify(activeCall)
+                .sendCallEvent(
+                        eq(BluetoothCallQualityReport.EVENT_BLUETOOTH_CALL_QUALITY_REPORT),
+                        bundleCaptor.capture());
         Bundle bundle = bundleCaptor.getValue();
-        BluetoothCallQualityReport report = (BluetoothCallQualityReport) bundle.get(
-                BluetoothCallQualityReport.EXTRA_BLUETOOTH_CALL_QUALITY_REPORT);
+        BluetoothCallQualityReport report =
+                (BluetoothCallQualityReport)
+                        bundle.get(BluetoothCallQualityReport.EXTRA_BLUETOOTH_CALL_QUALITY_REPORT);
         Assert.assertEquals(10, report.getSentTimestampMillis());
         Assert.assertEquals(20, report.getRssiDbm());
         Assert.assertEquals(30, report.getSnrDb());
@@ -338,8 +340,15 @@ public class BluetoothInCallServiceTest {
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
 
-        verify(mMockBluetoothHeadset, never()).clccResponse(eq(1), eq(0), eq(0), eq(0), eq(false),
-                eq("555000"), eq(PhoneNumberUtils.TOA_Unknown));
+        verify(mMockBluetoothHeadset, never())
+                .clccResponse(
+                        eq(1),
+                        eq(0),
+                        eq(0),
+                        eq(0),
+                        eq(false),
+                        eq("555000"),
+                        eq(PhoneNumberUtils.TOA_Unknown));
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
     }
 
@@ -365,46 +374,49 @@ public class BluetoothInCallServiceTest {
         when(confCall2.getState()).thenReturn(Call.STATE_ACTIVE);
         when(confCall1.isIncoming()).thenReturn(false);
         when(confCall2.isIncoming()).thenReturn(true);
-        when(confCall1.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
-        when(confCall2.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
+        when(confCall1.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
+        when(confCall2.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
         addCallCapability(parentCall, Connection.CAPABILITY_MERGE_CONFERENCE);
         addCallCapability(parentCall, Connection.CAPABILITY_SWAP_CONFERENCE);
         removeCallCapability(parentCall, Connection.CAPABILITY_CONFERENCE_HAS_NO_CHILDREN);
         Integer confCall1Id = confCall1.getId();
-        when(parentCall.getGenericConferenceActiveChildCallId())
-                .thenReturn(confCall1Id);
+        when(parentCall.getGenericConferenceActiveChildCallId()).thenReturn(confCall1Id);
         when(parentCall.isConference()).thenReturn(true);
-        List childrenIds = Arrays.asList(confCall1.getId(),
-                confCall2.getId());
+        List childrenIds = Arrays.asList(confCall1.getId(), confCall2.getId());
         when(parentCall.getChildrenIds()).thenReturn(childrenIds);
-        //Add links from child calls to parent
+        // Add links from child calls to parent
         Integer parentId = parentCall.getId();
         when(confCall1.getParentId()).thenReturn(parentId);
         when(confCall2.getParentId()).thenReturn(parentId);
 
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.queryPhoneState();
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(1), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
 
         when(parentCall.wasConferencePreviouslyMerged()).thenReturn(true);
         List children =
                 mBluetoothInCallService.getBluetoothCallsByIds(parentCall.getChildrenIds());
-        mBluetoothInCallService.getCallback(parentCall)
-                .onChildrenChanged(parentCall, children);
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(0), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        mBluetoothInCallService.getCallback(parentCall).onChildrenChanged(parentCall, children);
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
 
         when(mMockCallInfo.getHeldCall()).thenReturn(null);
         // Spurious BluetoothCall to onIsConferencedChanged.
-        mBluetoothInCallService.getCallback(parentCall)
-                .onChildrenChanged(parentCall, children);
+        mBluetoothInCallService.getCallback(parentCall).onChildrenChanged(parentCall, children);
         // Make sure the BluetoothCall has only occurred collectively 2 times (not on the third)
-        verify(mMockBluetoothHeadset, times(2)).phoneStateChanged(any(int.class),
-                any(int.class), any(int.class), nullable(String.class), any(int.class),
-                nullable(String.class));
+        verify(mMockBluetoothHeadset, times(2))
+                .phoneStateChanged(
+                        any(int.class),
+                        any(int.class),
+                        any(int.class),
+                        nullable(String.class),
+                        any(int.class),
+                        nullable(String.class));
     }
 
     @Test
@@ -429,10 +441,10 @@ public class BluetoothInCallServiceTest {
         when(heldCall.getState()).thenReturn(Call.STATE_ACTIVE);
         when(foregroundCall.isIncoming()).thenReturn(false);
         when(heldCall.isIncoming()).thenReturn(true);
-        when(foregroundCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
-        when(heldCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0002")));
+        when(foregroundCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
+        when(heldCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0002")));
         addCallCapability(parentCall, Connection.CAPABILITY_MERGE_CONFERENCE);
         addCallCapability(parentCall, Connection.CAPABILITY_SWAP_CONFERENCE);
         removeCallCapability(parentCall, Connection.CAPABILITY_CONFERENCE_HAS_NO_CHILDREN);
@@ -440,10 +452,9 @@ public class BluetoothInCallServiceTest {
         Integer foregroundCallId = foregroundCall.getId();
         when(parentCall.getGenericConferenceActiveChildCallId()).thenReturn(foregroundCallId);
         when(parentCall.isConference()).thenReturn(true);
-        List childrenIds = Arrays.asList(foregroundCall.getId(),
-                heldCall.getId());
+        List childrenIds = Arrays.asList(foregroundCall.getId(), heldCall.getId());
         when(parentCall.getChildrenIds()).thenReturn(childrenIds);
-        //Add links from child calls to parent
+        // Add links from child calls to parent
         Integer parentId = parentCall.getId();
         when(foregroundCall.getParentId()).thenReturn(parentId);
         when(heldCall.getParentId()).thenReturn(parentId);
@@ -452,10 +463,24 @@ public class BluetoothInCallServiceTest {
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
 
-        verify(mMockBluetoothHeadset).clccResponse(eq(1), eq(0), eq(CALL_STATE_ACTIVE), eq(0),
-                eq(false), eq("5550001"), eq(PhoneNumberUtils.TOA_Unknown));
-        verify(mMockBluetoothHeadset).clccResponse(eq(2), eq(1), eq(CALL_STATE_HELD), eq(0),
-                eq(false), eq("5550002"), eq(PhoneNumberUtils.TOA_Unknown));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        eq(1),
+                        eq(0),
+                        eq(CALL_STATE_ACTIVE),
+                        eq(0),
+                        eq(false),
+                        eq("5550001"),
+                        eq(PhoneNumberUtils.TOA_Unknown));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        eq(2),
+                        eq(1),
+                        eq(CALL_STATE_HELD),
+                        eq(0),
+                        eq(false),
+                        eq("5550002"),
+                        eq(PhoneNumberUtils.TOA_Unknown));
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
     }
 
@@ -481,19 +506,18 @@ public class BluetoothInCallServiceTest {
         when(confCall2.getState()).thenReturn(Call.STATE_ACTIVE);
         when(confCall1.isIncoming()).thenReturn(false);
         when(confCall2.isIncoming()).thenReturn(true);
-        when(confCall1.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
-        when(confCall2.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
+        when(confCall1.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
+        when(confCall2.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
         removeCallCapability(parentCall, Connection.CAPABILITY_MERGE_CONFERENCE);
         removeCallCapability(parentCall, Connection.CAPABILITY_CONFERENCE_HAS_NO_CHILDREN);
         when(parentCall.wasConferencePreviouslyMerged()).thenReturn(true);
-        //when(parentCall.getConferenceLevelActiveCall()).thenReturn(confCall1);
+        // when(parentCall.getConferenceLevelActiveCall()).thenReturn(confCall1);
         when(parentCall.isConference()).thenReturn(true);
-        List childrenIds = Arrays.asList(confCall1.getId(),
-                confCall2.getId());
+        List childrenIds = Arrays.asList(confCall1.getId(), confCall2.getId());
         when(parentCall.getChildrenIds()).thenReturn(childrenIds);
-        //Add links from child calls to parent
+        // Add links from child calls to parent
         Integer parentId = parentCall.getId();
         when(confCall1.getParentId()).thenReturn(parentId);
         when(confCall2.getParentId()).thenReturn(parentId);
@@ -502,10 +526,24 @@ public class BluetoothInCallServiceTest {
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
 
-        verify(mMockBluetoothHeadset).clccResponse(eq(1), eq(0), eq(CALL_STATE_ACTIVE), eq(0),
-                eq(true), eq("5550000"), eq(PhoneNumberUtils.TOA_Unknown));
-        verify(mMockBluetoothHeadset).clccResponse(eq(2), eq(1), eq(CALL_STATE_ACTIVE), eq(0),
-                eq(true), eq("5550001"), eq(PhoneNumberUtils.TOA_Unknown));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        eq(1),
+                        eq(0),
+                        eq(CALL_STATE_ACTIVE),
+                        eq(0),
+                        eq(true),
+                        eq("5550000"),
+                        eq(PhoneNumberUtils.TOA_Unknown));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        eq(2),
+                        eq(1),
+                        eq(CALL_STATE_ACTIVE),
+                        eq(0),
+                        eq(true),
+                        eq("5550001"),
+                        eq(PhoneNumberUtils.TOA_Unknown));
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
     }
 
@@ -521,19 +559,33 @@ public class BluetoothInCallServiceTest {
         mBluetoothInCallService.onCallAdded(waitingCall);
 
         when(waitingCall.isIncoming()).thenReturn(true);
-        when(waitingCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
+        when(waitingCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
         when(waitingCall.getState()).thenReturn(Call.STATE_RINGING);
         when(waitingCall.isConference()).thenReturn(false);
         when(waitingCall.getHandle()).thenReturn(Uri.parse("tel:555-0000"));
 
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
-        verify(mMockBluetoothHeadset).clccResponse(1, 1, CALL_STATE_WAITING, 0, false,
-                "5550000", PhoneNumberUtils.TOA_Unknown);
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        1,
+                        1,
+                        CALL_STATE_WAITING,
+                        0,
+                        false,
+                        "5550000",
+                        PhoneNumberUtils.TOA_Unknown);
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
-        verify(mMockBluetoothHeadset, times(2)).clccResponse(anyInt(),
-                anyInt(), anyInt(), anyInt(), anyBoolean(), nullable(String.class), anyInt());
+        verify(mMockBluetoothHeadset, times(2))
+                .clccResponse(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyBoolean(),
+                        nullable(String.class),
+                        anyInt());
     }
 
     @Test
@@ -550,8 +602,15 @@ public class BluetoothInCallServiceTest {
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
-        verify(mMockBluetoothHeadset, times(1)).clccResponse(anyInt(),
-                anyInt(), anyInt(), anyInt(), anyBoolean(), nullable(String.class), anyInt());
+        verify(mMockBluetoothHeadset, times(1))
+                .clccResponse(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyBoolean(),
+                        nullable(String.class),
+                        anyInt());
     }
 
     @Test
@@ -613,16 +672,30 @@ public class BluetoothInCallServiceTest {
         when(ringingCall.isIncoming()).thenReturn(true);
         when(ringingCall.isConference()).thenReturn(false);
         when(ringingCall.getHandle()).thenReturn(Uri.parse("tel:555-0000"));
-        when(ringingCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
+        when(ringingCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
 
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
-        verify(mMockBluetoothHeadset).clccResponse(1, 1, CALL_STATE_INCOMING, 0, false,
-                "5550000", PhoneNumberUtils.TOA_Unknown);
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        1,
+                        1,
+                        CALL_STATE_INCOMING,
+                        0,
+                        false,
+                        "5550000",
+                        PhoneNumberUtils.TOA_Unknown);
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
-        verify(mMockBluetoothHeadset, times(2)).clccResponse(anyInt(),
-                anyInt(), anyInt(), anyInt(), anyBoolean(), nullable(String.class), anyInt());
+        verify(mMockBluetoothHeadset, times(2))
+                .clccResponse(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyBoolean(),
+                        nullable(String.class),
+                        anyInt());
     }
 
     @Test
@@ -637,13 +710,20 @@ public class BluetoothInCallServiceTest {
         when(ringingCall.isIncoming()).thenReturn(true);
         when(ringingCall.isConference()).thenReturn(false);
         when(ringingCall.getHandle()).thenReturn(Uri.parse("tel:5550000"));
-        when(ringingCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:5550000")));
+        when(ringingCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:5550000")));
 
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
-        verify(mMockBluetoothHeadset).clccResponse(1, 1, CALL_STATE_INCOMING, 0, false,
-                "5550000", PhoneNumberUtils.TOA_Unknown);
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        1,
+                        1,
+                        CALL_STATE_INCOMING,
+                        0,
+                        false,
+                        "5550000",
+                        PhoneNumberUtils.TOA_Unknown);
 
         // Test Caching of old BluetoothCall indices in clcc
         when(ringingCall.getState()).thenReturn(Call.STATE_ACTIVE);
@@ -655,14 +735,16 @@ public class BluetoothInCallServiceTest {
         when(newHoldingCall.isIncoming()).thenReturn(true);
         when(newHoldingCall.isConference()).thenReturn(false);
         when(newHoldingCall.getHandle()).thenReturn(Uri.parse("tel:555-0001"));
-        when(newHoldingCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
+        when(newHoldingCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
 
         mBluetoothInCallService.listCurrentCalls();
-        verify(mMockBluetoothHeadset).clccResponse(1, 1, CALL_STATE_ACTIVE, 0, false,
-                "5550000", PhoneNumberUtils.TOA_Unknown);
-        verify(mMockBluetoothHeadset).clccResponse(2, 1, CALL_STATE_HELD, 0, false,
-                "5550001", PhoneNumberUtils.TOA_Unknown);
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        1, 1, CALL_STATE_ACTIVE, 0, false, "5550000", PhoneNumberUtils.TOA_Unknown);
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        2, 1, CALL_STATE_HELD, 0, false, "5550001", PhoneNumberUtils.TOA_Unknown);
         verify(mMockBluetoothHeadset, times(2)).clccResponse(0, 0, 0, 0, false, null, 0);
     }
 
@@ -678,16 +760,30 @@ public class BluetoothInCallServiceTest {
         when(dialingCall.isIncoming()).thenReturn(false);
         when(dialingCall.isConference()).thenReturn(false);
         when(dialingCall.getHandle()).thenReturn(Uri.parse("tel:555-0000"));
-        when(dialingCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
+        when(dialingCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
 
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
-        verify(mMockBluetoothHeadset).clccResponse(1, 0, CALL_STATE_ALERTING, 0, false,
-                "5550000", PhoneNumberUtils.TOA_Unknown);
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        1,
+                        0,
+                        CALL_STATE_ALERTING,
+                        0,
+                        false,
+                        "5550000",
+                        PhoneNumberUtils.TOA_Unknown);
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
-        verify(mMockBluetoothHeadset, times(2)).clccResponse(anyInt(),
-                anyInt(), anyInt(), anyInt(), anyBoolean(), nullable(String.class), anyInt());
+        verify(mMockBluetoothHeadset, times(2))
+                .clccResponse(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyBoolean(),
+                        nullable(String.class),
+                        anyInt());
     }
 
     @Test
@@ -702,8 +798,8 @@ public class BluetoothInCallServiceTest {
         when(dialingCall.isIncoming()).thenReturn(false);
         when(dialingCall.isConference()).thenReturn(false);
         when(dialingCall.getHandle()).thenReturn(Uri.parse("tel:555-0000"));
-        when(dialingCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
+        when(dialingCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0000")));
         BluetoothCall holdingCall = createHeldCall(UUID.randomUUID());
         calls.add(holdingCall);
         mBluetoothInCallService.onCallAdded(holdingCall);
@@ -712,18 +808,33 @@ public class BluetoothInCallServiceTest {
         when(holdingCall.isIncoming()).thenReturn(true);
         when(holdingCall.isConference()).thenReturn(false);
         when(holdingCall.getHandle()).thenReturn(Uri.parse("tel:555-0001"));
-        when(holdingCall.getGatewayInfo()).thenReturn(
-                new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
+        when(holdingCall.getGatewayInfo())
+                .thenReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0001")));
 
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
-        verify(mMockBluetoothHeadset).clccResponse(1, 0, CALL_STATE_ALERTING, 0, false,
-                "5550000", PhoneNumberUtils.TOA_Unknown);
-        verify(mMockBluetoothHeadset).clccResponse(2, 1, CALL_STATE_HELD, 0, false,
-                "5550001", PhoneNumberUtils.TOA_Unknown);
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        1,
+                        0,
+                        CALL_STATE_ALERTING,
+                        0,
+                        false,
+                        "5550000",
+                        PhoneNumberUtils.TOA_Unknown);
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        2, 1, CALL_STATE_HELD, 0, false, "5550001", PhoneNumberUtils.TOA_Unknown);
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
-        verify(mMockBluetoothHeadset, times(3)).clccResponse(anyInt(),
-                anyInt(), anyInt(), anyInt(), anyBoolean(), nullable(String.class), anyInt());
+        verify(mMockBluetoothHeadset, times(3))
+                .clccResponse(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyBoolean(),
+                        nullable(String.class),
+                        anyInt());
     }
 
     @Test
@@ -744,8 +855,15 @@ public class BluetoothInCallServiceTest {
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
 
-        verify(mMockBluetoothHeadset).clccResponse(eq(1), eq(1), eq(CALL_STATE_ACTIVE), eq(0),
-                eq(true), eq("5550000"), eq(129));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        eq(1),
+                        eq(1),
+                        eq(CALL_STATE_ACTIVE),
+                        eq(0),
+                        eq(true),
+                        eq("5550000"),
+                        eq(129));
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
     }
 
@@ -770,8 +888,7 @@ public class BluetoothInCallServiceTest {
         Integer parentId = parentCall.getId();
         when(childCall1.getParentId()).thenReturn(parentId);
         when(childCall2.getParentId()).thenReturn(parentId);
-        List childrenIds = Arrays.asList(childCall1.getId(),
-                childCall2.getId());
+        List childrenIds = Arrays.asList(childCall1.getId(), childCall2.getId());
         when(parentCall.getChildrenIds()).thenReturn(childrenIds);
 
         when(parentCall.isConference()).thenReturn(true);
@@ -785,10 +902,24 @@ public class BluetoothInCallServiceTest {
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
 
-        verify(mMockBluetoothHeadset).clccResponse(eq(1), eq(0), eq(CALL_STATE_HELD), eq(0),
-                eq(true), eq("5550001"), eq(PhoneNumberUtils.TOA_Unknown));
-        verify(mMockBluetoothHeadset).clccResponse(eq(2), eq(0), eq(CALL_STATE_HELD), eq(0),
-                eq(true), eq("5550002"), eq(PhoneNumberUtils.TOA_Unknown));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        eq(1),
+                        eq(0),
+                        eq(CALL_STATE_HELD),
+                        eq(0),
+                        eq(true),
+                        eq("5550001"),
+                        eq(PhoneNumberUtils.TOA_Unknown));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(
+                        eq(2),
+                        eq(0),
+                        eq(CALL_STATE_HELD),
+                        eq(0),
+                        eq(true),
+                        eq("5550002"),
+                        eq(PhoneNumberUtils.TOA_Unknown));
         verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0);
     }
 
@@ -812,8 +943,8 @@ public class BluetoothInCallServiceTest {
 
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.listCurrentCalls();
-        verify(mMockBluetoothHeadset).clccResponse(
-                eq(1), eq(1), eq(0), eq(0), eq(true), eq("5551234"), eq(129));
+        verify(mMockBluetoothHeadset)
+                .clccResponse(eq(1), eq(1), eq(0), eq(0), eq(true), eq("5551234"), eq(129));
     }
 
     @Test
@@ -961,8 +1092,14 @@ public class BluetoothInCallServiceTest {
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.queryPhoneState();
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_INCOMING),
-                eq("5550000"), eq(PhoneNumberUtils.TOA_Unknown), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_INCOMING),
+                        eq("5550000"),
+                        eq(PhoneNumberUtils.TOA_Unknown),
+                        nullable(String.class));
     }
 
     @Test
@@ -977,14 +1114,14 @@ public class BluetoothInCallServiceTest {
         removeCallCapability(parentConfCall, Connection.CAPABILITY_CONFERENCE_HAS_NO_CHILDREN);
         when(parentConfCall.wasConferencePreviouslyMerged()).thenReturn(true);
         when(parentConfCall.isConference()).thenReturn(true);
-        List childrenIds = Arrays.asList(confCall1.getId(),
-                confCall2.getId());
+        List childrenIds = Arrays.asList(confCall1.getId(), confCall2.getId());
         when(parentConfCall.getChildrenIds()).thenReturn(childrenIds);
 
         clearInvocations(mMockBluetoothHeadset);
         mBluetoothInCallService.queryPhoneState();
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(0), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1012,8 +1149,8 @@ public class BluetoothInCallServiceTest {
         BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
         BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
 
-        boolean didProcess = mBluetoothInCallService.processChld(
-                CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD);
+        boolean didProcess =
+                mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD);
 
         verify(activeCall).disconnect();
         verify(ringingCall).answer(any(int.class));
@@ -1025,8 +1162,8 @@ public class BluetoothInCallServiceTest {
         BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
         BluetoothCall heldCall = createHeldCall(UUID.randomUUID());
 
-        boolean didProcess = mBluetoothInCallService.processChld(
-                CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD);
+        boolean didProcess =
+                mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD);
 
         verify(activeCall).disconnect();
         // BluetoothCall unhold will occur as part of CallsManager auto-unholding
@@ -1038,8 +1175,7 @@ public class BluetoothInCallServiceTest {
     public void testProcessChldHoldActiveRinging() throws Exception {
         BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
 
-        boolean didProcess = mBluetoothInCallService.processChld(
-                CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
+        boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
 
         verify(ringingCall).answer(any(int.class));
         Assert.assertTrue(didProcess);
@@ -1049,8 +1185,7 @@ public class BluetoothInCallServiceTest {
     public void testProcessChldHoldActiveUnhold() throws Exception {
         BluetoothCall heldCall = createHeldCall(UUID.randomUUID());
 
-        boolean didProcess = mBluetoothInCallService.processChld(
-                CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
+        boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
 
         verify(heldCall).unhold();
         Assert.assertTrue(didProcess);
@@ -1061,8 +1196,7 @@ public class BluetoothInCallServiceTest {
         BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
         addCallCapability(activeCall, Connection.CAPABILITY_HOLD);
 
-        boolean didProcess = mBluetoothInCallService.processChld(
-                CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
+        boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
 
         verify(activeCall).hold();
         Assert.assertTrue(didProcess);
@@ -1110,17 +1244,16 @@ public class BluetoothInCallServiceTest {
         when(parentCall.isConference()).thenReturn(true);
         when(parentCall.wasConferencePreviouslyMerged()).thenReturn(false);
         when(heldCall.getHandle()).thenReturn(Uri.parse("tel:555-0000"));
-        List childrenIds = Arrays.asList(foregroundCall.getId(),
-                heldCall.getId());
+        List childrenIds = Arrays.asList(foregroundCall.getId(), heldCall.getId());
         when(parentCall.getChildrenIds()).thenReturn(childrenIds);
 
         clearInvocations(mMockBluetoothHeadset);
-        boolean didProcess = mBluetoothInCallService.processChld(
-                CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
+        boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
 
         verify(parentCall).swapConference();
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""),
-                eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
         Assert.assertTrue(didProcess);
     }
 
@@ -1132,8 +1265,14 @@ public class BluetoothInCallServiceTest {
 
         mBluetoothInCallService.onCallAdded(ringingCall);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_INCOMING),
-                eq("555000"), eq(PhoneNumberUtils.TOA_Unknown), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_INCOMING),
+                        eq("555000"),
+                        eq(PhoneNumberUtils.TOA_Unknown),
+                        nullable(String.class));
     }
 
     @Test
@@ -1144,8 +1283,14 @@ public class BluetoothInCallServiceTest {
 
         mBluetoothInCallService.onCallAdded(ringingCall);
 
-        verify(mMockBluetoothHeadset, never()).phoneStateChanged(anyInt(), anyInt(), anyInt(),
-                anyString(), anyInt(), nullable(String.class));
+        verify(mMockBluetoothHeadset, never())
+                .phoneStateChanged(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyString(),
+                        anyInt(),
+                        nullable(String.class));
     }
 
     @Test
@@ -1159,14 +1304,14 @@ public class BluetoothInCallServiceTest {
         addCallCapability(parentCall, Connection.CAPABILITY_MERGE_CONFERENCE);
         removeCallCapability(parentCall, Connection.CAPABILITY_CONFERENCE_HAS_NO_CHILDREN);
         when(parentCall.isConference()).thenReturn(true);
-        List childrenIds = Arrays.asList(foregroundCall.getId(),
-                heldCall.getId());
+        List childrenIds = Arrays.asList(foregroundCall.getId(), heldCall.getId());
         when(parentCall.getChildrenIds()).thenReturn(childrenIds);
 
         mBluetoothInCallService.onCallAdded(parentCall);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(1), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1178,8 +1323,9 @@ public class BluetoothInCallServiceTest {
 
         mBluetoothInCallService.onCallRemoved(activeCall, true /* forceRemoveCallback */);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1192,8 +1338,9 @@ public class BluetoothInCallServiceTest {
         when(activeCall.isExternalCall()).thenReturn(true);
         mBluetoothInCallService.getCallback(activeCall).onDetailsChanged(activeCall, null);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1201,8 +1348,8 @@ public class BluetoothInCallServiceTest {
         BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
         mBluetoothInCallService.onCallAdded(activeCall);
         when(activeCall.getHandle()).thenReturn(Uri.parse("tel:555-0001"));
-        BluetoothInCallService.CallStateCallback callBack = mBluetoothInCallService.getCallback(
-                activeCall);
+        BluetoothInCallService.CallStateCallback callBack =
+                mBluetoothInCallService.getCallback(activeCall);
 
         when(activeCall.isExternalCall()).thenReturn(true);
         callBack.onDetailsChanged(activeCall, null);
@@ -1210,8 +1357,9 @@ public class BluetoothInCallServiceTest {
         when(activeCall.isExternalCall()).thenReturn(false);
         callBack.onDetailsChanged(activeCall, null);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(0), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1226,11 +1374,18 @@ public class BluetoothInCallServiceTest {
         mBluetoothInCallService.onCallAdded(activeCall);
         when(mMockCallInfo.getBluetoothCalls()).thenReturn(calls);
 
-        mBluetoothInCallService.getCallback(activeCall)
+        mBluetoothInCallService
+                .getCallback(activeCall)
                 .onStateChanged(activeCall, Call.STATE_HOLDING);
 
-        verify(mMockBluetoothHeadset, never()).phoneStateChanged(anyInt(), anyInt(), anyInt(),
-                anyString(), anyInt(), nullable(String.class));
+        verify(mMockBluetoothHeadset, never())
+                .phoneStateChanged(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyString(),
+                        anyInt(),
+                        nullable(String.class));
     }
 
     @Test
@@ -1239,8 +1394,14 @@ public class BluetoothInCallServiceTest {
         when(call.getState()).thenReturn(Call.STATE_AUDIO_PROCESSING);
         mBluetoothInCallService.onCallAdded(call);
 
-        verify(mMockBluetoothHeadset, never()).phoneStateChanged(anyInt(), anyInt(), anyInt(),
-                anyString(), anyInt(), nullable(String.class));
+        verify(mMockBluetoothHeadset, never())
+                .phoneStateChanged(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyString(),
+                        anyInt(),
+                        nullable(String.class));
     }
 
     @Test
@@ -1250,17 +1411,25 @@ public class BluetoothInCallServiceTest {
 
         mBluetoothInCallService.onCallAdded(ringingCall);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_INCOMING),
-                eq("555000"), eq(PhoneNumberUtils.TOA_Unknown), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_INCOMING),
+                        eq("555000"),
+                        eq(PhoneNumberUtils.TOA_Unknown),
+                        nullable(String.class));
 
         when(ringingCall.getState()).thenReturn(Call.STATE_AUDIO_PROCESSING);
         when(mMockCallInfo.getRingingOrSimulatedRingingCall()).thenReturn(null);
 
-        mBluetoothInCallService.getCallback(ringingCall)
+        mBluetoothInCallService
+                .getCallback(ringingCall)
                 .onStateChanged(ringingCall, Call.STATE_AUDIO_PROCESSING);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1268,11 +1437,18 @@ public class BluetoothInCallServiceTest {
         BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
         when(ringingCall.getHandle()).thenReturn(Uri.parse("tel:555-0000"));
         mBluetoothInCallService.onCallAdded(ringingCall);
-        mBluetoothInCallService.getCallback(ringingCall)
+        mBluetoothInCallService
+                .getCallback(ringingCall)
                 .onStateChanged(ringingCall, Call.STATE_SIMULATED_RINGING);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_INCOMING),
-                eq("555-0000"), eq(PhoneNumberUtils.TOA_Unknown), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_INCOMING),
+                        eq("555-0000"),
+                        eq(PhoneNumberUtils.TOA_Unknown),
+                        nullable(String.class));
     }
 
     @Test
@@ -1280,11 +1456,13 @@ public class BluetoothInCallServiceTest {
         BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
         when(activeCall.getState()).thenReturn(Call.STATE_ACTIVE);
         mBluetoothInCallService.onCallAdded(activeCall);
-        mBluetoothInCallService.getCallback(activeCall)
+        mBluetoothInCallService
+                .getCallback(activeCall)
                 .onStateChanged(activeCall, Call.STATE_ACTIVE);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(0), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1294,27 +1472,47 @@ public class BluetoothInCallServiceTest {
         // make "mLastState" STATE_CONNECTING
         BluetoothInCallService.CallStateCallback callback =
                 mBluetoothInCallService.new CallStateCallback(Call.STATE_CONNECTING);
-        mBluetoothInCallService.mCallbacks.put(
-                activeCall.getId(), callback);
+        mBluetoothInCallService.mCallbacks.put(activeCall.getId(), callback);
 
-        mBluetoothInCallService.mCallbacks.get(activeCall.getId())
+        mBluetoothInCallService
+                .mCallbacks
+                .get(activeCall.getId())
                 .onStateChanged(activeCall, Call.STATE_DIALING);
 
-        verify(mMockBluetoothHeadset, never()).phoneStateChanged(anyInt(), anyInt(), anyInt(),
-                anyString(), anyInt(), nullable(String.class));
+        verify(mMockBluetoothHeadset, never())
+                .phoneStateChanged(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyString(),
+                        anyInt(),
+                        nullable(String.class));
     }
 
     @Test
     public void testOnCallStateChangedAlerting() throws Exception {
         BluetoothCall outgoingCall = createOutgoingCall(UUID.randomUUID());
         mBluetoothInCallService.onCallAdded(outgoingCall);
-        mBluetoothInCallService.getCallback(outgoingCall)
+        mBluetoothInCallService
+                .getCallback(outgoingCall)
                 .onStateChanged(outgoingCall, Call.STATE_DIALING);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_DIALING),
-                eq(""), eq(128), nullable(String.class));
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_ALERTING),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_DIALING),
+                        eq(""),
+                        eq(128),
+                        nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_ALERTING),
+                        eq(""),
+                        eq(128),
+                        nullable(String.class));
     }
 
     @Test
@@ -1322,10 +1520,17 @@ public class BluetoothInCallServiceTest {
         BluetoothCall disconnectedCall = createDisconnectedCall(UUID.randomUUID());
         doReturn(true).when(mMockCallInfo).hasOnlyDisconnectedCalls();
         mBluetoothInCallService.onCallAdded(disconnectedCall);
-        mBluetoothInCallService.getCallback(disconnectedCall)
+        mBluetoothInCallService
+                .getCallback(disconnectedCall)
                 .onStateChanged(disconnectedCall, Call.STATE_DISCONNECTED);
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_DISCONNECTED),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_DISCONNECTED),
+                        eq(""),
+                        eq(128),
+                        nullable(String.class));
     }
 
     @Test
@@ -1334,18 +1539,26 @@ public class BluetoothInCallServiceTest {
         when(ringingCall.getHandle()).thenReturn(Uri.parse("tel:555-0000"));
         mBluetoothInCallService.onCallAdded(ringingCall);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_INCOMING),
-                eq("555-0000"), eq(PhoneNumberUtils.TOA_Unknown), nullable(String.class));
-
-        //Switch to active
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_INCOMING),
+                        eq("555-0000"),
+                        eq(PhoneNumberUtils.TOA_Unknown),
+                        nullable(String.class));
+
+        // Switch to active
         doReturn(null).when(mMockCallInfo).getRingingOrSimulatedRingingCall();
         when(mMockCallInfo.getActiveCall()).thenReturn(ringingCall);
 
-        mBluetoothInCallService.getCallback(ringingCall)
+        mBluetoothInCallService
+                .getCallback(ringingCall)
                 .onStateChanged(ringingCall, Call.STATE_ACTIVE);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(0), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1356,11 +1569,16 @@ public class BluetoothInCallServiceTest {
         doReturn(2).when(mMockCallInfo).getNumHeldCalls();
 
         clearInvocations(mMockBluetoothHeadset);
-        mBluetoothInCallService.getCallback(heldCall)
-                .onStateChanged(heldCall, Call.STATE_HOLDING);
+        mBluetoothInCallService.getCallback(heldCall).onStateChanged(heldCall, Call.STATE_HOLDING);
 
-        verify(mMockBluetoothHeadset, never()).phoneStateChanged(eq(0), eq(2), eq(CALL_STATE_HELD),
-                eq("5550000"), eq(PhoneNumberUtils.TOA_Unknown), nullable(String.class));
+        verify(mMockBluetoothHeadset, never())
+                .phoneStateChanged(
+                        eq(0),
+                        eq(2),
+                        eq(CALL_STATE_HELD),
+                        eq("5550000"),
+                        eq(PhoneNumberUtils.TOA_Unknown),
+                        nullable(String.class));
     }
 
     @Test
@@ -1392,28 +1610,47 @@ public class BluetoothInCallServiceTest {
         // Be sure that onIsConferencedChanged rejects spurious changes during set up of
         // CDMA "conference"
         mBluetoothInCallService.getCallback(activeCall).onParentChanged(activeCall);
-        verify(mMockBluetoothHeadset, never()).phoneStateChanged(anyInt(), anyInt(), anyInt(),
-                anyString(), anyInt(), nullable(String.class));
+        verify(mMockBluetoothHeadset, never())
+                .phoneStateChanged(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyString(),
+                        anyInt(),
+                        nullable(String.class));
 
         mBluetoothInCallService.getCallback(heldCall).onParentChanged(heldCall);
-        verify(mMockBluetoothHeadset, never()).phoneStateChanged(anyInt(), anyInt(), anyInt(),
-                anyString(), anyInt(), nullable(String.class));
+        verify(mMockBluetoothHeadset, never())
+                .phoneStateChanged(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyString(),
+                        anyInt(),
+                        nullable(String.class));
 
-        mBluetoothInCallService.getCallback(parentCall)
+        mBluetoothInCallService
+                .getCallback(parentCall)
                 .onChildrenChanged(
-                        parentCall,
-                        mBluetoothInCallService.getBluetoothCallsByIds(calls));
-        verify(mMockBluetoothHeadset, never()).phoneStateChanged(anyInt(), anyInt(), anyInt(),
-                anyString(), anyInt(), nullable(String.class));
+                        parentCall, mBluetoothInCallService.getBluetoothCallsByIds(calls));
+        verify(mMockBluetoothHeadset, never())
+                .phoneStateChanged(
+                        anyInt(),
+                        anyInt(),
+                        anyInt(),
+                        anyString(),
+                        anyInt(),
+                        nullable(String.class));
 
         calls.add(heldCall.getId());
         mBluetoothInCallService.onCallAdded(heldCall);
-        mBluetoothInCallService.getCallback(parentCall)
+        mBluetoothInCallService
+                .getCallback(parentCall)
                 .onChildrenChanged(
-                        parentCall,
-                        mBluetoothInCallService.getBluetoothCallsByIds(calls));
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(1), eq(1), eq(CALL_STATE_IDLE),
-                eq(""), eq(128), nullable(String.class));
+                        parentCall, mBluetoothInCallService.getBluetoothCallsByIds(calls));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
     }
 
     @Test
@@ -1424,22 +1661,29 @@ public class BluetoothInCallServiceTest {
         Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
         intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON);
         clearInvocations(mMockBluetoothHeadset);
-        mBluetoothInCallService.mBluetoothAdapterReceiver
-                = mBluetoothInCallService.new BluetoothAdapterReceiver();
-        mBluetoothInCallService.mBluetoothAdapterReceiver
-                .onReceive(mBluetoothInCallService, intent);
+        mBluetoothInCallService.mBluetoothAdapterReceiver =
+                mBluetoothInCallService.new BluetoothAdapterReceiver();
+        mBluetoothInCallService.mBluetoothAdapterReceiver.onReceive(
+                mBluetoothInCallService, intent);
 
-        verify(mMockBluetoothHeadset).phoneStateChanged(eq(0), eq(0), eq(CALL_STATE_INCOMING),
-                eq("5550000"), eq(PhoneNumberUtils.TOA_Unknown), nullable(String.class));
+        verify(mMockBluetoothHeadset)
+                .phoneStateChanged(
+                        eq(0),
+                        eq(0),
+                        eq(CALL_STATE_INCOMING),
+                        eq("5550000"),
+                        eq(PhoneNumberUtils.TOA_Unknown),
+                        nullable(String.class));
     }
 
     @Test
     public void testClear() {
-        doNothing().when(mContext).unregisterReceiver(any(
-                BluetoothInCallService.BluetoothAdapterReceiver.class));
+        doNothing()
+                .when(mContext)
+                .unregisterReceiver(any(BluetoothInCallService.BluetoothAdapterReceiver.class));
         mBluetoothInCallService.attachBaseContext(mContext);
-        mBluetoothInCallService.mBluetoothAdapterReceiver
-                = mBluetoothInCallService.new BluetoothAdapterReceiver();
+        mBluetoothInCallService.mBluetoothAdapterReceiver =
+                mBluetoothInCallService.new BluetoothAdapterReceiver();
         Assert.assertNotNull(mBluetoothInCallService.mBluetoothAdapterReceiver);
         Assert.assertNotNull(mBluetoothInCallService.mBluetoothHeadset);
 
@@ -1453,54 +1697,64 @@ public class BluetoothInCallServiceTest {
     public void testGetBearerTechnology() {
         mBluetoothInCallService.mTelephonyManager = mMockTelephonyManager;
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_GSM);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_GSM);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_GSM);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_GPRS);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_GPRS);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_2G);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_EVDO_B);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_EVDO_B);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_3G);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_TD_SCDMA);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_TD_SCDMA);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_WCDMA);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_LTE);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_LTE);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_LTE);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_1xRTT);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_1xRTT);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_CDMA);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_HSPAP);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_HSPAP);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_4G);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_IWLAN);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_IWLAN);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_WIFI);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_NR);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_NR);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_5G);
 
-        when(mMockTelephonyManager.getDataNetworkType()).thenReturn(
-                TelephonyManager.NETWORK_TYPE_LTE_CA);
-        Assert.assertEquals(mBluetoothInCallService.getBearerTechnology(),
+        when(mMockTelephonyManager.getDataNetworkType())
+                .thenReturn(TelephonyManager.NETWORK_TYPE_LTE_CA);
+        Assert.assertEquals(
+                mBluetoothInCallService.getBearerTechnology(),
                 BluetoothLeCallControlProxy.BEARER_TECHNOLOGY_GSM);
     }
 
@@ -1509,45 +1763,54 @@ public class BluetoothInCallServiceTest {
         BluetoothCall call = getMockCall(UUID.randomUUID());
 
         when(call.getDisconnectCause()).thenReturn(null);
-        Assert.assertEquals(mBluetoothInCallService.getTbsTerminationReason(call),
+        Assert.assertEquals(
+                mBluetoothInCallService.getTbsTerminationReason(call),
                 BluetoothLeCallControl.TERMINATION_REASON_FAIL);
 
         DisconnectCause cause = new DisconnectCause(DisconnectCause.BUSY, null, null, null, 1);
         when(call.getDisconnectCause()).thenReturn(cause);
-        Assert.assertEquals(mBluetoothInCallService.getTbsTerminationReason(call),
+        Assert.assertEquals(
+                mBluetoothInCallService.getTbsTerminationReason(call),
                 BluetoothLeCallControl.TERMINATION_REASON_LINE_BUSY);
 
         cause = new DisconnectCause(DisconnectCause.REJECTED, null, null, null, 1);
         when(call.getDisconnectCause()).thenReturn(cause);
-        Assert.assertEquals(mBluetoothInCallService.getTbsTerminationReason(call),
+        Assert.assertEquals(
+                mBluetoothInCallService.getTbsTerminationReason(call),
                 BluetoothLeCallControl.TERMINATION_REASON_REMOTE_HANGUP);
 
         cause = new DisconnectCause(DisconnectCause.LOCAL, null, null, null, 1);
         when(call.getDisconnectCause()).thenReturn(cause);
         mBluetoothInCallService.mIsTerminatedByClient = false;
-        Assert.assertEquals(mBluetoothInCallService.getTbsTerminationReason(call),
+        Assert.assertEquals(
+                mBluetoothInCallService.getTbsTerminationReason(call),
                 BluetoothLeCallControl.TERMINATION_REASON_SERVER_HANGUP);
 
         cause = new DisconnectCause(DisconnectCause.LOCAL, null, null, null, 1);
         when(call.getDisconnectCause()).thenReturn(cause);
         mBluetoothInCallService.mIsTerminatedByClient = true;
-        Assert.assertEquals(mBluetoothInCallService.getTbsTerminationReason(call),
+        Assert.assertEquals(
+                mBluetoothInCallService.getTbsTerminationReason(call),
                 BluetoothLeCallControl.TERMINATION_REASON_CLIENT_HANGUP);
 
         cause = new DisconnectCause(DisconnectCause.ERROR, null, null, null, 1);
         when(call.getDisconnectCause()).thenReturn(cause);
-        Assert.assertEquals(mBluetoothInCallService.getTbsTerminationReason(call),
+        Assert.assertEquals(
+                mBluetoothInCallService.getTbsTerminationReason(call),
                 BluetoothLeCallControl.TERMINATION_REASON_NETWORK_CONGESTION);
 
-        cause = new DisconnectCause(
-                DisconnectCause.CONNECTION_MANAGER_NOT_SUPPORTED, null, null, null, 1);
+        cause =
+                new DisconnectCause(
+                        DisconnectCause.CONNECTION_MANAGER_NOT_SUPPORTED, null, null, null, 1);
         when(call.getDisconnectCause()).thenReturn(cause);
-        Assert.assertEquals(mBluetoothInCallService.getTbsTerminationReason(call),
+        Assert.assertEquals(
+                mBluetoothInCallService.getTbsTerminationReason(call),
                 BluetoothLeCallControl.TERMINATION_REASON_INVALID_URI);
 
         cause = new DisconnectCause(DisconnectCause.ERROR, null, null, null, 1);
         when(call.getDisconnectCause()).thenReturn(cause);
-        Assert.assertEquals(mBluetoothInCallService.getTbsTerminationReason(call),
+        Assert.assertEquals(
+                mBluetoothInCallService.getTbsTerminationReason(call),
                 BluetoothLeCallControl.TERMINATION_REASON_NETWORK_CONGESTION);
     }
 
@@ -1586,8 +1849,8 @@ public class BluetoothInCallServiceTest {
         UUID unknownCallId = UUID.randomUUID();
         callback.onAcceptCall(requestId, unknownCallId);
 
-        verify(callControlProxy).requestResult(
-                requestId, BluetoothLeCallControl.RESULT_ERROR_UNKNOWN_CALL_ID);
+        verify(callControlProxy)
+                .requestResult(requestId, BluetoothLeCallControl.RESULT_ERROR_UNKNOWN_CALL_ID);
     }
 
     @Test
@@ -1601,8 +1864,8 @@ public class BluetoothInCallServiceTest {
         UUID unknownCallId = UUID.randomUUID();
         callback.onTerminateCall(requestId, unknownCallId);
 
-        verify(callControlProxy).requestResult(
-                requestId, BluetoothLeCallControl.RESULT_ERROR_UNKNOWN_CALL_ID);
+        verify(callControlProxy)
+                .requestResult(requestId, BluetoothLeCallControl.RESULT_ERROR_UNKNOWN_CALL_ID);
     }
 
     @Test
@@ -1616,8 +1879,8 @@ public class BluetoothInCallServiceTest {
         UUID unknownCallId = UUID.randomUUID();
         callback.onHoldCall(requestId, unknownCallId);
 
-        verify(callControlProxy).requestResult(
-                requestId, BluetoothLeCallControl.RESULT_ERROR_UNKNOWN_CALL_ID);
+        verify(callControlProxy)
+                .requestResult(requestId, BluetoothLeCallControl.RESULT_ERROR_UNKNOWN_CALL_ID);
     }
 
     @Test
@@ -1631,8 +1894,8 @@ public class BluetoothInCallServiceTest {
         UUID unknownCallId = UUID.randomUUID();
         callback.onUnholdCall(requestId, unknownCallId);
 
-        verify(callControlProxy).requestResult(
-                requestId, BluetoothLeCallControl.RESULT_ERROR_UNKNOWN_CALL_ID);
+        verify(callControlProxy)
+                .requestResult(requestId, BluetoothLeCallControl.RESULT_ERROR_UNKNOWN_CALL_ID);
     }
 
     @Test
@@ -1646,8 +1909,8 @@ public class BluetoothInCallServiceTest {
         UUID baseCallId = UUID.randomUUID();
         UUID firstJoiningCallId = UUID.randomUUID();
         UUID secondJoiningCallId = UUID.randomUUID();
-        List uuids = new ArrayList<>(Arrays.asList(baseCallId, firstJoiningCallId,
-                secondJoiningCallId));
+        List uuids =
+                new ArrayList<>(Arrays.asList(baseCallId, firstJoiningCallId, secondJoiningCallId));
         ArrayList calls = new ArrayList<>();
         BluetoothCall baseCall = createActiveCall(baseCallId);
         BluetoothCall firstCall = createRingingCall(firstJoiningCallId);
@@ -1672,8 +1935,7 @@ public class BluetoothInCallServiceTest {
 
         callback.onJoinCalls(requestId, uuids);
 
-        verify(callControlProxy).requestResult(
-                requestId, BluetoothLeCallControl.RESULT_SUCCESS);
+        verify(callControlProxy).requestResult(requestId, BluetoothLeCallControl.RESULT_SUCCESS);
         verify(baseCall, times(2)).conference(any(BluetoothCall.class));
     }
 
@@ -1687,8 +1949,8 @@ public class BluetoothInCallServiceTest {
         int requestId = 1;
         UUID baseCallId = UUID.randomUUID();
         UUID firstJoiningCallId = UUID.randomUUID();
-        List uuids = new ArrayList<>(Arrays.asList(baseCallId, firstJoiningCallId,
-                firstJoiningCallId));
+        List uuids =
+                new ArrayList<>(Arrays.asList(baseCallId, firstJoiningCallId, firstJoiningCallId));
         ArrayList calls = new ArrayList<>();
         BluetoothCall baseCall = createActiveCall(baseCallId);
         BluetoothCall firstCall = createRingingCall(firstJoiningCallId);
@@ -1707,8 +1969,7 @@ public class BluetoothInCallServiceTest {
 
         callback.onJoinCalls(requestId, uuids);
 
-        verify(callControlProxy).requestResult(
-                requestId, BluetoothLeCallControl.RESULT_SUCCESS);
+        verify(callControlProxy).requestResult(requestId, BluetoothLeCallControl.RESULT_SUCCESS);
         verify(baseCall, times(1)).conference(any(BluetoothCall.class));
     }
 
@@ -1723,8 +1984,8 @@ public class BluetoothInCallServiceTest {
         UUID baseCallId = UUID.randomUUID();
         UUID firstJoiningCallId = UUID.randomUUID();
         UUID secondJoiningCallId = UUID.randomUUID();
-        List uuids = new ArrayList<>(Arrays.asList(baseCallId, firstJoiningCallId,
-                secondJoiningCallId));
+        List uuids =
+                new ArrayList<>(Arrays.asList(baseCallId, firstJoiningCallId, secondJoiningCallId));
         ArrayList calls = new ArrayList<>();
         BluetoothCall baseCall = createActiveCall(baseCallId);
         BluetoothCall firstCall = createRingingCall(firstJoiningCallId);
@@ -1749,8 +2010,7 @@ public class BluetoothInCallServiceTest {
 
         callback.onJoinCalls(requestId, uuids);
 
-        verify(callControlProxy).requestResult(
-                requestId, BluetoothLeCallControl.RESULT_SUCCESS);
+        verify(callControlProxy).requestResult(requestId, BluetoothLeCallControl.RESULT_SUCCESS);
         verify(firstCall, times(1)).conference(any(BluetoothCall.class));
     }
 
@@ -1800,13 +2060,14 @@ public class BluetoothInCallServiceTest {
     }
 
     private static ComponentName makeQuickConnectionServiceComponentName() {
-        return new ComponentName("com.android.server.telecom.tests",
+        return new ComponentName(
+                "com.android.server.telecom.tests",
                 "com.android.server.telecom.tests.MockConnectionService");
     }
 
     private static PhoneAccountHandle makeQuickAccountHandle(String id) {
-        return new PhoneAccountHandle(makeQuickConnectionServiceComponentName(), id,
-                Binder.getCallingUserHandle());
+        return new PhoneAccountHandle(
+                makeQuickConnectionServiceComponentName(), id, Binder.getCallingUserHandle());
     }
 
     private PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) {
diff --git a/android/app/tests/unit/src/com/android/bluetooth/telephony/CallInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/telephony/CallInfoTest.java
index 102389c3640..a1796a4d127 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/telephony/CallInfoTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/telephony/CallInfoTest.java
@@ -57,8 +57,7 @@ public class CallInfoTest {
 
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private TelecomManager mMockTelecomManager;
+    @Mock private TelecomManager mMockTelecomManager;
 
     private BluetoothInCallService mBluetoothInCallService;
     private BluetoothInCallService.CallInfo mMockCallInfo;
@@ -269,8 +268,8 @@ public class CallInfoTest {
         List handles = new ArrayList<>();
         PhoneAccountHandle testHandle = makeQuickAccountHandle(testId);
         handles.add(testHandle);
-        when(mMockTelecomManager.getPhoneAccountsSupportingScheme(
-                PhoneAccount.SCHEME_TEL)).thenReturn(handles);
+        when(mMockTelecomManager.getPhoneAccountsSupportingScheme(PhoneAccount.SCHEME_TEL))
+                .thenReturn(handles);
 
         PhoneAccount fakePhoneAccount = makeQuickAccount(testId, TEST_ACCOUNT_INDEX);
         when(mMockTelecomManager.getPhoneAccount(testHandle)).thenReturn(fakePhoneAccount);
@@ -280,13 +279,14 @@ public class CallInfoTest {
     }
 
     private static ComponentName makeQuickConnectionServiceComponentName() {
-        return new ComponentName("com.placeholder.connectionservice.package.name",
+        return new ComponentName(
+                "com.placeholder.connectionservice.package.name",
                 "com.placeholder.connectionservice.class.name");
     }
 
     private static PhoneAccountHandle makeQuickAccountHandle(String id) {
-        return new PhoneAccountHandle(makeQuickConnectionServiceComponentName(), id,
-                Process.myUserHandle());
+        return new PhoneAccountHandle(
+                makeQuickConnectionServiceComponentName(), id, Process.myUserHandle());
     }
 
     private PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) {
@@ -306,4 +306,4 @@ public class CallInfoTest {
     private BluetoothCall getMockCall() {
         return mock(BluetoothCall.class);
     }
-}
\ No newline at end of file
+}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/util/GsmAlphabetTest.java b/android/app/tests/unit/src/com/android/bluetooth/util/GsmAlphabetTest.java
index 8d271e851df..1cc1a925133 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/util/GsmAlphabetTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/util/GsmAlphabetTest.java
@@ -30,159 +30,180 @@ import org.junit.runners.JUnit4;
 @RunWith(JUnit4.class)
 public final class GsmAlphabetTest {
 
-  private static final String GSM_EXTENDED_CHARS = "{|}\\[~]\f\u20ac";
-
-  @Before
-  public void setUp() throws Exception {
-    InstrumentationRegistry.getInstrumentation().getUiAutomation().adoptShellPermissionIdentity();
-  }
-
-  @Test
-  public void gsm7BitPackedToString() throws Exception {
-    byte[] packed;
-    StringBuilder testString = new StringBuilder(300);
-
-    packed = com.android.internal.telephony.GsmAlphabet.stringToGsm7BitPacked(
-            testString.toString());
-    assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0], 0, 0, 0))
-            .isEqualTo(testString.toString());
-
-    // Check all alignment cases
-    for (int i = 0; i < 9; i++, testString.append('@')) {
-      packed = com.android.internal.telephony.GsmAlphabet.stringToGsm7BitPacked(
-              testString.toString());
-      assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0], 0, 0, 0))
-              .isEqualTo(testString.toString());
+    private static final String GSM_EXTENDED_CHARS = "{|}\\[~]\f\u20ac";
+
+    @Before
+    public void setUp() throws Exception {
+        InstrumentationRegistry.getInstrumentation()
+                .getUiAutomation()
+                .adoptShellPermissionIdentity();
+    }
+
+    @Test
+    public void gsm7BitPackedToString() throws Exception {
+        byte[] packed;
+        StringBuilder testString = new StringBuilder(300);
+
+        packed =
+                com.android.internal.telephony.GsmAlphabet.stringToGsm7BitPacked(
+                        testString.toString());
+        assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0], 0, 0, 0))
+                .isEqualTo(testString.toString());
+
+        // Check all alignment cases
+        for (int i = 0; i < 9; i++, testString.append('@')) {
+            packed =
+                    com.android.internal.telephony.GsmAlphabet.stringToGsm7BitPacked(
+                            testString.toString());
+            assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0], 0, 0, 0))
+                    .isEqualTo(testString.toString());
+        }
+
+        // Test extended chars too
+        testString.append(GSM_EXTENDED_CHARS);
+        packed =
+                com.android.internal.telephony.GsmAlphabet.stringToGsm7BitPacked(
+                        testString.toString());
+        assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0], 0, 0, 0))
+                .isEqualTo(testString.toString());
+
+        // Try 254 septets with 127 extended chars
+        testString.setLength(0);
+        for (int i = 0; i < (255 / 2); i++) {
+            testString.append('{');
+        }
+        packed =
+                com.android.internal.telephony.GsmAlphabet.stringToGsm7BitPacked(
+                        testString.toString());
+        assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0], 0, 0, 0))
+                .isEqualTo(testString.toString());
+
+        // Reserved for extension to extension table (mapped to space)
+        packed = new byte[] {(byte) (0x1b | 0x80), 0x1b >> 1};
+        assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 0, 2, 0, 0, 0)).isEqualTo(" ");
+
+        // Unmappable (mapped to character in default alphabet table)
+        packed[0] = 0x1b;
+        packed[1] = 0x00;
+        assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 0, 2, 0, 0, 0)).isEqualTo("@");
+        packed[0] = (byte) (0x1b | 0x80);
+        packed[1] = (byte) (0x7f >> 1);
+        assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 0, 2, 0, 0, 0)).isEqualTo("\u00e0");
+    }
+
+    @Test
+    public void stringToGsm8BitPacked() throws Exception {
+        byte unpacked[];
+        unpacked = IccUtils.hexStringToBytes("566F696365204D61696C");
+        assertThat(IccUtils.bytesToHexString(GsmAlphabet.stringToGsm8BitPacked("Voice Mail")))
+                .isEqualTo(IccUtils.bytesToHexString(unpacked));
+
+        unpacked = GsmAlphabet.stringToGsm8BitPacked(GSM_EXTENDED_CHARS);
+        // two bytes for every extended char
+        assertThat(unpacked.length).isEqualTo(2 * GSM_EXTENDED_CHARS.length());
     }
 
-    // Test extended chars too
-    testString.append(GSM_EXTENDED_CHARS);
-    packed = com.android.internal.telephony.GsmAlphabet.stringToGsm7BitPacked(
-            testString.toString());
-    assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0], 0, 0, 0))
-            .isEqualTo(testString.toString());
-
-    // Try 254 septets with 127 extended chars
-    testString.setLength(0);
-    for (int i = 0; i < (255 / 2); i++) {
-      testString.append('{');
+    @Test
+    public void stringToGsm8BitUnpackedField() throws Exception {
+        byte unpacked[];
+        // Test truncation of unaligned extended chars
+        unpacked = new byte[3];
+        GsmAlphabet.stringToGsm8BitUnpackedField(GSM_EXTENDED_CHARS, unpacked, 0, unpacked.length);
+
+        // Should be one extended char and an 0xff at the end
+        assertThat(0xff & unpacked[2]).isEqualTo(0xff);
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 0, unpacked.length))
+                .isEqualTo(GSM_EXTENDED_CHARS.substring(0, 1));
+
+        // Test truncation of normal chars
+        unpacked = new byte[3];
+        GsmAlphabet.stringToGsm8BitUnpackedField("abcd", unpacked, 0, unpacked.length);
+
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 0, unpacked.length))
+                .isEqualTo("abc");
+
+        // Test truncation of mixed normal and extended chars
+        unpacked = new byte[3];
+        GsmAlphabet.stringToGsm8BitUnpackedField("a{cd", unpacked, 0, unpacked.length);
+
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 0, unpacked.length))
+                .isEqualTo("a{");
+
+        // Test padding after normal char
+        unpacked = new byte[3];
+        GsmAlphabet.stringToGsm8BitUnpackedField("a", unpacked, 0, unpacked.length);
+
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 0, unpacked.length))
+                .isEqualTo("a");
+
+        assertThat(0xff & unpacked[1]).isEqualTo(0xff);
+        assertThat(0xff & unpacked[2]).isEqualTo(0xff);
+
+        // Test malformed input -- escape char followed by end of field
+        unpacked[0] = 0;
+        unpacked[1] = 0;
+        unpacked[2] = GsmAlphabet.GSM_EXTENDED_ESCAPE;
+
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 0, unpacked.length))
+                .isEqualTo("@@");
+
+        // non-zero offset
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 1, unpacked.length - 1))
+                .isEqualTo("@");
+
+        // test non-zero offset
+        unpacked[0] = 0;
+        GsmAlphabet.stringToGsm8BitUnpackedField("abcd", unpacked, 1, unpacked.length - 1);
+
+        assertThat(unpacked[0]).isEqualTo(0);
+
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 1, unpacked.length - 1))
+                .isEqualTo("ab");
+
+        // test non-zero offset with truncated extended char
+        unpacked[0] = 0;
+
+        GsmAlphabet.stringToGsm8BitUnpackedField("a{", unpacked, 1, unpacked.length - 1);
+
+        assertThat(unpacked[0]).isEqualTo(0);
+
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 1, unpacked.length - 1))
+                .isEqualTo("a");
+
+        // Reserved for extension to extension table (mapped to space)
+        unpacked[0] = 0x1b;
+        unpacked[1] = 0x1b;
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 0, 2))
+                .isEqualTo(" ");
+
+        // Unmappable (mapped to character in default or national locking shift table)
+        unpacked[1] = 0x00;
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 0, 2))
+                .isEqualTo("@");
+        unpacked[1] = 0x7f;
+        assertThat(
+                        com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
+                                unpacked, 0, 2))
+                .isEqualTo("\u00e0");
     }
-    packed = com.android.internal.telephony.GsmAlphabet.stringToGsm7BitPacked(
-            testString.toString());
-    assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 1, 0xff & packed[0], 0, 0, 0))
-            .isEqualTo(testString.toString());
-
-    // Reserved for extension to extension table (mapped to space)
-    packed = new byte[]{(byte)(0x1b | 0x80), 0x1b >> 1};
-    assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 0, 2, 0, 0, 0)).isEqualTo(" ");
-
-    // Unmappable (mapped to character in default alphabet table)
-    packed[0] = 0x1b;
-    packed[1] = 0x00;
-    assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 0, 2, 0, 0, 0)).isEqualTo("@");
-    packed[0] = (byte)(0x1b | 0x80);
-    packed[1] = (byte)(0x7f >> 1);
-    assertThat(GsmAlphabet.gsm7BitPackedToString(packed, 0, 2, 0, 0, 0)).isEqualTo("\u00e0");
-  }
-
-  @Test
-  public void stringToGsm8BitPacked() throws Exception {
-    byte unpacked[];
-    unpacked = IccUtils.hexStringToBytes("566F696365204D61696C");
-    assertThat(IccUtils.bytesToHexString(GsmAlphabet.stringToGsm8BitPacked("Voice Mail")))
-            .isEqualTo(IccUtils.bytesToHexString(unpacked));
-
-    unpacked = GsmAlphabet.stringToGsm8BitPacked(GSM_EXTENDED_CHARS);
-    // two bytes for every extended char
-    assertThat(unpacked.length).isEqualTo(2 * GSM_EXTENDED_CHARS.length());
-  }
-
-  @Test
-  public void stringToGsm8BitUnpackedField() throws Exception {
-    byte unpacked[];
-    // Test truncation of unaligned extended chars
-    unpacked = new byte[3];
-    GsmAlphabet.stringToGsm8BitUnpackedField(GSM_EXTENDED_CHARS, unpacked,
-            0, unpacked.length);
-
-    // Should be one extended char and an 0xff at the end
-    assertThat(0xff & unpacked[2]).isEqualTo(0xff);
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 0, unpacked.length)).isEqualTo(GSM_EXTENDED_CHARS.substring(0, 1));
-
-    // Test truncation of normal chars
-    unpacked = new byte[3];
-    GsmAlphabet.stringToGsm8BitUnpackedField("abcd", unpacked,
-            0, unpacked.length);
-
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 0, unpacked.length)).isEqualTo("abc");
-
-    // Test truncation of mixed normal and extended chars
-    unpacked = new byte[3];
-    GsmAlphabet.stringToGsm8BitUnpackedField("a{cd", unpacked,
-            0, unpacked.length);
-
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 0, unpacked.length)).isEqualTo("a{");
-
-    // Test padding after normal char
-    unpacked = new byte[3];
-    GsmAlphabet.stringToGsm8BitUnpackedField("a", unpacked,
-            0, unpacked.length);
-
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 0, unpacked.length)).isEqualTo("a");
-
-    assertThat(0xff & unpacked[1]).isEqualTo(0xff);
-    assertThat(0xff & unpacked[2]).isEqualTo(0xff);
-
-    // Test malformed input -- escape char followed by end of field
-    unpacked[0] = 0;
-    unpacked[1] = 0;
-    unpacked[2] = GsmAlphabet.GSM_EXTENDED_ESCAPE;
-
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 0, unpacked.length)).isEqualTo("@@");
-
-    // non-zero offset
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 1, unpacked.length - 1)).isEqualTo("@");
-
-    // test non-zero offset
-    unpacked[0] = 0;
-    GsmAlphabet.stringToGsm8BitUnpackedField("abcd", unpacked,
-            1, unpacked.length - 1);
-
-
-    assertThat(unpacked[0]).isEqualTo(0);
-
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 1, unpacked.length - 1)).isEqualTo("ab");
-
-    // test non-zero offset with truncated extended char
-    unpacked[0] = 0;
-
-    GsmAlphabet.stringToGsm8BitUnpackedField("a{", unpacked,
-            1, unpacked.length - 1);
-
-    assertThat(unpacked[0]).isEqualTo(0);
-
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 1, unpacked.length - 1)).isEqualTo("a");
-
-    // Reserved for extension to extension table (mapped to space)
-    unpacked[0] = 0x1b;
-    unpacked[1] = 0x1b;
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 0, 2)).isEqualTo(" ");
-
-    // Unmappable (mapped to character in default or national locking shift table)
-    unpacked[1] = 0x00;
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 0, 2)).isEqualTo("@");
-    unpacked[1] = 0x7f;
-    assertThat(com.android.internal.telephony.GsmAlphabet.gsm8BitUnpackedToString(
-            unpacked, 0, 2)).isEqualTo("\u00e0");
-  }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeInterfaceTest.java
index 7d19671151e..1ed290c8b93 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeInterfaceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeInterfaceTest.java
@@ -37,8 +37,7 @@ import org.mockito.junit.MockitoRule;
 public class VolumeControlNativeInterfaceTest {
     @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    private VolumeControlService mService;
+    @Mock private VolumeControlService mService;
 
     private VolumeControlNativeInterface mNativeInterface;
 
@@ -57,22 +56,22 @@ public class VolumeControlNativeInterfaceTest {
     @Test
     public void onConnectionStateChanged() {
         int state = VolumeControlStackEvent.CONNECTION_STATE_CONNECTED;
-        byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
+        byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
 
         mNativeInterface.onConnectionStateChanged(state, address);
 
         ArgumentCaptor event =
                 ArgumentCaptor.forClass(VolumeControlStackEvent.class);
         verify(mService).messageFromNative(event.capture());
-        assertThat(event.getValue().type).isEqualTo(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        assertThat(event.getValue().type)
+                .isEqualTo(VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
     }
 
     @Test
     public void onVolumeStateChanged() {
         int volume = 3;
         boolean mute = false;
-        byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
+        byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
         boolean isAutonomous = false;
 
         mNativeInterface.onVolumeStateChanged(volume, mute, address, isAutonomous);
@@ -80,8 +79,8 @@ public class VolumeControlNativeInterfaceTest {
         ArgumentCaptor event =
                 ArgumentCaptor.forClass(VolumeControlStackEvent.class);
         verify(mService).messageFromNative(event.capture());
-        assertThat(event.getValue().type).isEqualTo(
-                VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
+        assertThat(event.getValue().type)
+                .isEqualTo(VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
     }
 
     @Test
@@ -96,66 +95,67 @@ public class VolumeControlNativeInterfaceTest {
         ArgumentCaptor event =
                 ArgumentCaptor.forClass(VolumeControlStackEvent.class);
         verify(mService).messageFromNative(event.capture());
-        assertThat(event.getValue().type).isEqualTo(
-                VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
+        assertThat(event.getValue().type)
+                .isEqualTo(VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
         assertThat(event.getValue().valueInt1).isEqualTo(groupId);
     }
 
     @Test
     public void onDeviceAvailable() {
         int numOfExternalOutputs = 3;
-        byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
+        byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
 
         mNativeInterface.onDeviceAvailable(numOfExternalOutputs, address);
 
         ArgumentCaptor event =
                 ArgumentCaptor.forClass(VolumeControlStackEvent.class);
         verify(mService).messageFromNative(event.capture());
-        assertThat(event.getValue().type).isEqualTo(
-                VolumeControlStackEvent.EVENT_TYPE_DEVICE_AVAILABLE);
+        assertThat(event.getValue().type)
+                .isEqualTo(VolumeControlStackEvent.EVENT_TYPE_DEVICE_AVAILABLE);
     }
+
     @Test
     public void onExtAudioOutVolumeOffsetChanged() {
         int externalOutputId = 2;
         int offset = 0;
-        byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
+        byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
 
         mNativeInterface.onExtAudioOutVolumeOffsetChanged(externalOutputId, offset, address);
 
         ArgumentCaptor event =
                 ArgumentCaptor.forClass(VolumeControlStackEvent.class);
         verify(mService).messageFromNative(event.capture());
-        assertThat(event.getValue().type).isEqualTo(
-                VolumeControlStackEvent.EVENT_TYPE_EXT_AUDIO_OUT_VOL_OFFSET_CHANGED);
+        assertThat(event.getValue().type)
+                .isEqualTo(VolumeControlStackEvent.EVENT_TYPE_EXT_AUDIO_OUT_VOL_OFFSET_CHANGED);
     }
 
     @Test
     public void onExtAudioOutLocationChanged() {
         int externalOutputId = 2;
         int location = 100;
-        byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
+        byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
 
         mNativeInterface.onExtAudioOutLocationChanged(externalOutputId, location, address);
 
         ArgumentCaptor event =
                 ArgumentCaptor.forClass(VolumeControlStackEvent.class);
         verify(mService).messageFromNative(event.capture());
-        assertThat(event.getValue().type).isEqualTo(
-                VolumeControlStackEvent.EVENT_TYPE_EXT_AUDIO_OUT_LOCATION_CHANGED);
+        assertThat(event.getValue().type)
+                .isEqualTo(VolumeControlStackEvent.EVENT_TYPE_EXT_AUDIO_OUT_LOCATION_CHANGED);
     }
 
     @Test
     public void onExtAudioOutDescriptionChanged() {
         int externalOutputId = 2;
         String descr = "test-descr";
-        byte[] address = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
+        byte[] address = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
 
         mNativeInterface.onExtAudioOutDescriptionChanged(externalOutputId, descr, address);
 
         ArgumentCaptor event =
                 ArgumentCaptor.forClass(VolumeControlStackEvent.class);
         verify(mService).messageFromNative(event.capture());
-        assertThat(event.getValue().type).isEqualTo(
-                VolumeControlStackEvent.EVENT_TYPE_EXT_AUDIO_OUT_DESCRIPTION_CHANGED);
+        assertThat(event.getValue().type)
+                .isEqualTo(VolumeControlStackEvent.EVENT_TYPE_EXT_AUDIO_OUT_DESCRIPTION_CHANGED);
     }
 }
diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java
index 2547d5ab0da..20712196893 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java
@@ -113,13 +113,17 @@ public class VolumeControlServiceTest {
         mAdapter = BluetoothAdapter.getDefaultAdapter();
         mAttributionSource = mAdapter.getAttributionSource();
 
-        doReturn(MEDIA_MIN_VOL).when(mAudioManager)
+        doReturn(MEDIA_MIN_VOL)
+                .when(mAudioManager)
                 .getStreamMinVolume(eq(AudioManager.STREAM_MUSIC));
-        doReturn(MEDIA_MAX_VOL).when(mAudioManager)
+        doReturn(MEDIA_MAX_VOL)
+                .when(mAudioManager)
                 .getStreamMaxVolume(eq(AudioManager.STREAM_MUSIC));
-        doReturn(CALL_MIN_VOL).when(mAudioManager)
+        doReturn(CALL_MIN_VOL)
+                .when(mAudioManager)
                 .getStreamMinVolume(eq(AudioManager.STREAM_VOICE_CALL));
-        doReturn(CALL_MAX_VOL).when(mAudioManager)
+        doReturn(CALL_MAX_VOL)
+                .when(mAudioManager)
                 .getStreamMaxVolume(eq(AudioManager.STREAM_VOICE_CALL));
 
         VolumeControlNativeInterface.setInstance(mNativeInterface);
@@ -136,7 +140,7 @@ public class VolumeControlServiceTest {
         doReturn(mLeAudioService).when(mServiceFactory).getLeAudioService();
 
         // Override the timeout value to speed up the test
-        VolumeControlStateMachine.sConnectTimeoutMs = TIMEOUT_MS;    // 1s
+        VolumeControlStateMachine.sConnectTimeoutMs = TIMEOUT_MS; // 1s
 
         // Set up the Connection State Changed receiver
         IntentFilter filter = new IntentFilter();
@@ -152,9 +156,11 @@ public class VolumeControlServiceTest {
         mDeviceQueueMap = new HashMap<>();
         mDeviceQueueMap.put(mDevice, new LinkedBlockingQueue<>());
         mDeviceQueueMap.put(mDeviceTwo, new LinkedBlockingQueue<>());
-        doReturn(BluetoothDevice.BOND_BONDED).when(mAdapterService)
+        doReturn(BluetoothDevice.BOND_BONDED)
+                .when(mAdapterService)
                 .getBondState(any(BluetoothDevice.class));
-        doReturn(new ParcelUuid[]{BluetoothUuid.VOLUME_CONTROL}).when(mAdapterService)
+        doReturn(new ParcelUuid[] {BluetoothUuid.VOLUME_CONTROL})
+                .when(mAdapterService)
                 .getRemoteUuids(any(BluetoothDevice.class));
     }
 
@@ -176,29 +182,27 @@ public class VolumeControlServiceTest {
         @Override
         public void onReceive(Context context, Intent intent) {
             try {
-                BluetoothDevice device = intent.getParcelableExtra(
-                        BluetoothDevice.EXTRA_DEVICE);
+                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                 Assert.assertNotNull(device);
                 LinkedBlockingQueue queue = mDeviceQueueMap.get(device);
                 Assert.assertNotNull(queue);
                 queue.put(intent);
             } catch (InterruptedException e) {
-                Assert.fail("Cannot add Intent to the Connection State queue: "
-                        + e.getMessage());
+                Assert.fail("Cannot add Intent to the Connection State queue: " + e.getMessage());
             }
         }
     }
 
-    private void verifyConnectionStateIntent(int timeoutMs, BluetoothDevice device,
-            int newState, int prevState) {
+    private void verifyConnectionStateIntent(
+            int timeoutMs, BluetoothDevice device, int newState, int prevState) {
         Intent intent = TestUtils.waitForIntent(timeoutMs, mDeviceQueueMap.get(device));
         Assert.assertNotNull(intent);
-        Assert.assertEquals(BluetoothVolumeControl.ACTION_CONNECTION_STATE_CHANGED,
-                intent.getAction());
+        Assert.assertEquals(
+                BluetoothVolumeControl.ACTION_CONNECTION_STATE_CHANGED, intent.getAction());
         Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));
         Assert.assertEquals(newState, intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1));
-        Assert.assertEquals(prevState, intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE,
-                -1));
+        Assert.assertEquals(
+                prevState, intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1));
     }
 
     private void verifyNoConnectionStateIntent(int timeoutMs, BluetoothDevice device) {
@@ -206,17 +210,13 @@ public class VolumeControlServiceTest {
         Assert.assertNull(intent);
     }
 
-    /**
-     * Test getting VolumeControl Service: getVolumeControlService()
-     */
+    /** Test getting VolumeControl Service: getVolumeControlService() */
     @Test
     public void testGetVolumeControlService() {
         Assert.assertEquals(mService, VolumeControlService.getVolumeControlService());
     }
 
-    /**
-     * Test stop VolumeControl Service
-     */
+    /** Test stop VolumeControl Service */
     @Test
     public void testStopVolumeControlService() throws Exception {
         // Prepare: connect
@@ -232,83 +232,101 @@ public class VolumeControlServiceTest {
     @Test
     public void testGetSetPolicy() {
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
-        Assert.assertEquals("Initial device policy",
+        Assert.assertEquals(
+                "Initial device policy",
                 BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
                 mService.getConnectionPolicy(mDevice));
 
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
-        Assert.assertEquals("Setting device policy to POLICY_FORBIDDEN",
+        Assert.assertEquals(
+                "Setting device policy to POLICY_FORBIDDEN",
                 BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
                 mService.getConnectionPolicy(mDevice));
 
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
-        Assert.assertEquals("Setting device policy to POLICY_ALLOWED",
+        Assert.assertEquals(
+                "Setting device policy to POLICY_ALLOWED",
                 BluetoothProfile.CONNECTION_POLICY_ALLOWED,
                 mService.getConnectionPolicy(mDevice));
     }
 
-    /**
-     * Test if getProfileConnectionPolicy works after the service is stopped.
-     */
+    /** Test if getProfileConnectionPolicy works after the service is stopped. */
     @Test
     public void testGetPolicyAfterStopped() throws Exception {
         mService.stop();
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
         int policy = mServiceBinder.getConnectionPolicy(mDevice, mAttributionSource);
-        Assert.assertEquals("Initial device policy",
-                BluetoothProfile.CONNECTION_POLICY_UNKNOWN, policy);
+        Assert.assertEquals(
+                "Initial device policy", BluetoothProfile.CONNECTION_POLICY_UNKNOWN, policy);
     }
 
-    /**
-     *  Test okToConnect method using various test cases
-     */
+    /** Test okToConnect method using various test cases */
     @Test
     public void testOkToConnect() {
         int badPolicyValue = 1024;
         int badBondState = 42;
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_NONE, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_NONE, badPolicyValue, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_BONDING, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_BONDING, badPolicyValue, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_ALLOWED, true);
-        testOkToConnectCase(mDevice,
-                BluetoothDevice.BOND_BONDED, badPolicyValue, false);
-        testOkToConnectCase(mDevice,
-                badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false);
-        testOkToConnectCase(mDevice,
-                badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
-        testOkToConnectCase(mDevice,
-                badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false);
-        testOkToConnectCase(mDevice,
-                badBondState, badPolicyValue, false);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_NONE,
+                BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+                false);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_NONE,
+                BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
+                false);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_NONE,
+                BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+                false);
+        testOkToConnectCase(mDevice, BluetoothDevice.BOND_NONE, badPolicyValue, false);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_BONDING,
+                BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+                false);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_BONDING,
+                BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
+                false);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_BONDING,
+                BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+                false);
+        testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDING, badPolicyValue, false);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_BONDED,
+                BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+                true);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_BONDED,
+                BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
+                false);
+        testOkToConnectCase(
+                mDevice,
+                BluetoothDevice.BOND_BONDED,
+                BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+                true);
+        testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDED, badPolicyValue, false);
+        testOkToConnectCase(
+                mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false);
+        testOkToConnectCase(
+                mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
+        testOkToConnectCase(
+                mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_ALLOWED, false);
+        testOkToConnectCase(mDevice, badBondState, badPolicyValue, false);
     }
 
     /**
@@ -318,35 +336,33 @@ public class VolumeControlServiceTest {
     public void testOutgoingConnectMissingVolumeControlUuid() {
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
 
         // Return No UUID
-        doReturn(new ParcelUuid[]{}).when(mAdapterService)
+        doReturn(new ParcelUuid[] {})
+                .when(mAdapterService)
                 .getRemoteUuids(any(BluetoothDevice.class));
 
         // Send a connect request
         Assert.assertFalse("Connect expected to fail", mService.connect(mDevice));
     }
 
-    /**
-     * Test that an outgoing connection to device that have Volume Control UUID is successful
-     */
+    /** Test that an outgoing connection to device that have Volume Control UUID is successful */
     @Test
     public void testOutgoingConnectDisconnectExistingVolumeControlUuid() throws Exception {
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
 
         // Return Volume Control UUID
-        doReturn(new ParcelUuid[]{BluetoothUuid.VOLUME_CONTROL}).when(mAdapterService)
+        doReturn(new ParcelUuid[] {BluetoothUuid.VOLUME_CONTROL})
+                .when(mAdapterService)
                 .getRemoteUuids(any(BluetoothDevice.class));
 
         // Send a connect request via binder
@@ -354,7 +370,10 @@ public class VolumeControlServiceTest {
                 "Connect expected to succeed", mServiceBinder.connect(mDevice, mAttributionSource));
 
         // Verify the connection state broadcast, and that we are in Connecting state
-        verifyConnectionStateIntent(TIMEOUT_MS, mDevice, BluetoothProfile.STATE_CONNECTING,
+        verifyConnectionStateIntent(
+                TIMEOUT_MS,
+                mDevice,
+                BluetoothProfile.STATE_CONNECTING,
                 BluetoothProfile.STATE_DISCONNECTED);
 
         // Send a disconnect request via binder
@@ -363,13 +382,14 @@ public class VolumeControlServiceTest {
                 mServiceBinder.disconnect(mDevice, mAttributionSource));
 
         // Verify the connection state broadcast, and that we are in Connecting state
-        verifyConnectionStateIntent(TIMEOUT_MS, mDevice, BluetoothProfile.STATE_DISCONNECTED,
+        verifyConnectionStateIntent(
+                TIMEOUT_MS,
+                mDevice,
+                BluetoothProfile.STATE_DISCONNECTED,
                 BluetoothProfile.STATE_CONNECTING);
     }
 
-    /**
-     * Test that an outgoing connection to device with POLICY_FORBIDDEN is rejected
-     */
+    /** Test that an outgoing connection to device with POLICY_FORBIDDEN is rejected */
     @Test
     public void testOutgoingConnectPolicyForbidden() {
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
@@ -377,23 +397,19 @@ public class VolumeControlServiceTest {
 
         // Set the device policy to POLICY_FORBIDDEN so connect() should fail
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
 
         // Send a connect request
         Assert.assertFalse("Connect expected to fail", mService.connect(mDevice));
     }
 
-    /**
-     * Test that an outgoing connection times out
-     */
+    /** Test that an outgoing connection times out */
     @Test
     public void testOutgoingConnectTimeout() throws Exception {
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
@@ -402,14 +418,19 @@ public class VolumeControlServiceTest {
         Assert.assertTrue("Connect failed", mService.connect(mDevice));
 
         // Verify the connection state broadcast, and that we are in Connecting state
-        verifyConnectionStateIntent(TIMEOUT_MS, mDevice, BluetoothProfile.STATE_CONNECTING,
+        verifyConnectionStateIntent(
+                TIMEOUT_MS,
+                mDevice,
+                BluetoothProfile.STATE_CONNECTING,
                 BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
-                mService.getConnectionState(mDevice));
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(mDevice));
 
         // Verify the connection state broadcast, and that we are in Disconnected state
-        verifyConnectionStateIntent(VolumeControlStateMachine.sConnectTimeoutMs * 2,
-                mDevice, BluetoothProfile.STATE_DISCONNECTED,
+        verifyConnectionStateIntent(
+                VolumeControlStateMachine.sConnectTimeoutMs * 2,
+                mDevice,
+                BluetoothProfile.STATE_DISCONNECTED,
                 BluetoothProfile.STATE_CONNECTING);
 
         int state = mServiceBinder.getConnectionState(mDevice, mAttributionSource);
@@ -424,58 +445,54 @@ public class VolumeControlServiceTest {
     public void testCreateStateMachineStackEvents() {
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
 
         // stack event: CONNECTION_STATE_CONNECTING - state machine should be created
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_CONNECTING,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // stack event: CONNECTION_STATE_DISCONNECTED - state machine should be removed
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_DISCONNECTED,
-                BluetoothProfile.STATE_CONNECTING);
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
         mService.bondStateChanged(mDevice, BluetoothDevice.BOND_NONE);
         Assert.assertFalse(mService.getDevices().contains(mDevice));
 
         // stack event: CONNECTION_STATE_CONNECTED - state machine should be created
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // stack event: CONNECTION_STATE_DISCONNECTED - state machine should be removed
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_DISCONNECTED,
-                BluetoothProfile.STATE_CONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
         mService.bondStateChanged(mDevice, BluetoothDevice.BOND_NONE);
         Assert.assertFalse(mService.getDevices().contains(mDevice));
 
         // stack event: CONNECTION_STATE_DISCONNECTING - state machine should not be created
-        generateUnexpectedConnectionMessageFromNative(mDevice,
-                BluetoothProfile.STATE_DISCONNECTING,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
-                mService.getConnectionState(mDevice));
+        generateUnexpectedConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED, mService.getConnectionState(mDevice));
         Assert.assertFalse(mService.getDevices().contains(mDevice));
 
         // stack event: CONNECTION_STATE_DISCONNECTED - state machine should not be created
-        generateUnexpectedConnectionMessageFromNative(mDevice,
-                BluetoothProfile.STATE_DISCONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
-                mService.getConnectionState(mDevice));
+        generateUnexpectedConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED, mService.getConnectionState(mDevice));
         Assert.assertFalse(mService.getDevices().contains(mDevice));
     }
 
@@ -487,49 +504,47 @@ public class VolumeControlServiceTest {
     public void testDeleteStateMachineDisconnectEvents() {
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
+        when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.VOLUME_CONTROL))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
 
         // stack event: CONNECTION_STATE_CONNECTING - state machine should be created
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_CONNECTING,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // stack event: CONNECTION_STATE_DISCONNECTED - state machine is not removed
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_DISCONNECTED,
-                BluetoothProfile.STATE_CONNECTING);
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // stack event: CONNECTION_STATE_CONNECTING - state machine remains
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_CONNECTING,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // device bond state marked as unbond - state machine is not removed
-        doReturn(BluetoothDevice.BOND_NONE).when(mAdapterService)
+        doReturn(BluetoothDevice.BOND_NONE)
+                .when(mAdapterService)
                 .getBondState(any(BluetoothDevice.class));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // stack event: CONNECTION_STATE_DISCONNECTED - state machine is removed
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_DISCONNECTED,
-                BluetoothProfile.STATE_CONNECTING);
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED, mService.getConnectionState(mDevice));
         Assert.assertFalse(mService.getDevices().contains(mDevice));
     }
 
-    /**
-     * Test that various Volume Control stack events will broadcast related states.
-     */
+    /** Test that various Volume Control stack events will broadcast related states. */
     @Test
     public void testVolumeControlStackEvents() {
         int group_id = -1;
@@ -537,8 +552,9 @@ public class VolumeControlServiceTest {
         boolean mute = false;
 
         // Send a message to trigger volume state changed broadcast
-        VolumeControlStackEvent stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
+        VolumeControlStackEvent stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
         stackEvent.device = mDevice;
         stackEvent.valueInt1 = group_id;
         stackEvent.valueInt2 = volume;
@@ -553,23 +569,31 @@ public class VolumeControlServiceTest {
 
     void testVolumeCalculations(int streamType, int minIdx, int maxIdx) {
         // Send a message to trigger volume state changed broadcast
-        final VolumeControlStackEvent stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
+        final VolumeControlStackEvent stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
         stackEvent.device = null;
-        stackEvent.valueInt1 = 1;       // groupId
-        stackEvent.valueBool1 = false;  // isMuted
-        stackEvent.valueBool2 = true;   // isAutonomous
-
-        IntStream.range(minIdx, maxIdx).forEach(idx -> {
-            // Given the reference volume index, set the LeAudio Volume
-            stackEvent.valueInt2 = getLeAudioVolume(idx,
-                            mAudioManager.getStreamMinVolume(streamType),
-                            mAudioManager.getStreamMaxVolume(streamType), streamType);
-            mService.messageFromNative(stackEvent);
-
-            // Verify that setting LeAudio Volume, sets the original volume index to Audio FW
-            verify(mAudioManager, times(1)).setStreamVolume(eq(streamType), eq(idx), anyInt());
-        });
+        stackEvent.valueInt1 = 1; // groupId
+        stackEvent.valueBool1 = false; // isMuted
+        stackEvent.valueBool2 = true; // isAutonomous
+
+        IntStream.range(minIdx, maxIdx)
+                .forEach(
+                        idx -> {
+                            // Given the reference volume index, set the LeAudio Volume
+                            stackEvent.valueInt2 =
+                                    getLeAudioVolume(
+                                            idx,
+                                            mAudioManager.getStreamMinVolume(streamType),
+                                            mAudioManager.getStreamMaxVolume(streamType),
+                                            streamType);
+                            mService.messageFromNative(stackEvent);
+
+                            // Verify that setting LeAudio Volume, sets the original volume index to
+                            // Audio FW
+                            verify(mAudioManager, times(1))
+                                    .setStreamVolume(eq(streamType), eq(idx), anyInt());
+                        });
     }
 
     @Test
@@ -585,9 +609,7 @@ public class VolumeControlServiceTest {
         testVolumeCalculations(AudioManager.STREAM_MUSIC, MEDIA_MIN_VOL, MEDIA_MAX_VOL);
     }
 
-    /**
-     * Test if autonomous Mute/Unmute propagates the event to audio manager.
-     */
+    /** Test if autonomous Mute/Unmute propagates the event to audio manager. */
     @Test
     public void testAutonomousMuteUnmute() {
         // TODO: b/329163385 - This test should be modified to run without having to set the flag to
@@ -598,36 +620,33 @@ public class VolumeControlServiceTest {
         int streamVol = getLeAudioVolume(19, MEDIA_MIN_VOL, MEDIA_MAX_VOL, streamType);
 
         // Send a message to trigger volume state changed broadcast
-        final VolumeControlStackEvent stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
+        final VolumeControlStackEvent stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
         stackEvent.device = null;
-        stackEvent.valueInt1 = 1;       // groupId
+        stackEvent.valueInt1 = 1; // groupId
         stackEvent.valueInt2 = streamVol;
-        stackEvent.valueBool1 = false;  // isMuted
-        stackEvent.valueBool2 = true;   // isAutonomous
+        stackEvent.valueBool1 = false; // isMuted
+        stackEvent.valueBool2 = true; // isAutonomous
 
-        doReturn(false).when(mAudioManager)
-                .isStreamMute(eq(AudioManager.STREAM_MUSIC));
+        doReturn(false).when(mAudioManager).isStreamMute(eq(AudioManager.STREAM_MUSIC));
 
         // Verify that muting LeAudio device, sets the mute state on the audio device
         stackEvent.valueBool1 = true;
         mService.messageFromNative(stackEvent);
-        verify(mAudioManager, times(1)).adjustStreamVolume(eq(streamType),
-                eq(AudioManager.ADJUST_MUTE), anyInt());
+        verify(mAudioManager, times(1))
+                .adjustStreamVolume(eq(streamType), eq(AudioManager.ADJUST_MUTE), anyInt());
 
-        doReturn(true).when(mAudioManager)
-                .isStreamMute(eq(AudioManager.STREAM_MUSIC));
+        doReturn(true).when(mAudioManager).isStreamMute(eq(AudioManager.STREAM_MUSIC));
 
         // Verify that unmuting LeAudio device, unsets the mute state on the audio device
         stackEvent.valueBool1 = false;
         mService.messageFromNative(stackEvent);
-        verify(mAudioManager, times(1)).adjustStreamVolume(eq(streamType),
-                eq(AudioManager.ADJUST_UNMUTE), anyInt());
+        verify(mAudioManager, times(1))
+                .adjustStreamVolume(eq(streamType), eq(AudioManager.ADJUST_UNMUTE), anyInt());
     }
 
-    /**
-     * Test Volume Control cache.
-     */
+    /** Test Volume Control cache. */
     @Test
     public void testVolumeCache() throws Exception {
         int groupId = 1;
@@ -641,8 +660,9 @@ public class VolumeControlServiceTest {
 
         volume = 10;
         // Send autonomous volume change.
-        VolumeControlStackEvent stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
+        VolumeControlStackEvent stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
         stackEvent.device = null;
         stackEvent.valueInt1 = groupId;
         stackEvent.valueInt2 = volume;
@@ -686,9 +706,7 @@ public class VolumeControlServiceTest {
         verify(mAudioManager, times(1)).setStreamVolume(anyInt(), eq(expectedVol), anyInt());
     }
 
-    /**
-     * Test Volume Control Mute cache.
-     */
+    /** Test Volume Control Mute cache. */
     @Test
     public void testMuteCache() throws Exception {
         int groupId = 1;
@@ -697,8 +715,9 @@ public class VolumeControlServiceTest {
         Assert.assertEquals(false, mService.getGroupMute(groupId));
 
         // Send autonomous volume change
-        VolumeControlStackEvent stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
+        VolumeControlStackEvent stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
         stackEvent.device = null;
         stackEvent.valueInt1 = groupId;
         stackEvent.valueInt2 = volume;
@@ -720,9 +739,7 @@ public class VolumeControlServiceTest {
         Assert.assertEquals(false, mService.getGroupMute(groupId));
     }
 
-    /**
-     * Test Volume Control with muted stream.
-     */
+    /** Test Volume Control with muted stream. */
     @Test
     public void testVolumeChangeWhileMuted() throws Exception {
         int groupId = 1;
@@ -731,8 +748,9 @@ public class VolumeControlServiceTest {
         Assert.assertEquals(false, mService.getGroupMute(groupId));
 
         // Set the initial volume state
-        VolumeControlStackEvent stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
+        VolumeControlStackEvent stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED);
         stackEvent.device = null;
         stackEvent.valueInt1 = groupId;
         stackEvent.valueInt2 = volume;
@@ -746,8 +764,7 @@ public class VolumeControlServiceTest {
         verify(mNativeInterface, times(1)).muteGroup(eq(groupId));
 
         // Make sure the volume is kept even when muted
-        doReturn(true).when(mAudioManager)
-                .isStreamMute(eq(AudioManager.STREAM_MUSIC));
+        doReturn(true).when(mAudioManager).isStreamMute(eq(AudioManager.STREAM_MUSIC));
         Assert.assertEquals(volume, mService.getGroupVolume(groupId));
 
         // Lower the volume and keep it mute
@@ -764,8 +781,7 @@ public class VolumeControlServiceTest {
 
         // Raise the volume and unmute
         volume += 10; // avoid previous volume levels and simplify mock verification
-        doReturn(false).when(mAudioManager)
-                .isStreamMute(eq(AudioManager.STREAM_MUSIC));
+        doReturn(false).when(mAudioManager).isStreamMute(eq(AudioManager.STREAM_MUSIC));
         mService.setGroupVolume(groupId, ++volume);
         Assert.assertEquals(false, mService.getGroupMute(groupId));
         verify(mNativeInterface, times(1)).setGroupVolume(eq(groupId), eq(volume));
@@ -778,8 +794,8 @@ public class VolumeControlServiceTest {
     }
 
     /**
-     * Test setting volume for a group member who connects after the volume level
-     * for a group was already changed and cached.
+     * Test setting volume for a group member who connects after the volume level for a group was
+     * already changed and cached.
      */
     @Test
     public void testLateConnectingDevice() throws Exception {
@@ -792,17 +808,15 @@ public class VolumeControlServiceTest {
 
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(any(BluetoothDevice.class),
-                        eq(BluetoothProfile.VOLUME_CONTROL)))
+        when(mDatabaseManager.getProfileConnectionPolicy(
+                        any(BluetoothDevice.class), eq(BluetoothProfile.VOLUME_CONTROL)))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
 
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         mService.setGroupVolume(groupId, groupVolume);
@@ -810,17 +824,17 @@ public class VolumeControlServiceTest {
         verify(mNativeInterface, times(0)).setVolume(eq(mDeviceTwo), eq(groupVolume));
 
         // Verify that second device gets the proper group volume level when connected
-        generateConnectionMessageFromNative(mDeviceTwo, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDeviceTwo));
+        generateConnectionMessageFromNative(
+                mDeviceTwo, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDeviceTwo));
         Assert.assertTrue(mService.getDevices().contains(mDeviceTwo));
         verify(mNativeInterface, times(1)).setVolume(eq(mDeviceTwo), eq(groupVolume));
     }
 
     /**
-     * Test setting volume for a new group member who is discovered after the volume level
-     * for a group was already changed and cached.
+     * Test setting volume for a new group member who is discovered after the volume level for a
+     * group was already changed and cached.
      */
     @Test
     public void testLateDiscoveredGroupMember() throws Exception {
@@ -833,27 +847,25 @@ public class VolumeControlServiceTest {
 
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(any(BluetoothDevice.class),
-                        eq(BluetoothProfile.VOLUME_CONTROL)))
+        when(mDatabaseManager.getProfileConnectionPolicy(
+                        any(BluetoothDevice.class), eq(BluetoothProfile.VOLUME_CONTROL)))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
 
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // Set the group volume
         mService.setGroupVolume(groupId, groupVolume);
 
         // Verify that second device will not get the group volume level if it is not a group member
-        generateConnectionMessageFromNative(mDeviceTwo, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDeviceTwo));
+        generateConnectionMessageFromNative(
+                mDeviceTwo, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDeviceTwo));
         Assert.assertTrue(mService.getDevices().contains(mDeviceTwo));
         verify(mNativeInterface, times(0)).setVolume(eq(mDeviceTwo), eq(groupVolume));
 
@@ -864,10 +876,9 @@ public class VolumeControlServiceTest {
     }
 
     /**
-     * Test setting volume to 0 for a group member who connects after the volume level
-     * for a group was already changed and cached. LeAudio has no knowledge of mute
-     * for anything else than telephony, thus setting volume level to 0 is considered
-     * as muting.
+     * Test setting volume to 0 for a group member who connects after the volume level for a group
+     * was already changed and cached. LeAudio has no knowledge of mute for anything else than
+     * telephony, thus setting volume level to 0 is considered as muting.
      */
     @Test
     public void testMuteLateConnectingDevice() throws Exception {
@@ -880,17 +891,15 @@ public class VolumeControlServiceTest {
 
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(any(BluetoothDevice.class),
-                        eq(BluetoothProfile.VOLUME_CONTROL)))
+        when(mDatabaseManager.getProfileConnectionPolicy(
+                        any(BluetoothDevice.class), eq(BluetoothProfile.VOLUME_CONTROL)))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
 
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // Set the initial volume and mute conditions
@@ -905,10 +914,10 @@ public class VolumeControlServiceTest {
         Assert.assertEquals(true, mService.getGroupMute(groupId));
 
         // Verify that second device gets the proper group volume level when connected
-        generateConnectionMessageFromNative(mDeviceTwo, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDeviceTwo));
+        generateConnectionMessageFromNative(
+                mDeviceTwo, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDeviceTwo));
         Assert.assertTrue(mService.getDevices().contains(mDeviceTwo));
         verify(mNativeInterface, times(1)).setVolume(eq(mDeviceTwo), eq(volume));
         // Check if new device was muted
@@ -916,10 +925,9 @@ public class VolumeControlServiceTest {
     }
 
     /**
-     * Test setting volume to 0 for a new group member who is discovered after the volume level
-     * for a group was already changed and cached. LeAudio has no knowledge of mute
-     * for anything else than telephony, thus setting volume level to 0 is considered
-     * as muting.
+     * Test setting volume to 0 for a new group member who is discovered after the volume level for
+     * a group was already changed and cached. LeAudio has no knowledge of mute for anything else
+     * than telephony, thus setting volume level to 0 is considered as muting.
      */
     @Test
     public void testMuteLateDiscoveredGroupMember() throws Exception {
@@ -932,17 +940,15 @@ public class VolumeControlServiceTest {
 
         // Update the device policy so okToConnect() returns true
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
-        when(mDatabaseManager
-                .getProfileConnectionPolicy(any(BluetoothDevice.class),
-                        eq(BluetoothProfile.VOLUME_CONTROL)))
+        when(mDatabaseManager.getProfileConnectionPolicy(
+                        any(BluetoothDevice.class), eq(BluetoothProfile.VOLUME_CONTROL)))
                 .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
         doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
         doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
 
-        generateConnectionMessageFromNative(mDevice, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDevice));
+        generateConnectionMessageFromNative(
+                mDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDevice));
         Assert.assertTrue(mService.getDevices().contains(mDevice));
 
         // Set the initial volume and mute conditions
@@ -950,10 +956,10 @@ public class VolumeControlServiceTest {
         mService.setGroupVolume(groupId, volume);
 
         // Verify that second device will not get the group volume level if it is not a group member
-        generateConnectionMessageFromNative(mDeviceTwo, BluetoothProfile.STATE_CONNECTED,
-                BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(mDeviceTwo));
+        generateConnectionMessageFromNative(
+                mDeviceTwo, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDeviceTwo));
         Assert.assertTrue(mService.getDevices().contains(mDeviceTwo));
         verify(mNativeInterface, times(0)).setVolume(eq(mDeviceTwo), eq(volume));
         // Check if it was not muted
@@ -978,8 +984,11 @@ public class VolumeControlServiceTest {
         Assert.assertTrue(
                 mServiceBinder.setConnectionPolicy(
                         mDevice, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, mAttributionSource));
-        verify(mDatabaseManager).setProfileConnectionPolicy(
-                mDevice, BluetoothProfile.VOLUME_CONTROL, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+        verify(mDatabaseManager)
+                .setProfileConnectionPolicy(
+                        mDevice,
+                        BluetoothProfile.VOLUME_CONTROL,
+                        BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
     }
 
     @Test
@@ -1410,23 +1419,28 @@ public class VolumeControlServiceTest {
         Assert.assertTrue("Connect failed", mService.connect(device));
 
         // Verify the connection state broadcast, and that we are in Connecting state
-        verifyConnectionStateIntent(TIMEOUT_MS, device, BluetoothProfile.STATE_CONNECTING,
+        verifyConnectionStateIntent(
+                TIMEOUT_MS,
+                device,
+                BluetoothProfile.STATE_CONNECTING,
                 BluetoothProfile.STATE_DISCONNECTED);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
-                mService.getConnectionState(device));
+        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(device));
 
         // Send a message to trigger connection completed
-        connCompletedEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        connCompletedEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         connCompletedEvent.device = device;
         connCompletedEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_CONNECTED;
         mService.messageFromNative(connCompletedEvent);
 
         // Verify the connection state broadcast, and that we are in Connected state
-        verifyConnectionStateIntent(TIMEOUT_MS, device, BluetoothProfile.STATE_CONNECTED,
+        verifyConnectionStateIntent(
+                TIMEOUT_MS,
+                device,
+                BluetoothProfile.STATE_CONNECTED,
                 BluetoothProfile.STATE_CONNECTING);
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED,
-                mService.getConnectionState(device));
+        Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(device));
 
         // Verify that the device is in the list of connected devices
         List connectedDevices =
@@ -1438,8 +1452,8 @@ public class VolumeControlServiceTest {
         }
     }
 
-    private void generateConnectionMessageFromNative(BluetoothDevice device, int newConnectionState,
-            int oldConnectionState) {
+    private void generateConnectionMessageFromNative(
+            BluetoothDevice device, int newConnectionState, int oldConnectionState) {
         VolumeControlStackEvent stackEvent =
                 new VolumeControlStackEvent(
                         VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
@@ -1450,8 +1464,8 @@ public class VolumeControlServiceTest {
         verifyConnectionStateIntent(TIMEOUT_MS, device, newConnectionState, oldConnectionState);
     }
 
-    private void generateUnexpectedConnectionMessageFromNative(BluetoothDevice device,
-            int newConnectionState, int oldConnectionState) {
+    private void generateUnexpectedConnectionMessageFromNative(
+            BluetoothDevice device, int newConnectionState, int oldConnectionState) {
         VolumeControlStackEvent stackEvent =
                 new VolumeControlStackEvent(
                         VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
@@ -1509,15 +1523,15 @@ public class VolumeControlServiceTest {
     }
 
     /**
-     *  Helper function to test okToConnect() method
+     * Helper function to test okToConnect() method
      *
-     *  @param device test device
-     *  @param bondState bond state value, could be invalid
-     *  @param policy value, could be invalid
-     *  @param expected expected result from okToConnect()
+     * @param device test device
+     * @param bondState bond state value, could be invalid
+     * @param policy value, could be invalid
+     * @param expected expected result from okToConnect()
      */
-    private void testOkToConnectCase(BluetoothDevice device, int bondState, int policy,
-            boolean expected) {
+    private void testOkToConnectCase(
+            BluetoothDevice device, int bondState, int policy, boolean expected) {
         doReturn(bondState).when(mAdapterService).getBondState(device);
         when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
         when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.VOLUME_CONTROL))
diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlStateMachineTest.java
index 80d25bdb4f9..809742c2e37 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlStateMachineTest.java
@@ -72,7 +72,9 @@ public class VolumeControlStateMachineTest {
     @Before
     public void setUp() throws Exception {
         mTargetContext = InstrumentationRegistry.getTargetContext();
-        InstrumentationRegistry.getInstrumentation().getUiAutomation().adoptShellPermissionIdentity();
+        InstrumentationRegistry.getInstrumentation()
+                .getUiAutomation()
+                .adoptShellPermissionIdentity();
         TestUtils.setAdapterService(mAdapterService);
 
         mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -83,10 +85,14 @@ public class VolumeControlStateMachineTest {
         // Set up thread and looper
         mHandlerThread = new HandlerThread("VolumeControlStateMachineTestHandlerThread");
         mHandlerThread.start();
-        mVolumeControlStateMachine = new VolumeControlStateMachine(mTestDevice,
-                mVolumeControlService, mVolumeControlNativeInterface, mHandlerThread.getLooper());
+        mVolumeControlStateMachine =
+                new VolumeControlStateMachine(
+                        mTestDevice,
+                        mVolumeControlService,
+                        mVolumeControlNativeInterface,
+                        mHandlerThread.getLooper());
         // Override the timeout value to speed up the test
-        mVolumeControlStateMachine.sConnectTimeoutMs = 1000;     // 1s
+        mVolumeControlStateMachine.sConnectTimeoutMs = 1000; // 1s
         mVolumeControlStateMachine.start();
     }
 
@@ -96,12 +102,11 @@ public class VolumeControlStateMachineTest {
         TestUtils.clearAdapterService(mAdapterService);
     }
 
-    /**
-     * Test that default state is disconnected
-     */
+    /** Test that default state is disconnected */
     @Test
     public void testDefaultDisconnectedState() {
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED,
                 mVolumeControlStateMachine.getConnectionState());
     }
 
@@ -114,9 +119,7 @@ public class VolumeControlStateMachineTest {
         doReturn(allow).when(mVolumeControlService).okToConnect(any(BluetoothDevice.class));
     }
 
-    /**
-     * Test that an incoming connection with policy forbidding connection is rejected
-     */
+    /** Test that an incoming connection with policy forbidding connection is rejected */
     @Test
     public void testIncomingPolicyReject() {
         allowConnection(false);
@@ -130,16 +133,15 @@ public class VolumeControlStateMachineTest {
         mVolumeControlStateMachine.sendMessage(VolumeControlStateMachine.STACK_EVENT, connStCh);
 
         // Verify that no connection state broadcast is executed
-        verify(mVolumeControlService, after(TIMEOUT_MS).never()).sendBroadcast(any(Intent.class),
-                anyString());
+        verify(mVolumeControlService, after(TIMEOUT_MS).never())
+                .sendBroadcast(any(Intent.class), anyString());
         // Check that we are in Disconnected state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Disconnected.class));
     }
 
-    /**
-     * Test that an incoming connection with policy allowing connection is accepted
-     */
+    /** Test that an incoming connection with policy allowing connection is accepted */
     @Test
     public void testIncomingPolicyAccept() {
         allowConnection(true);
@@ -154,82 +156,91 @@ public class VolumeControlStateMachineTest {
 
         // Verify that one connection state broadcast is executed
         ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class);
-        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(1)).sendBroadcast(
-                intentArgument1.capture(), anyString());
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
+        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(1))
+                .sendBroadcast(intentArgument1.capture(), anyString());
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTING,
                 intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1));
 
         // Check that we are in Connecting state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Connecting.class));
 
         // Send a message to trigger connection completed
         VolumeControlStackEvent connCompletedEvent =
-                new VolumeControlStackEvent(VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         connCompletedEvent.device = mTestDevice;
         connCompletedEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_CONNECTED;
-        mVolumeControlStateMachine.sendMessage(VolumeControlStateMachine.STACK_EVENT,
-                connCompletedEvent);
+        mVolumeControlStateMachine.sendMessage(
+                VolumeControlStateMachine.STACK_EVENT, connCompletedEvent);
 
         // Verify that the expected number of broadcasts are executed:
         // - two calls to broadcastConnectionState(): Disconnected -> Connecting -> Connected
         ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class);
-        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(2)).sendBroadcast(
-                intentArgument2.capture(), anyString());
+        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(2))
+                .sendBroadcast(intentArgument2.capture(), anyString());
         // Check that we are in Connected state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Connected.class));
     }
 
-    /**
-     * Test that an outgoing connection times out
-     */
+    /** Test that an outgoing connection times out */
     @Test
     public void testOutgoingTimeout() {
         allowConnection(true);
-        doReturn(true).when(mVolumeControlNativeInterface).connectVolumeControl(any(
-                BluetoothDevice.class));
-        doReturn(true).when(mVolumeControlNativeInterface).disconnectVolumeControl(any(
-                BluetoothDevice.class));
+        doReturn(true)
+                .when(mVolumeControlNativeInterface)
+                .connectVolumeControl(any(BluetoothDevice.class));
+        doReturn(true)
+                .when(mVolumeControlNativeInterface)
+                .disconnectVolumeControl(any(BluetoothDevice.class));
 
         // Send a connect request
         mVolumeControlStateMachine.sendMessage(VolumeControlStateMachine.CONNECT, mTestDevice);
 
         // Verify that one connection state broadcast is executed
         ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class);
-        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(1)).sendBroadcast(
-                intentArgument1.capture(),
-                anyString());
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
+        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(1))
+                .sendBroadcast(intentArgument1.capture(), anyString());
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTING,
                 intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1));
 
         // Check that we are in Connecting state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Connecting.class));
 
         // Verify that one connection state broadcast is executed
         ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class);
-        verify(mVolumeControlService, timeout(VolumeControlStateMachine.sConnectTimeoutMs * 2)
-                .times(2)).sendBroadcast(intentArgument2.capture(), anyString());
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
+        verify(
+                        mVolumeControlService,
+                        timeout(VolumeControlStateMachine.sConnectTimeoutMs * 2).times(2))
+                .sendBroadcast(intentArgument2.capture(), anyString());
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED,
                 intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1));
 
         // Check that we are in Disconnected state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Disconnected.class));
         verify(mVolumeControlNativeInterface).disconnectVolumeControl(eq(mTestDevice));
     }
 
-    /**
-     * Test that an incoming connection times out
-     */
+    /** Test that an incoming connection times out */
     @Test
     public void testIncomingTimeout() {
         allowConnection(true);
-        doReturn(true).when(mVolumeControlNativeInterface).connectVolumeControl(any(
-                BluetoothDevice.class));
-        doReturn(true).when(mVolumeControlNativeInterface).disconnectVolumeControl(any(
-                BluetoothDevice.class));
+        doReturn(true)
+                .when(mVolumeControlNativeInterface)
+                .connectVolumeControl(any(BluetoothDevice.class));
+        doReturn(true)
+                .when(mVolumeControlNativeInterface)
+                .disconnectVolumeControl(any(BluetoothDevice.class));
 
         // Inject an event for when incoming connection is requested
         VolumeControlStackEvent connStCh =
@@ -241,25 +252,30 @@ public class VolumeControlStateMachineTest {
 
         // Verify that one connection state broadcast is executed
         ArgumentCaptor intentArgument1 = ArgumentCaptor.forClass(Intent.class);
-        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(1)).sendBroadcast(
-                intentArgument1.capture(),
-                anyString());
-        Assert.assertEquals(BluetoothProfile.STATE_CONNECTING,
+        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(1))
+                .sendBroadcast(intentArgument1.capture(), anyString());
+        Assert.assertEquals(
+                BluetoothProfile.STATE_CONNECTING,
                 intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1));
 
         // Check that we are in Connecting state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Connecting.class));
 
         // Verify that one connection state broadcast is executed
         ArgumentCaptor intentArgument2 = ArgumentCaptor.forClass(Intent.class);
-        verify(mVolumeControlService, timeout(VolumeControlStateMachine.sConnectTimeoutMs * 2)
-                .times(2)).sendBroadcast(intentArgument2.capture(), anyString());
-        Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED,
+        verify(
+                        mVolumeControlService,
+                        timeout(VolumeControlStateMachine.sConnectTimeoutMs * 2).times(2))
+                .sendBroadcast(intentArgument2.capture(), anyString());
+        Assert.assertEquals(
+                BluetoothProfile.STATE_DISCONNECTED,
                 intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1));
 
         // Check that we are in Disconnected state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Disconnected.class));
         verify(mVolumeControlNativeInterface).disconnectVolumeControl(eq(mTestDevice));
     }
@@ -267,18 +283,22 @@ public class VolumeControlStateMachineTest {
     @Test
     public void testStatesChangesWithMessages() {
         allowConnection(true);
-        doReturn(true).when(mVolumeControlNativeInterface).connectVolumeControl(any(
-                BluetoothDevice.class));
-        doReturn(true).when(mVolumeControlNativeInterface).disconnectVolumeControl(any(
-                BluetoothDevice.class));
+        doReturn(true)
+                .when(mVolumeControlNativeInterface)
+                .connectVolumeControl(any(BluetoothDevice.class));
+        doReturn(true)
+                .when(mVolumeControlNativeInterface)
+                .disconnectVolumeControl(any(BluetoothDevice.class));
 
         // Check that we are in Disconnected state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Disconnected.class));
 
         mVolumeControlStateMachine.sendMessage(mVolumeControlStateMachine.DISCONNECT);
         // Check that we are in Disconnected state
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(),
                 IsInstanceOf.instanceOf(VolumeControlStateMachine.Disconnected.class));
 
         // disconnected -> connecting
@@ -291,8 +311,9 @@ public class VolumeControlStateMachineTest {
                 VolumeControlStateMachine.Disconnected.class);
 
         // disconnected -> connecting
-        VolumeControlStackEvent stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        VolumeControlStackEvent stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         stackEvent.device = mTestDevice;
         stackEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_CONNECTING;
         sendMessageAndVerifyTransition(
@@ -310,8 +331,9 @@ public class VolumeControlStateMachineTest {
                 mVolumeControlStateMachine.obtainMessage(mVolumeControlStateMachine.CONNECT),
                 VolumeControlStateMachine.Connecting.class);
         // connecting -> disconnecting
-        stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         stackEvent.device = mTestDevice;
         stackEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_DISCONNECTING;
         sendMessageAndVerifyTransition(
@@ -319,8 +341,9 @@ public class VolumeControlStateMachineTest {
                         mVolumeControlStateMachine.STACK_EVENT, stackEvent),
                 VolumeControlStateMachine.Disconnecting.class);
         // disconnecting -> connecting
-        stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         stackEvent.device = mTestDevice;
         stackEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_CONNECTING;
         sendMessageAndVerifyTransition(
@@ -328,8 +351,9 @@ public class VolumeControlStateMachineTest {
                         mVolumeControlStateMachine.STACK_EVENT, stackEvent),
                 VolumeControlStateMachine.Connecting.class);
         // connecting -> connected
-        stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         stackEvent.device = mTestDevice;
         stackEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_CONNECTED;
         sendMessageAndVerifyTransition(
@@ -337,8 +361,9 @@ public class VolumeControlStateMachineTest {
                         mVolumeControlStateMachine.STACK_EVENT, stackEvent),
                 VolumeControlStateMachine.Connected.class);
         // connected -> disconnecting
-        stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         stackEvent.device = mTestDevice;
         stackEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_DISCONNECTING;
         sendMessageAndVerifyTransition(
@@ -351,8 +376,9 @@ public class VolumeControlStateMachineTest {
                 VolumeControlStateMachine.Disconnected.class);
 
         // disconnected -> connected
-        stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         stackEvent.device = mTestDevice;
         stackEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_CONNECTED;
         sendMessageAndVerifyTransition(
@@ -361,13 +387,13 @@ public class VolumeControlStateMachineTest {
                 VolumeControlStateMachine.Connected.class);
         // connected -> disconnected
         sendMessageAndVerifyTransition(
-                mVolumeControlStateMachine.obtainMessage(
-                        mVolumeControlStateMachine.DISCONNECT),
+                mVolumeControlStateMachine.obtainMessage(mVolumeControlStateMachine.DISCONNECT),
                 VolumeControlStateMachine.Disconnecting.class);
 
         // disconnecting -> connected
-        stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         stackEvent.device = mTestDevice;
         stackEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_CONNECTED;
         sendMessageAndVerifyTransition(
@@ -375,8 +401,9 @@ public class VolumeControlStateMachineTest {
                         mVolumeControlStateMachine.STACK_EVENT, stackEvent),
                 VolumeControlStateMachine.Connected.class);
         // connected -> disconnected
-        stackEvent = new VolumeControlStackEvent(
-                VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
+        stackEvent =
+                new VolumeControlStackEvent(
+                        VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED);
         stackEvent.device = mTestDevice;
         stackEvent.valueInt1 = VolumeControlStackEvent.CONNECTION_STATE_DISCONNECTED;
         sendMessageAndVerifyTransition(
@@ -389,9 +416,9 @@ public class VolumeControlStateMachineTest {
         Mockito.clearInvocations(mVolumeControlService);
         mVolumeControlStateMachine.sendMessage(msg);
         // Verify that one connection state broadcast is executed
-        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(1)).sendBroadcast(
-                any(Intent.class), anyString());
-        Assert.assertThat(mVolumeControlStateMachine.getCurrentState(),
-                IsInstanceOf.instanceOf(type));
+        verify(mVolumeControlService, timeout(TIMEOUT_MS).times(1))
+                .sendBroadcast(any(Intent.class), anyString());
+        Assert.assertThat(
+                mVolumeControlStateMachine.getCurrentState(), IsInstanceOf.instanceOf(type));
     }
 }
-- 
GitLab