[Audiosharing] Migrate feature from overlay to Settings

Bug: 340379827
Test: atest
Change-Id: I3a88ac1d2f575f3be1f26f617479bbfd25cf6a8e
This commit is contained in:
Yiyi Shen
2024-05-14 12:50:20 +08:00
parent a719e78a4c
commit e5bd60a0cf
133 changed files with 18497 additions and 275 deletions

View File

@@ -24,26 +24,32 @@ import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothStatusCodes;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.platform.test.flag.junit.SetFlagsRule;
import android.util.Pair;
import com.android.settings.connecteddevice.DevicePreferenceCallback;
import com.android.settings.connecteddevice.audiosharing.AudioSharingFeatureProvider;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowAudioManager;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.flags.Flags;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -55,6 +61,7 @@ import org.robolectric.shadow.api.Shadow;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(
@@ -66,6 +73,8 @@ import java.util.Collection;
public class AvailableMediaBluetoothDeviceUpdaterTest {
private static final String MAC_ADDRESS = "04:52:C7:0B:D8:3C";
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Mock private DashboardFragment mDashboardFragment;
@Mock private DevicePreferenceCallback mDevicePreferenceCallback;
@Mock private CachedBluetoothDevice mCachedBluetoothDevice;
@@ -73,6 +82,9 @@ public class AvailableMediaBluetoothDeviceUpdaterTest {
@Mock private Drawable mDrawable;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private CachedBluetoothDeviceManager mCachedDeviceManager;
@Mock private LocalBluetoothProfileManager mProfileManager;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private BluetoothLeBroadcastReceiveState mBroadcastReceiveState;
private Context mContext;
private AvailableMediaBluetoothDeviceUpdater mBluetoothDeviceUpdater;
@@ -80,20 +92,24 @@ public class AvailableMediaBluetoothDeviceUpdaterTest {
private AudioManager mAudioManager;
private BluetoothDevicePreference mPreference;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private AudioSharingFeatureProvider mFeatureProvider;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mFeatureProvider = FakeFeatureFactory.setupForTest().getAudioSharingFeatureProvider();
mAudioManager = mContext.getSystemService(AudioManager.class);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBtManager = Utils.getLocalBtManager(mContext);
when(mProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
when(mLocalBtManager.getProfileManager()).thenReturn(mProfileManager);
when(mLocalBtManager.getCachedDeviceManager()).thenReturn(mCachedDeviceManager);
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mCachedDevices = new ArrayList<>();
mCachedDevices.add(mCachedBluetoothDevice);
when(mCachedDeviceManager.getCachedDevicesCopy()).thenReturn(mCachedDevices);
@@ -252,14 +268,16 @@ public class AvailableMediaBluetoothDeviceUpdaterTest {
@Test
public void
onProfileConnectionStateChanged_leaDeviceConnected_notInCallNoSharing_addsPreference() {
onProfileConnectionStateChanged_leaConnected_notInCallSharingFlagOff_addsPreference() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mAudioManager.setMode(AudioManager.MODE_NORMAL);
when(mBluetoothDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class)))
.thenReturn(true);
when(mCachedBluetoothDevice.isConnectedLeAudioDevice()).thenReturn(true);
when(mFeatureProvider.isAudioSharingFilterMatched(
any(CachedBluetoothDevice.class), any(LocalBluetoothManager.class)))
.thenReturn(false);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mBroadcastReceiveState));
List<Long> bisSyncState = new ArrayList<>();
bisSyncState.add(1L);
when(mBroadcastReceiveState.getBisSyncState()).thenReturn(bisSyncState);
mBluetoothDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
@@ -271,14 +289,50 @@ public class AvailableMediaBluetoothDeviceUpdaterTest {
@Test
public void
onProfileConnectionStateChanged_leaDeviceConnected_inCallNoSharing_addsPreference() {
onProfileConnectionStateChanged_leaConnected_notInCallNotInSharing_addsPreference() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mAudioManager.setMode(AudioManager.MODE_NORMAL);
when(mBluetoothDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class)))
.thenReturn(true);
when(mCachedBluetoothDevice.isConnectedLeAudioDevice()).thenReturn(true);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mBluetoothDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
verify(mBluetoothDeviceUpdater).addPreference(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaConnected_inCallSharingFlagOff_addsPreference() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mAudioManager.setMode(AudioManager.MODE_IN_CALL);
when(mBluetoothDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class)))
.thenReturn(true);
when(mCachedBluetoothDevice.isConnectedLeAudioDevice()).thenReturn(true);
when(mFeatureProvider.isAudioSharingFilterMatched(
any(CachedBluetoothDevice.class), any(LocalBluetoothManager.class)))
.thenReturn(false);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mBroadcastReceiveState));
List<Long> bisSyncState = new ArrayList<>();
bisSyncState.add(1L);
when(mBroadcastReceiveState.getBisSyncState()).thenReturn(bisSyncState);
mBluetoothDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
verify(mBluetoothDeviceUpdater).addPreference(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaConnected_inCallNotInSharing_addsPreference() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mAudioManager.setMode(AudioManager.MODE_IN_CALL);
when(mBluetoothDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class)))
.thenReturn(true);
when(mCachedBluetoothDevice.isConnectedLeAudioDevice()).thenReturn(true);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mBluetoothDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
@@ -291,14 +345,16 @@ public class AvailableMediaBluetoothDeviceUpdaterTest {
@Test
public void
onProfileConnectionStateChanged_leaDeviceConnected_notInCallInSharing_removesPref() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mAudioManager.setMode(AudioManager.MODE_NORMAL);
when(mBluetoothDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class)))
.thenReturn(true);
when(mCachedBluetoothDevice.isConnectedLeAudioDevice()).thenReturn(true);
when(mCachedBluetoothDevice.isConnectedA2dpDevice()).thenReturn(true);
when(mFeatureProvider.isAudioSharingFilterMatched(
any(CachedBluetoothDevice.class), any(LocalBluetoothManager.class)))
.thenReturn(true);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mBroadcastReceiveState));
List<Long> bisSyncState = new ArrayList<>();
bisSyncState.add(1L);
when(mBroadcastReceiveState.getBisSyncState()).thenReturn(bisSyncState);
mBluetoothDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
@@ -310,14 +366,16 @@ public class AvailableMediaBluetoothDeviceUpdaterTest {
@Test
public void onProfileConnectionStateChanged_leaDeviceConnected_inCallInSharing_removesPref() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mAudioManager.setMode(AudioManager.MODE_NORMAL);
when(mBluetoothDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class)))
.thenReturn(true);
when(mCachedBluetoothDevice.isConnectedLeAudioDevice()).thenReturn(true);
when(mCachedBluetoothDevice.isConnectedHfpDevice()).thenReturn(true);
when(mFeatureProvider.isAudioSharingFilterMatched(
any(CachedBluetoothDevice.class), any(LocalBluetoothManager.class)))
.thenReturn(true);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mBroadcastReceiveState));
List<Long> bisSyncState = new ArrayList<>();
bisSyncState.add(1L);
when(mBroadcastReceiveState.getBisSyncState()).thenReturn(bisSyncState);
mBluetoothDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,

View File

@@ -22,18 +22,24 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.shadows.ShadowLooper.shadowMainLooper;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcastAssistant;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothStatusCodes;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.platform.test.flag.junit.SetFlagsRule;
import android.util.Pair;
import androidx.appcompat.app.AlertDialog;
@@ -48,16 +54,21 @@ import com.android.settings.R;
import com.android.settings.bluetooth.AvailableMediaBluetoothDeviceUpdater;
import com.android.settings.bluetooth.BluetoothDevicePreference;
import com.android.settings.bluetooth.Utils;
import com.android.settings.connecteddevice.audiosharing.AudioSharingDialogHandler;
import com.android.settings.testutils.shadow.ShadowAlertDialogCompat;
import com.android.settings.testutils.shadow.ShadowAudioManager;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settingslib.bluetooth.BluetoothCallback;
import com.android.settingslib.bluetooth.BluetoothEventManager;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.HearingAidInfo;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
@@ -71,17 +82,22 @@ import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import java.util.concurrent.Executor;
/** Tests for {@link AvailableMediaDeviceGroupController}. */
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowAudioManager.class,
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
ShadowAlertDialogCompat.class,
})
public class AvailableMediaDeviceGroupControllerTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private static final String TEST_DEVICE_ADDRESS = "00:A1:A1:A1:A1:A1";
private static final String PREFERENCE_KEY_1 = "pref_key_1";
@@ -96,17 +112,20 @@ public class AvailableMediaDeviceGroupControllerTest {
@Mock private PackageManager mPackageManager;
@Mock private BluetoothEventManager mEventManager;
@Mock private LocalBluetoothManager mLocalBluetoothManager;
@Mock private LocalBluetoothProfileManager mLocalBtProfileManager;
@Mock private CachedBluetoothDeviceManager mCachedDeviceManager;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private CachedBluetoothDevice mCachedBluetoothDevice;
@Mock private BluetoothDevice mDevice;
@Mock
private Drawable mDrawable;
@Mock private Drawable mDrawable;
@Mock private AudioSharingDialogHandler mDialogHandler;
private PreferenceGroup mPreferenceGroup;
private Context mContext;
private Preference mPreference;
private AvailableMediaDeviceGroupController mAvailableMediaDeviceGroupController;
private AudioManager mAudioManager;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private LifecycleOwner mLifecycleOwner;
private Lifecycle mLifecycle;
@@ -123,19 +142,27 @@ public class AvailableMediaDeviceGroupControllerTest {
doReturn(mPackageManager).when(mContext).getPackageManager();
doReturn(true).when(mPackageManager).hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_NOT_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_NOT_SUPPORTED);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBluetoothManager;
mLocalBluetoothManager = Utils.getLocalBtManager(mContext);
mAudioManager = mContext.getSystemService(AudioManager.class);
doReturn(mEventManager).when(mLocalBluetoothManager).getEventManager();
when(mLocalBluetoothManager.getProfileManager()).thenReturn(mLocalBtProfileManager);
when(mLocalBluetoothManager.getCachedDeviceManager()).thenReturn(mCachedDeviceManager);
when(mCachedDeviceManager.findDevice(any(BluetoothDevice.class)))
.thenReturn(mCachedBluetoothDevice);
when(mCachedBluetoothDevice.getAddress()).thenReturn(TEST_DEVICE_ADDRESS);
mAvailableMediaDeviceGroupController =
spy(new AvailableMediaDeviceGroupController(mContext, null, mLifecycle));
spy(new AvailableMediaDeviceGroupController(mContext));
mAvailableMediaDeviceGroupController.setBluetoothDeviceUpdater(
mAvailableMediaBluetoothDeviceUpdater);
mAvailableMediaDeviceGroupController.setDialogHandler(mDialogHandler);
mAvailableMediaDeviceGroupController.setFragmentManager(
mActivity.getSupportFragmentManager());
mAvailableMediaDeviceGroupController.mPreferenceGroup = mPreferenceGroup;
@@ -181,23 +208,58 @@ public class AvailableMediaDeviceGroupControllerTest {
}
@Test
public void testRegister() {
public void testRegister_audioSharingOff() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
// register the callback in onStart()
mAvailableMediaDeviceGroupController.onStart(mLifecycleOwner);
verify(mAvailableMediaBluetoothDeviceUpdater).registerCallback();
verify(mLocalBluetoothManager.getEventManager())
.registerCallback(any(BluetoothCallback.class));
verify(mEventManager).registerCallback(any(BluetoothCallback.class));
verify(mAvailableMediaBluetoothDeviceUpdater).refreshPreference();
verify(mAssistant, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDialogHandler, times(0)).registerCallbacks(any(Executor.class));
}
@Test
public void testUnregister() {
public void testRegister_audioSharingOn() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
setUpBroadcast();
// register the callback in onStart()
mAvailableMediaDeviceGroupController.onStart(mLifecycleOwner);
verify(mAvailableMediaBluetoothDeviceUpdater).registerCallback();
verify(mEventManager).registerCallback(any(BluetoothCallback.class));
verify(mAvailableMediaBluetoothDeviceUpdater).refreshPreference();
verify(mAssistant)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDialogHandler).registerCallbacks(any(Executor.class));
}
@Test
public void testUnregister_audioSharingOff() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
// unregister the callback in onStop()
mAvailableMediaDeviceGroupController.onStop(mLifecycleOwner);
verify(mAvailableMediaBluetoothDeviceUpdater).unregisterCallback();
verify(mLocalBluetoothManager.getEventManager())
.unregisterCallback(any(BluetoothCallback.class));
verify(mEventManager).unregisterCallback(any(BluetoothCallback.class));
verify(mAssistant, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDialogHandler, times(0)).unregisterCallbacks();
}
@Test
public void testUnregister_audioSharingOn() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
setUpBroadcast();
// unregister the callback in onStop()
mAvailableMediaDeviceGroupController.onStop(mLifecycleOwner);
verify(mAvailableMediaBluetoothDeviceUpdater).unregisterCallback();
verify(mEventManager).unregisterCallback(any(BluetoothCallback.class));
verify(mAssistant)
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDialogHandler).unregisterCallbacks();
}
@Test
@@ -267,7 +329,8 @@ public class AvailableMediaDeviceGroupControllerTest {
}
@Test
public void onDeviceClick_setActive() {
public void onDeviceClick_audioSharingOff_setActive() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mCachedBluetoothDevice.getDevice()).thenReturn(mDevice);
Pair<Drawable, String> pair = new Pair<>(mDrawable, TEST_DEVICE_NAME);
when(mCachedBluetoothDevice.getDrawableWithDescription()).thenReturn(pair);
@@ -280,4 +343,37 @@ public class AvailableMediaDeviceGroupControllerTest {
mAvailableMediaDeviceGroupController.onDeviceClick(preference);
verify(mCachedBluetoothDevice).setActive();
}
@Test
public void onDeviceClick_audioSharingOn_dialogHandler() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
setUpBroadcast();
when(mCachedBluetoothDevice.getDevice()).thenReturn(mDevice);
Pair<Drawable, String> pair = new Pair<>(mDrawable, TEST_DEVICE_NAME);
when(mCachedBluetoothDevice.getDrawableWithDescription()).thenReturn(pair);
BluetoothDevicePreference preference =
new BluetoothDevicePreference(
mContext,
mCachedBluetoothDevice,
true,
BluetoothDevicePreference.SortType.TYPE_NO_SORT);
mAvailableMediaDeviceGroupController.onDeviceClick(preference);
verify(mDialogHandler)
.handleDeviceConnected(mCachedBluetoothDevice, /* userTriggered= */ true);
}
private void setUpBroadcast() {
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
when(mLocalBtProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
doNothing()
.when(mAssistant)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
doNothing()
.when(mAssistant)
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
}
}

View File

@@ -72,6 +72,9 @@ public class ConnectedDeviceDashboardFragmentTest {
private static final String KEY_DISCOVERABLE_FOOTER = "discoverable_footer";
private static final String KEY_SAVED_DEVICE_SEE_ALL = "previously_connected_devices_see_all";
private static final String KEY_FAST_PAIR_DEVICE_SEE_ALL = "fast_pair_devices_see_all";
private static final String KEY_AUDIO_SHARING_DEVICES = "audio_sharing_device_list";
private static final String KEY_AUDIO_SHARING_SETTINGS =
"connected_device_audio_sharing_settings";
private static final String KEY_ADD_BT_DEVICES = "add_bt_devices";
private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
private static final String SYSTEMUI_PACKAGE_NAME = "com.android.systemui";
@@ -84,7 +87,6 @@ public class ConnectedDeviceDashboardFragmentTest {
private Context mContext;
private ConnectedDeviceDashboardFragment mFragment;
private FakeFeatureFactory mFeatureFactory;
private AvailableMediaDeviceGroupController mMediaDeviceGroupController;
@Before
public void setUp() {
@@ -93,21 +95,13 @@ public class ConnectedDeviceDashboardFragmentTest {
mContext = spy(RuntimeEnvironment.application);
mFragment = new ConnectedDeviceDashboardFragment();
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_SUBSEQUENT_PAIR_SETTINGS_INTEGRATION);
mSetFlagsRule.enableFlags(com.android.settingslib.flags.Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory
.getFastPairFeatureProvider()
.getFastPairDeviceUpdater(
any(Context.class), any(DevicePreferenceCallback.class)))
.thenReturn(mFastPairDeviceUpdater);
when(mFeatureFactory
.getAudioSharingFeatureProvider()
.createAudioSharingDevicePreferenceController(mContext, null, null))
.thenReturn(null);
mMediaDeviceGroupController = new AvailableMediaDeviceGroupController(mContext, null, null);
when(mFeatureFactory
.getAudioSharingFeatureProvider()
.createAvailableMediaDeviceGroupController(mContext, null, null))
.thenReturn(mMediaDeviceGroupController);
doReturn(mPackageManager).when(mContext).getPackageManager();
doReturn(true).when(mPackageManager).hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
}
@@ -135,7 +129,9 @@ public class ConnectedDeviceDashboardFragmentTest {
KEY_NEARBY_DEVICES,
KEY_DISCOVERABLE_FOOTER,
KEY_SAVED_DEVICE_SEE_ALL,
KEY_FAST_PAIR_DEVICE_SEE_ALL);
KEY_FAST_PAIR_DEVICE_SEE_ALL,
KEY_AUDIO_SHARING_DEVICES,
KEY_AUDIO_SHARING_SETTINGS);
}
@Test

View File

@@ -0,0 +1,88 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothStatusCodes;
import android.os.Bundle;
import android.platform.test.flag.junit.SetFlagsRule;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowBluetoothAdapter.class})
public class AudioSharingActivityTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private AudioSharingActivity mActivity;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
@Before
public void setUp() {
mActivity = spy(Robolectric.buildActivity(AudioSharingActivity.class).get());
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
}
@Test
public void isValidFragment_returnsTrue() {
assertThat(mActivity.isValidFragment(AudioSharingDashboardFragment.class.getName()))
.isTrue();
}
@Test
public void isValidFragment_returnsFalse() {
assertThat(mActivity.isValidFragment("")).isFalse();
}
@Test
public void onCreate_flagOff_finish() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mActivity.onCreate(new Bundle());
verify(mActivity).finish();
}
@Test
public void onCreate_flagOn_create() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mActivity.onCreate(new Bundle());
verify(mActivity, times(0)).finish();
}
}

View File

@@ -0,0 +1,270 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothStatusCodes;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import android.util.Pair;
import androidx.preference.Preference;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.bluetooth.BluetoothDevicePreference;
import com.android.settings.bluetooth.Utils;
import com.android.settings.connecteddevice.DevicePreferenceCallback;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settings.testutils.shadow.ShadowThreadUtils;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.flags.Flags;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
ShadowThreadUtils.class
})
public class AudioSharingBluetoothDeviceUpdaterTest {
private static final String MAC_ADDRESS = "04:52:C7:0B:D8:3C";
private static final String TEST_DEVICE_NAME = "test";
private static final String PREF_KEY = "audio_sharing_bt";
private static final String TAG = "AudioSharingBluetoothDeviceUpdater";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Mock private DevicePreferenceCallback mDevicePreferenceCallback;
@Mock private CachedBluetoothDevice mCachedBluetoothDevice;
@Mock private BluetoothDevice mBluetoothDevice;
@Mock private Drawable mDrawable;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private CachedBluetoothDeviceManager mCachedDeviceManager;
@Mock private LocalBluetoothProfileManager mLocalBtProfileManager;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private BluetoothLeBroadcastReceiveState mState;
private Context mContext;
private AudioSharingBluetoothDeviceUpdater mDeviceUpdater;
private Collection<CachedBluetoothDevice> mCachedDevices;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
@Before
public void setUp() {
mContext = ApplicationProvider.getApplicationContext();
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBtManager = Utils.getLocalBtManager(mContext);
when(mLocalBtManager.getCachedDeviceManager()).thenReturn(mCachedDeviceManager);
when(mLocalBtManager.getProfileManager()).thenReturn(mLocalBtProfileManager);
when(mLocalBtProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
List<Long> bisSyncState = new ArrayList<>();
bisSyncState.add(1L);
when(mState.getBisSyncState()).thenReturn(bisSyncState);
Pair<Drawable, String> pairs = new Pair<>(mDrawable, TEST_DEVICE_NAME);
doReturn(TEST_DEVICE_NAME).when(mCachedBluetoothDevice).getName();
doReturn(mBluetoothDevice).when(mCachedBluetoothDevice).getDevice();
doReturn(MAC_ADDRESS).when(mCachedBluetoothDevice).getAddress();
doReturn(pairs).when(mCachedBluetoothDevice).getDrawableWithDescription();
doReturn(ImmutableSet.of()).when(mCachedBluetoothDevice).getMemberDevice();
doReturn("").when(mCachedBluetoothDevice).getConnectionSummary();
mCachedDevices = new ArrayList<>();
mCachedDevices.add(mCachedBluetoothDevice);
when(mCachedDeviceManager.getCachedDevicesCopy()).thenReturn(mCachedDevices);
doNothing().when(mDevicePreferenceCallback).onDeviceAdded(any(Preference.class));
doNothing().when(mDevicePreferenceCallback).onDeviceRemoved(any(Preference.class));
mDeviceUpdater =
spy(
new AudioSharingBluetoothDeviceUpdater(
mContext, mDevicePreferenceCallback, /* metricsCategory= */ 0));
mDeviceUpdater.setPrefContext(mContext);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceConnected_flagOff_removesPref() {
setupPreferenceMapWithDevice();
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof BluetoothDevicePreference).isTrue();
assertThat(((BluetoothDevicePreference) captor.getValue()).getBluetoothDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceConnected_noSource_removesPref() {
setupPreferenceMapWithDevice();
when(mAssistant.getAllSources(mBluetoothDevice)).thenReturn(ImmutableList.of());
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof BluetoothDevicePreference).isTrue();
assertThat(((BluetoothDevicePreference) captor.getValue()).getBluetoothDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_deviceIsNotInList_removesPref() {
setupPreferenceMapWithDevice();
mCachedDevices.clear();
when(mCachedDeviceManager.getCachedDevicesCopy()).thenReturn(mCachedDevices);
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof BluetoothDevicePreference).isTrue();
assertThat(((BluetoothDevicePreference) captor.getValue()).getBluetoothDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceDisconnected_removesPref() {
setupPreferenceMapWithDevice();
when(mDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class))).thenReturn(false);
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_DISCONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof BluetoothDevicePreference).isTrue();
assertThat(((BluetoothDevicePreference) captor.getValue()).getBluetoothDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceDisconnecting_removesPref() {
setupPreferenceMapWithDevice();
doReturn(false).when(mCachedBluetoothDevice).isConnectedLeAudioDevice();
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof BluetoothDevicePreference).isTrue();
assertThat(((BluetoothDevicePreference) captor.getValue()).getBluetoothDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceConnected_hasSource_addsPreference() {
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
setupPreferenceMapWithDevice();
verify(mDevicePreferenceCallback).onDeviceAdded(captor.capture());
assertThat(captor.getValue() instanceof BluetoothDevicePreference).isTrue();
assertThat(((BluetoothDevicePreference) captor.getValue()).getBluetoothDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void getLogTag_returnsCorrectTag() {
assertThat(mDeviceUpdater.getLogTag()).isEqualTo(TAG);
}
@Test
public void getPreferenceKey_returnsCorrectKey() {
assertThat(mDeviceUpdater.getPreferenceKey()).isEqualTo(PREF_KEY);
}
private void setupPreferenceMapWithDevice() {
// Add device to preferenceMap
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mAssistant.getAllSources(mBluetoothDevice)).thenReturn(ImmutableList.of(mState));
when(mDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class))).thenReturn(true);
doReturn(true).when(mCachedBluetoothDevice).isConnectedLeAudioDevice();
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
}
}

View File

@@ -0,0 +1,271 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothLeBroadcast;
import android.bluetooth.BluetoothStatusCodes;
import android.content.Context;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.PreferenceScreen;
import androidx.preference.TwoStatePreference;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settings.bluetooth.Utils;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settings.testutils.shadow.ShadowThreadUtils;
import com.android.settingslib.bluetooth.BluetoothEventManager;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.bluetooth.VolumeControlProfile;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import java.util.concurrent.Executor;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
ShadowThreadUtils.class,
})
public class AudioSharingCompatibilityPreferenceControllerTest {
private static final String PREF_KEY = "audio_sharing_stream_compatibility";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Spy Context mContext = ApplicationProvider.getApplicationContext();
@Mock private PreferenceScreen mScreen;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private BluetoothEventManager mBtEventManager;
@Mock private LocalBluetoothProfileManager mBtProfileManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private VolumeControlProfile mVolumeControl;
@Mock private TwoStatePreference mPreference;
private AudioSharingCompatibilityPreferenceController mController;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private LocalBluetoothManager mLocalBluetoothManager;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
@Before
public void setUp() {
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBluetoothManager = Utils.getLocalBtManager(mContext);
when(mLocalBluetoothManager.getEventManager()).thenReturn(mBtEventManager);
when(mLocalBluetoothManager.getProfileManager()).thenReturn(mBtProfileManager);
when(mBtProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
when(mBtProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
when(mBtProfileManager.getVolumeControlProfile()).thenReturn(mVolumeControl);
when(mBroadcast.isProfileReady()).thenReturn(true);
when(mAssistant.isProfileReady()).thenReturn(true);
when(mVolumeControl.isProfileReady()).thenReturn(true);
mController = new AudioSharingCompatibilityPreferenceController(mContext, PREF_KEY);
when(mScreen.findPreference(PREF_KEY)).thenReturn(mPreference);
}
@Test
public void onStart_flagOn_registerCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mBroadcast)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcast.Callback.class));
verify(mBtProfileManager, times(0)).addServiceListener(mController);
}
@Test
public void onStart_flagOnProfileNotReady_registerProfileCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isProfileReady()).thenReturn(false);
mController.onStart(mLifecycleOwner);
verify(mBroadcast, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcast.Callback.class));
verify(mBtProfileManager).addServiceListener(mController);
}
@Test
public void onStart_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mBroadcast, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcast.Callback.class));
}
@Test
public void onStop_flagOn_unregisterCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mController.onStop(mLifecycleOwner);
verify(mBroadcast).unregisterServiceCallBack(any(BluetoothLeBroadcast.Callback.class));
verify(mBtProfileManager).removeServiceListener(mController);
}
@Test
public void onStop_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mController.onStop(mLifecycleOwner);
verify(mBroadcast, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcast.Callback.class));
verify(mBtProfileManager, times(0)).removeServiceListener(mController);
}
@Test
public void onServiceConnected_updateSwitch() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(null)).thenReturn(false);
when(mBroadcast.isProfileReady()).thenReturn(false);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
verify(mPreference).setEnabled(true);
when(mBroadcast.isEnabled(null)).thenReturn(true);
when(mBroadcast.isProfileReady()).thenReturn(true);
mController.onServiceConnected();
shadowOf(Looper.getMainLooper()).idle();
verify(mBroadcast)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcast.Callback.class));
verify(mBtProfileManager).removeServiceListener(mController);
verify(mPreference).setEnabled(false);
}
@Test
public void getAvailabilityStatus_flagOn() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_flagOff() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void getPreferenceKey_returnsCorrectKey() {
assertThat(mController.getPreferenceKey()).isEqualTo(PREF_KEY);
}
@Test
public void getSliceHighlightMenuRes_returnsZero() {
assertThat(mController.getSliceHighlightMenuRes()).isEqualTo(0);
}
@Test
public void displayPreference_broadcastOn_Disabled() {
when(mBroadcast.isEnabled(any())).thenReturn(true);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
verify(mPreference).setEnabled(false);
verify(mPreference)
.setSummary(
eq(mContext.getString(
R.string
.audio_sharing_stream_compatibility_disabled_description)));
}
@Test
public void displayPreference_broadcastOff_Enabled() {
when(mBroadcast.isEnabled(any())).thenReturn(false);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
verify(mPreference).setEnabled(true);
verify(mPreference)
.setSummary(
eq(mContext.getString(
R.string.audio_sharing_stream_compatibility_description)));
}
@Test
public void isChecked_returnsTrue() {
when(mBroadcast.getImproveCompatibility()).thenReturn(true);
assertThat(mController.isChecked()).isTrue();
}
@Test
public void isChecked_returnsFalse() {
when(mBroadcast.getImproveCompatibility()).thenReturn(false);
assertThat(mController.isChecked()).isFalse();
mBroadcast = null;
assertThat(mController.isChecked()).isFalse();
}
@Test
public void setCheckedToNewValue_returnsTrue() {
when(mBroadcast.getImproveCompatibility()).thenReturn(true);
doNothing().when(mBroadcast).setImproveCompatibility(anyBoolean());
boolean setChecked = mController.setChecked(false);
verify(mBroadcast).setImproveCompatibility(false);
assertThat(setChecked).isTrue();
}
@Test
public void setCheckedToCurrentValue_returnsFalse() {
when(mBroadcast.getImproveCompatibility()).thenReturn(true);
boolean setChecked = mController.setChecked(true);
verify(mBroadcast, times(0)).setImproveCompatibility(anyBoolean());
assertThat(setChecked).isFalse();
}
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import android.app.settings.SettingsEnums;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class AudioSharingDashboardFragmentTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
private AudioSharingDashboardFragment mFragment;
@Before
public void setUp() {
mFragment = new AudioSharingDashboardFragment();
}
@Test
public void getPreferenceScreenResId_returnsCorrectXml() {
assertThat(mFragment.getPreferenceScreenResId())
.isEqualTo(R.xml.bluetooth_le_audio_sharing);
}
@Test
public void getLogTag_returnsCorrectTag() {
assertThat(mFragment.getLogTag()).isEqualTo("AudioSharingDashboardFrag");
}
@Test
public void getMetricsCategory_returnsCorrectCategory() {
assertThat(mFragment.getMetricsCategory()).isEqualTo(SettingsEnums.AUDIO_SHARING_SETTINGS);
}
@Test
public void getHelpResource_returnsCorrectResource() {
assertThat(mFragment.getHelpResource())
.isEqualTo(R.string.help_url_audio_sharing);
}
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import android.os.Parcel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class AudioSharingDeviceItemTest {
private static final String TEST_NAME = "test";
private static final int TEST_GROUP_ID = 1;
private static final boolean TEST_IS_ACTIVE = true;
@Test
public void createItem_new() {
AudioSharingDeviceItem item =
new AudioSharingDeviceItem(TEST_NAME, TEST_GROUP_ID, TEST_IS_ACTIVE);
assertThat(item.getName()).isEqualTo(TEST_NAME);
assertThat(item.getGroupId()).isEqualTo(TEST_GROUP_ID);
assertThat(item.isActive()).isEqualTo(TEST_IS_ACTIVE);
}
@Test
public void createItem_withParcel() {
AudioSharingDeviceItem item =
new AudioSharingDeviceItem(TEST_NAME, TEST_GROUP_ID, TEST_IS_ACTIVE);
Parcel parcel = Parcel.obtain();
item.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
AudioSharingDeviceItem newItem = new AudioSharingDeviceItem(parcel);
assertThat(newItem.getName()).isEqualTo(TEST_NAME);
assertThat(newItem.getGroupId()).isEqualTo(TEST_GROUP_ID);
assertThat(newItem.isActive()).isEqualTo(TEST_IS_ACTIVE);
}
@Test
public void describeContents_returnsZero() {
AudioSharingDeviceItem item =
new AudioSharingDeviceItem(TEST_NAME, TEST_GROUP_ID, TEST_IS_ACTIVE);
assertThat(item.describeContents()).isEqualTo(0);
}
@Test
public void creator_newArray() {
assertThat(AudioSharingDeviceItem.CREATOR.newArray(2)).hasLength(2);
}
}

View File

@@ -0,0 +1,487 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.android.settings.core.BasePreferenceController.AVAILABLE_UNSEARCHABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast.EXTRA_BLUETOOTH_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcastAssistant;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothStatusCodes;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.SettingsActivity;
import com.android.settings.bluetooth.Utils;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settings.testutils.shadow.ShadowFragment;
import com.android.settingslib.bluetooth.A2dpProfile;
import com.android.settingslib.bluetooth.BluetoothCallback;
import com.android.settingslib.bluetooth.BluetoothEventManager;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.HeadsetProfile;
import com.android.settingslib.bluetooth.LeAudioProfile;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.bluetooth.VolumeControlProfile;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import java.util.concurrent.Executor;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
ShadowFragment.class,
})
public class AudioSharingDevicePreferenceControllerTest {
private static final String KEY = "audio_sharing_device_list";
private static final String KEY_AUDIO_SHARING_SETTINGS =
"connected_device_audio_sharing_settings";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Mock private AudioSharingBluetoothDeviceUpdater mBluetoothDeviceUpdater;
@Mock private PreferenceManager mPreferenceManager;
@Mock private CachedBluetoothDevice mCachedDevice;
@Mock private BluetoothDevice mDevice;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private BluetoothEventManager mEventManager;
@Mock private LocalBluetoothProfileManager mProfileManager;
@Mock private CachedBluetoothDeviceManager mDeviceManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private VolumeControlProfile mVolumeControl;
@Mock private PreferenceScreen mScreen;
@Mock private AudioSharingDialogHandler mDialogHandler;
@Mock private DashboardFragment mFragment;
@Mock private FragmentActivity mActivity;
@Mock private LeAudioProfile mLeAudioProfile;
@Mock private A2dpProfile mA2dpProfile;
@Mock private HeadsetProfile mHeadsetProfile;
private Context mContext;
private AudioSharingDevicePreferenceController mController;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private PreferenceCategory mPreferenceGroup;
private Preference mAudioSharingPreference;
@Before
public void setUp() {
mContext = ApplicationProvider.getApplicationContext();
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBtManager = Utils.getLocalBtManager(mContext);
when(mLocalBtManager.getEventManager()).thenReturn(mEventManager);
when(mLocalBtManager.getProfileManager()).thenReturn(mProfileManager);
when(mLocalBtManager.getCachedDeviceManager()).thenReturn(mDeviceManager);
when(mProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
when(mProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
when(mProfileManager.getVolumeControlProfile()).thenReturn(mVolumeControl);
when(mBroadcast.isProfileReady()).thenReturn(true);
when(mAssistant.isProfileReady()).thenReturn(true);
when(mVolumeControl.isProfileReady()).thenReturn(true);
when(mDevice.getAnonymizedAddress()).thenReturn("");
doReturn(mDevice).when(mCachedDevice).getDevice();
when(mDeviceManager.findDevice(mDevice)).thenReturn(mCachedDevice);
when(mHeadsetProfile.getProfileId()).thenReturn(BluetoothProfile.HEADSET);
when(mA2dpProfile.getProfileId()).thenReturn(BluetoothProfile.A2DP);
when(mLeAudioProfile.getProfileId()).thenReturn(BluetoothProfile.LE_AUDIO);
when(mLeAudioProfile.isEnabled(mDevice)).thenReturn(true);
when(mScreen.getContext()).thenReturn(mContext);
mPreferenceGroup = spy(new PreferenceCategory(mContext));
doReturn(mPreferenceManager).when(mPreferenceGroup).getPreferenceManager();
mAudioSharingPreference = new Preference(mContext);
mPreferenceGroup.addPreference(mAudioSharingPreference);
when(mPreferenceGroup.findPreference(KEY_AUDIO_SHARING_SETTINGS))
.thenReturn(mAudioSharingPreference);
when(mScreen.findPreference(KEY)).thenReturn(mPreferenceGroup);
mController = new AudioSharingDevicePreferenceController(mContext);
mController.setBluetoothDeviceUpdater(mBluetoothDeviceUpdater);
mController.setDialogHandler(mDialogHandler);
doReturn(mActivity).when(mFragment).getActivity();
mController.setHostFragment(mFragment);
}
@Test
public void onStart_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mEventManager, times(0)).registerCallback(any(BluetoothCallback.class));
verify(mDialogHandler, times(0)).registerCallbacks(any(Executor.class));
verify(mAssistant, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mBluetoothDeviceUpdater, times(0)).registerCallback();
verify(mBluetoothDeviceUpdater, times(0)).refreshPreference();
}
@Test
public void onStart_flagOn_registerCallbacks() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mEventManager).registerCallback(any(BluetoothCallback.class));
verify(mDialogHandler).registerCallbacks(any(Executor.class));
verify(mAssistant)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mBluetoothDeviceUpdater).registerCallback();
verify(mBluetoothDeviceUpdater).refreshPreference();
}
@Test
public void onStop_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStop(mLifecycleOwner);
verify(mEventManager, times(0)).unregisterCallback(any(BluetoothCallback.class));
verify(mDialogHandler, times(0)).unregisterCallbacks();
verify(mAssistant, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mBluetoothDeviceUpdater, times(0)).unregisterCallback();
}
@Test
public void onStop_flagOn_unregisterCallbacks() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStop(mLifecycleOwner);
verify(mEventManager).unregisterCallback(any(BluetoothCallback.class));
verify(mDialogHandler).unregisterCallbacks();
verify(mAssistant)
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mBluetoothDeviceUpdater).unregisterCallback();
}
@Test
public void displayPreference_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.displayPreference(mScreen);
assertThat(mPreferenceGroup.isVisible()).isFalse();
assertThat(mAudioSharingPreference.isVisible()).isFalse();
verify(mBluetoothDeviceUpdater, times(0)).forceUpdate();
}
@Test
public void displayPreference_flagOn_updateDeviceList() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.displayPreference(mScreen);
assertThat(mPreferenceGroup.isVisible()).isFalse();
assertThat(mAudioSharingPreference.isVisible()).isFalse();
verify(mBluetoothDeviceUpdater).setPrefContext(mContext);
verify(mBluetoothDeviceUpdater).forceUpdate();
}
@Test
public void getPreferenceKey_returnsCorrectKey() {
assertThat(mController.getPreferenceKey()).isEqualTo(KEY);
}
@Test
public void getAvailabilityStatus_flagOff_returnUnSupported() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void getAvailabilityStatus_flagOn_returnSupported() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE_UNSEARCHABLE);
}
@Test
public void onDeviceAdded_firstDevice_updateVisibility() {
mController.displayPreference(mScreen);
Preference preference = new Preference(mContext);
mController.onDeviceAdded(preference);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreferenceGroup.isVisible()).isTrue();
assertThat(mAudioSharingPreference.isVisible()).isTrue();
assertThat(mPreferenceGroup.getPreferenceCount()).isEqualTo(2);
}
@Test
public void onDeviceRemoved_lastDevice_updateVisibility() {
Preference preference = new Preference(mContext);
mPreferenceGroup.addPreference(preference);
mController.displayPreference(mScreen);
mController.onDeviceRemoved(preference);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreferenceGroup.isVisible()).isFalse();
assertThat(mAudioSharingPreference.isVisible()).isFalse();
assertThat(mPreferenceGroup.getPreferenceCount()).isEqualTo(1);
}
@Test
public void onProfileConnectionStateChanged_notMediaDevice_doNothing() {
doReturn(ImmutableList.of()).when(mCachedDevice).getConnectableProfiles();
mController.onProfileConnectionStateChanged(
mCachedDevice, BluetoothAdapter.STATE_CONNECTED, BluetoothProfile.HID_DEVICE);
verifyNoInteractions(mDialogHandler);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceDisconnected_closeOpeningDialogsForIt() {
// Test when LEA device LE_AUDIO_BROADCAST_ASSISTANT disconnected.
when(mDevice.isConnected()).thenReturn(true);
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getConnectableProfiles();
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getProfiles();
mController.onProfileConnectionStateChanged(
mCachedDevice,
BluetoothAdapter.STATE_DISCONNECTED,
BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT);
verify(mDialogHandler).closeOpeningDialogsForLeaDevice(mCachedDevice);
}
@Test
public void onProfileConnectionStateChanged_assistantProfileConnecting_doNothing() {
// Test when LEA device LE_AUDIO_BROADCAST_ASSISTANT connecting
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getConnectableProfiles();
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getProfiles();
mController.onProfileConnectionStateChanged(
mCachedDevice,
BluetoothAdapter.STATE_CONNECTING,
BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT);
verifyNoInteractions(mDialogHandler);
}
@Test
public void onProfileConnectionStateChanged_otherProfileConnected_doNothing() {
// Test when LEA device other profile connected
when(mDevice.isConnected()).thenReturn(true);
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getConnectableProfiles();
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getProfiles();
mController.onProfileConnectionStateChanged(
mCachedDevice, BluetoothAdapter.STATE_CONNECTED, BluetoothProfile.A2DP);
verifyNoInteractions(mDialogHandler);
}
@Test
public void onProfileConnectionStateChanged_otherProfileConnecting_doNothing() {
// Test when LEA device other profile connecting
when(mDevice.isConnected()).thenReturn(true);
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getConnectableProfiles();
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getProfiles();
mController.onProfileConnectionStateChanged(
mCachedDevice, BluetoothAdapter.STATE_CONNECTING, BluetoothProfile.A2DP);
verifyNoInteractions(mDialogHandler);
}
@Test
public void onProfileConnectionStateChanged_assistantProfileConnected_handle() {
// Test when LEA device LE_AUDIO_BROADCAST_ASSISTANT connected
when(mDevice.isConnected()).thenReturn(true);
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getConnectableProfiles();
doReturn(ImmutableList.of(mLeAudioProfile)).when(mCachedDevice).getProfiles();
mController.onProfileConnectionStateChanged(
mCachedDevice,
BluetoothAdapter.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT);
verify(mDialogHandler).handleDeviceConnected(mCachedDevice, false);
}
@Test
public void
onProfileConnectionStateChanged_nonLeaDeviceDisconnected_closeOpeningDialogsForIt() {
// Test when non-LEA device totally disconnected
when(mLeAudioProfile.isEnabled(mDevice)).thenReturn(false);
doReturn(ImmutableList.of(mA2dpProfile)).when(mCachedDevice).getConnectableProfiles();
doReturn(ImmutableList.of(mLeAudioProfile, mA2dpProfile)).when(mCachedDevice).getProfiles();
when(mCachedDevice.isConnected()).thenReturn(false);
mController.onProfileConnectionStateChanged(
mCachedDevice, BluetoothAdapter.STATE_DISCONNECTED, BluetoothProfile.A2DP);
verify(mDialogHandler).closeOpeningDialogsForNonLeaDevice(mCachedDevice);
}
@Test
public void onProfileConnectionStateChanged_nonLeaNotFirstProfileConnected_doNothing() {
// Test when non-LEA device LE_AUDIO_BROADCAST_ASSISTANT connecting
when(mDevice.isConnected()).thenReturn(true);
when(mHeadsetProfile.getConnectionStatus(mDevice))
.thenReturn(BluetoothAdapter.STATE_CONNECTED);
doReturn(ImmutableList.of(mA2dpProfile, mHeadsetProfile))
.when(mCachedDevice)
.getConnectableProfiles();
doReturn(ImmutableList.of(mA2dpProfile, mHeadsetProfile)).when(mCachedDevice).getProfiles();
mController.onProfileConnectionStateChanged(
mCachedDevice, BluetoothAdapter.STATE_CONNECTED, BluetoothProfile.A2DP);
verifyNoInteractions(mDialogHandler);
}
@Test
public void onProfileConnectionStateChanged_nonLeaFirstProfileConnected_handle() {
// Test when non-LEA device LE_AUDIO_BROADCAST_ASSISTANT connecting
when(mDevice.isConnected()).thenReturn(true);
when(mHeadsetProfile.getConnectionStatus(mDevice))
.thenReturn(BluetoothAdapter.STATE_DISCONNECTED);
doReturn(ImmutableList.of(mA2dpProfile, mHeadsetProfile))
.when(mCachedDevice)
.getConnectableProfiles();
doReturn(ImmutableList.of(mA2dpProfile, mHeadsetProfile)).when(mCachedDevice).getProfiles();
mController.onProfileConnectionStateChanged(
mCachedDevice, BluetoothAdapter.STATE_CONNECTED, BluetoothProfile.A2DP);
verify(mDialogHandler).handleDeviceConnected(mCachedDevice, false);
}
@Test
public void handleDeviceClickFromIntent_noDevice_doNothing() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Intent intent = new Intent();
intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, new Bundle());
doReturn(intent).when(mActivity).getIntent();
mController.displayPreference(mScreen);
verify(mDeviceManager, times(0)).findDevice(any(BluetoothDevice.class));
verify(mDialogHandler, times(0))
.handleDeviceConnected(any(CachedBluetoothDevice.class), anyBoolean());
}
@Test
public void handleDeviceClickFromIntent_profileNotReady_doNothing() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isProfileReady()).thenReturn(false);
Bundle arg = new Bundle();
arg.putParcelable(EXTRA_BLUETOOTH_DEVICE, mDevice);
Intent intent = new Intent();
intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, arg);
doReturn(intent).when(mActivity).getIntent();
when(mDevice.isConnected()).thenReturn(false);
mController.displayPreference(mScreen);
verify(mDeviceManager, times(0)).findDevice(any(BluetoothDevice.class));
verify(mDialogHandler, times(0))
.handleDeviceConnected(any(CachedBluetoothDevice.class), anyBoolean());
}
@Test
public void handleDeviceClickFromIntent_intentHandled_handle() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Bundle arg = new Bundle();
arg.putParcelable(EXTRA_BLUETOOTH_DEVICE, mDevice);
Intent intent = new Intent();
intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, arg);
doReturn(intent).when(mActivity).getIntent();
when(mDevice.isConnected()).thenReturn(true);
when(mCachedDevice.isConnected()).thenReturn(true);
mController.setIntentHandled(true);
mController.displayPreference(mScreen);
verify(mDeviceManager, times(0)).findDevice(any(BluetoothDevice.class));
verify(mDialogHandler, times(0))
.handleDeviceConnected(any(CachedBluetoothDevice.class), anyBoolean());
}
@Test
public void handleDeviceClickFromIntent_disconnectedDevice_connect() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Bundle arg = new Bundle();
arg.putParcelable(EXTRA_BLUETOOTH_DEVICE, mDevice);
Intent intent = new Intent();
intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, arg);
doReturn(intent).when(mActivity).getIntent();
when(mDevice.isConnected()).thenReturn(false);
mController.displayPreference(mScreen);
verify(mCachedDevice).connect();
}
@Test
public void handleDeviceClickFromIntent_connectedDevice_handle() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Bundle arg = new Bundle();
arg.putParcelable(EXTRA_BLUETOOTH_DEVICE, mDevice);
Intent intent = new Intent();
intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, arg);
doReturn(intent).when(mActivity).getIntent();
when(mDevice.isConnected()).thenReturn(true);
when(mCachedDevice.isConnected()).thenReturn(true);
mController.displayPreference(mScreen);
verify(mDialogHandler).handleDeviceConnected(mCachedDevice, true);
}
@Test
public void handleDeviceClickFromIntent_onServiceConnected_handle() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Bundle arg = new Bundle();
arg.putParcelable(EXTRA_BLUETOOTH_DEVICE, mDevice);
Intent intent = new Intent();
intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, arg);
doReturn(intent).when(mActivity).getIntent();
when(mDevice.isConnected()).thenReturn(true);
when(mCachedDevice.isConnected()).thenReturn(true);
mController.onServiceConnected();
verify(mDialogHandler).handleDeviceConnected(mCachedDevice, true);
}
}

View File

@@ -0,0 +1,299 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.media.AudioManager;
import android.os.Looper;
import android.provider.Settings;
import android.widget.SeekBar;
import androidx.preference.Preference;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.bluetooth.Utils;
import com.android.settings.connecteddevice.DevicePreferenceCallback;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.bluetooth.VolumeControlProfile;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowBluetoothUtils.class})
public class AudioSharingDeviceVolumeControlUpdaterTest {
private static final String TEST_DEVICE_NAME = "test";
private static final String TAG = "AudioSharingDeviceVolumeControlUpdater";
private static final String PREF_KEY = "audio_sharing_volume_control";
private static final String TEST_SETTINGS_KEY =
"bluetooth_le_broadcast_fallback_active_group_id";
private static final int TEST_DEVICE_GROUP_ID = 1;
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock private DevicePreferenceCallback mDevicePreferenceCallback;
@Mock private CachedBluetoothDevice mCachedBluetoothDevice;
@Mock private BluetoothDevice mBluetoothDevice;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private CachedBluetoothDeviceManager mCachedDeviceManager;
@Mock private LocalBluetoothProfileManager mLocalBtProfileManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private VolumeControlProfile mVolumeControl;
@Mock private BluetoothLeBroadcastReceiveState mState;
@Mock private AudioManager mAudioManager;
private Context mContext;
private AudioSharingDeviceVolumeControlUpdater mDeviceUpdater;
private Collection<CachedBluetoothDevice> mCachedDevices;
@Before
public void setUp() {
mContext = spy(ApplicationProvider.getApplicationContext());
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBtManager = Utils.getLocalBtManager(mContext);
when(mLocalBtManager.getCachedDeviceManager()).thenReturn(mCachedDeviceManager);
when(mLocalBtManager.getProfileManager()).thenReturn(mLocalBtProfileManager);
when(mLocalBtProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
when(mLocalBtProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
when(mLocalBtProfileManager.getVolumeControlProfile()).thenReturn(mVolumeControl);
List<Long> bisSyncState = new ArrayList<>();
bisSyncState.add(1L);
when(mState.getBisSyncState()).thenReturn(bisSyncState);
doReturn(TEST_DEVICE_NAME).when(mCachedBluetoothDevice).getName();
doReturn(mBluetoothDevice).when(mCachedBluetoothDevice).getDevice();
doReturn(ImmutableSet.of()).when(mCachedBluetoothDevice).getMemberDevice();
doReturn(TEST_DEVICE_GROUP_ID).when(mCachedBluetoothDevice).getGroupId();
mCachedDevices = new ArrayList<>();
mCachedDevices.add(mCachedBluetoothDevice);
when(mCachedDeviceManager.getCachedDevicesCopy()).thenReturn(mCachedDevices);
doNothing().when(mDevicePreferenceCallback).onDeviceAdded(any(Preference.class));
doNothing().when(mDevicePreferenceCallback).onDeviceRemoved(any(Preference.class));
when(mContext.getSystemService(AudioManager.class)).thenReturn(mAudioManager);
mDeviceUpdater =
spy(
new AudioSharingDeviceVolumeControlUpdater(
mContext, mDevicePreferenceCallback, /* metricsCategory= */ 0));
mDeviceUpdater.setPrefContext(mContext);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceConnected_noSharing_removesPref() {
setupPreferenceMapWithDevice();
when(mBroadcast.isEnabled(null)).thenReturn(false);
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof AudioSharingDeviceVolumePreference).isTrue();
assertThat(((AudioSharingDeviceVolumePreference) captor.getValue()).getCachedDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceConnected_noSource_removesPref() {
setupPreferenceMapWithDevice();
when(mAssistant.getAllSources(mBluetoothDevice)).thenReturn(ImmutableList.of());
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof AudioSharingDeviceVolumePreference).isTrue();
assertThat(((AudioSharingDeviceVolumePreference) captor.getValue()).getCachedDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_deviceIsNotInList_removesPref() {
setupPreferenceMapWithDevice();
mCachedDevices.clear();
when(mCachedDeviceManager.getCachedDevicesCopy()).thenReturn(mCachedDevices);
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof AudioSharingDeviceVolumePreference).isTrue();
assertThat(((AudioSharingDeviceVolumePreference) captor.getValue()).getCachedDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceDisconnected_removesPref() {
setupPreferenceMapWithDevice();
when(mDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class))).thenReturn(false);
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_DISCONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof AudioSharingDeviceVolumePreference).isTrue();
assertThat(((AudioSharingDeviceVolumePreference) captor.getValue()).getCachedDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceDisconnecting_removesPref() {
setupPreferenceMapWithDevice();
when(mCachedBluetoothDevice.isConnectedLeAudioDevice()).thenReturn(false);
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
verify(mDevicePreferenceCallback).onDeviceRemoved(captor.capture());
assertThat(captor.getValue() instanceof AudioSharingDeviceVolumePreference).isTrue();
assertThat(((AudioSharingDeviceVolumePreference) captor.getValue()).getCachedDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void onProfileConnectionStateChanged_leaDeviceConnected_hasSource_addsPreference() {
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
setupPreferenceMapWithDevice();
verify(mDevicePreferenceCallback).onDeviceAdded(captor.capture());
assertThat(captor.getValue() instanceof AudioSharingDeviceVolumePreference).isTrue();
assertThat(((AudioSharingDeviceVolumePreference) captor.getValue()).getCachedDevice())
.isEqualTo(mCachedBluetoothDevice);
}
@Test
public void addPreference_notFallbackDevice_setDeviceVolume() {
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
setupPreferenceMapWithDevice();
verify(mDevicePreferenceCallback).onDeviceAdded(captor.capture());
assertThat(captor.getValue() instanceof AudioSharingDeviceVolumePreference).isTrue();
AudioSharingDeviceVolumePreference preference =
(AudioSharingDeviceVolumePreference) captor.getValue();
SeekBar seekBar = mock(SeekBar.class);
when(seekBar.getProgress()).thenReturn(255);
preference.onStopTrackingTouch(seekBar);
verify(mVolumeControl).setDeviceVolume(mBluetoothDevice, 255, true);
verifyNoInteractions(mAudioManager);
}
@Test
public void addPreference_fallbackDevice_setStreamVolume() {
ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
setupPreferenceMapWithDevice();
verify(mDevicePreferenceCallback).onDeviceAdded(captor.capture());
assertThat(captor.getValue() instanceof AudioSharingDeviceVolumePreference).isTrue();
AudioSharingDeviceVolumePreference preference =
(AudioSharingDeviceVolumePreference) captor.getValue();
Settings.Secure.putInt(
mContext.getContentResolver(), TEST_SETTINGS_KEY, TEST_DEVICE_GROUP_ID);
when(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)).thenReturn(10);
when(mAudioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)).thenReturn(0);
SeekBar seekBar = mock(SeekBar.class);
when(seekBar.getProgress()).thenReturn(255);
preference.onStopTrackingTouch(seekBar);
verifyNoInteractions(mVolumeControl);
verify(mAudioManager).setStreamVolume(AudioManager.STREAM_MUSIC, 10, 0);
}
@Test
public void getLogTag_returnsCorrectTag() {
assertThat(mDeviceUpdater.getLogTag()).isEqualTo(TAG);
}
@Test
public void getPreferenceKey_returnsCorrectKey() {
assertThat(mDeviceUpdater.getPreferenceKey()).isEqualTo(PREF_KEY);
}
private void setupPreferenceMapWithDevice() {
// Add device to preferenceMap
when(mBroadcast.isEnabled(null)).thenReturn(true);
when(mAssistant.getAllSources(mBluetoothDevice)).thenReturn(ImmutableList.of(mState));
when(mDeviceUpdater.isDeviceConnected(any(CachedBluetoothDevice.class))).thenReturn(true);
when(mCachedBluetoothDevice.isConnectedLeAudioDevice()).thenReturn(true);
mDeviceUpdater.onProfileConnectionStateChanged(
mCachedBluetoothDevice,
BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.LE_AUDIO);
shadowOf(Looper.getMainLooper()).idle();
}
}

View File

@@ -0,0 +1,414 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.android.settings.connecteddevice.audiosharing.AudioSharingUtils.SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcastAssistant;
import android.bluetooth.BluetoothStatusCodes;
import android.bluetooth.BluetoothVolumeControl;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.Settings;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.bluetooth.Utils;
import com.android.settings.connecteddevice.DevicePreferenceCallback;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settings.testutils.shadow.ShadowThreadUtils;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.bluetooth.VolumeControlProfile;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import java.util.concurrent.Executor;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
ShadowThreadUtils.class,
})
public class AudioSharingDeviceVolumeGroupControllerTest {
private static final String TEST_DEVICE_NAME1 = "test1";
private static final String TEST_DEVICE_NAME2 = "test2";
private static final int TEST_DEVICE_GROUP_ID1 = 1;
private static final int TEST_DEVICE_GROUP_ID2 = 2;
private static final int TEST_VOLUME_VALUE = 10;
private static final int TEST_INVALID_VOLUME_VALUE = -1;
private static final int TEST_MAX_VOLUME_VALUE = 100;
private static final int TEST_MIN_VOLUME_VALUE = 0;
private static final String PREF_KEY = "audio_sharing_device_volume_group";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Mock private DevicePreferenceCallback mDevicePreferenceCallback;
@Mock private CachedBluetoothDevice mCachedDevice1;
@Mock private CachedBluetoothDevice mCachedDevice2;
@Mock private BluetoothDevice mDevice1;
@Mock private BluetoothDevice mDevice2;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private CachedBluetoothDeviceManager mCachedDeviceManager;
@Mock private LocalBluetoothProfileManager mProfileManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private AudioSharingDeviceVolumeControlUpdater mDeviceUpdater;
@Mock private VolumeControlProfile mVolumeControl;
@Mock private PreferenceScreen mScreen;
@Mock private AudioSharingDeviceVolumePreference mPreference1;
@Mock private AudioSharingDeviceVolumePreference mPreference2;
@Mock private AudioManager mAudioManager;
@Mock private PreferenceManager mPreferenceManager;
@Mock private ContentResolver mContentResolver;
@Spy private ContentObserver mContentObserver;
private Context mContext;
private AudioSharingDeviceVolumeGroupController mController;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private PreferenceCategory mPreferenceGroup;
@Before
public void setUp() {
mContext = spy(ApplicationProvider.getApplicationContext());
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBtManager = Utils.getLocalBtManager(mContext);
when(mLocalBtManager.getCachedDeviceManager()).thenReturn(mCachedDeviceManager);
when(mLocalBtManager.getProfileManager()).thenReturn(mProfileManager);
when(mProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
when(mProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
when(mProfileManager.getVolumeControlProfile()).thenReturn(mVolumeControl);
when(mBroadcast.isProfileReady()).thenReturn(true);
when(mAssistant.isProfileReady()).thenReturn(true);
when(mVolumeControl.isProfileReady()).thenReturn(true);
when(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC))
.thenReturn(TEST_MAX_VOLUME_VALUE);
when(mAudioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC))
.thenReturn(TEST_MIN_VOLUME_VALUE);
when(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC))
.thenReturn(TEST_VOLUME_VALUE);
when(mContext.getSystemService(AudioManager.class)).thenReturn(mAudioManager);
when(mContext.getContentResolver()).thenReturn(mContentResolver);
doReturn(TEST_DEVICE_NAME1).when(mCachedDevice1).getName();
doReturn(TEST_DEVICE_GROUP_ID1).when(mCachedDevice1).getGroupId();
doReturn(mDevice1).when(mCachedDevice1).getDevice();
doReturn(ImmutableSet.of()).when(mCachedDevice1).getMemberDevice();
when(mPreference1.getCachedDevice()).thenReturn(mCachedDevice1);
doReturn(TEST_DEVICE_NAME2).when(mCachedDevice2).getName();
doReturn(TEST_DEVICE_GROUP_ID2).when(mCachedDevice2).getGroupId();
doReturn(mDevice2).when(mCachedDevice2).getDevice();
doReturn(ImmutableSet.of()).when(mCachedDevice2).getMemberDevice();
when(mPreference2.getCachedDevice()).thenReturn(mCachedDevice2);
doNothing().when(mDevicePreferenceCallback).onDeviceAdded(any(Preference.class));
doNothing().when(mDevicePreferenceCallback).onDeviceRemoved(any(Preference.class));
when(mScreen.getContext()).thenReturn(mContext);
mPreferenceGroup = spy(new PreferenceCategory(mContext));
doReturn(mPreferenceManager).when(mPreferenceGroup).getPreferenceManager();
when(mScreen.findPreference(PREF_KEY)).thenReturn(mPreferenceGroup);
mController = new AudioSharingDeviceVolumeGroupController(mContext);
mController.setDeviceUpdater(mDeviceUpdater);
mContentObserver = mController.getSettingsObserver();
}
@Test
public void onStart_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mAssistant, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDeviceUpdater, times(0)).registerCallback();
verify(mVolumeControl, times(0))
.registerCallback(any(Executor.class), any(BluetoothVolumeControl.Callback.class));
verify(mContentResolver, times(0))
.registerContentObserver(
Settings.Secure.getUriFor(SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID),
false,
mContentObserver);
}
@Test
public void onStart_flagOn_registerCallbacks() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mAssistant)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDeviceUpdater).registerCallback();
verify(mVolumeControl)
.registerCallback(any(Executor.class), any(BluetoothVolumeControl.Callback.class));
verify(mContentResolver)
.registerContentObserver(
Settings.Secure.getUriFor(SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID),
false,
mContentObserver);
}
@Test
public void onStop_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStop(mLifecycleOwner);
verify(mAssistant, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDeviceUpdater, times(0)).unregisterCallback();
verify(mVolumeControl, times(0))
.unregisterCallback(any(BluetoothVolumeControl.Callback.class));
verify(mContentResolver, times(0)).unregisterContentObserver(mContentObserver);
}
@Test
public void onStop_flagOn_callbacksNotRegistered_doNothing() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(false);
mController.onStop(mLifecycleOwner);
verify(mAssistant, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDeviceUpdater, times(0)).unregisterCallback();
verify(mVolumeControl, times(0))
.unregisterCallback(any(BluetoothVolumeControl.Callback.class));
verify(mContentResolver, times(0)).unregisterContentObserver(mContentObserver);
}
@Test
public void onStop_flagOn_callbacksRegistered_unregisterCallbacks() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mController.onStop(mLifecycleOwner);
verify(mAssistant)
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mDeviceUpdater).unregisterCallback();
verify(mVolumeControl).unregisterCallback(any(BluetoothVolumeControl.Callback.class));
verify(mContentResolver).unregisterContentObserver(mContentObserver);
}
@Test
public void displayPreference_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.displayPreference(mScreen);
assertThat(mPreferenceGroup.isVisible()).isFalse();
verify(mDeviceUpdater, times(0)).forceUpdate();
}
@Test
public void displayPreference_flagOn_updateDeviceList() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.displayPreference(mScreen);
assertThat(mPreferenceGroup.isVisible()).isFalse();
verify(mDeviceUpdater).forceUpdate();
}
@Test
public void getPreferenceKey_returnsCorrectKey() {
assertThat(mController.getPreferenceKey()).isEqualTo(PREF_KEY);
}
@Test
public void onDeviceAdded_firstDevice_updateVisibility() {
when(mPreference1.getProgress()).thenReturn(TEST_VOLUME_VALUE);
mController.setPreferenceGroup(mPreferenceGroup);
mController.onDeviceAdded(mPreference1);
verify(mPreferenceGroup).setVisible(true);
assertThat(mPreferenceGroup.isVisible()).isTrue();
}
@Test
public void onDeviceAdded_rankFallbackDeviceOnTop() {
Settings.Secure.putInt(
mContentResolver, SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID, TEST_DEVICE_GROUP_ID2);
when(mPreference1.getProgress()).thenReturn(TEST_VOLUME_VALUE);
when(mPreference2.getProgress()).thenReturn(TEST_VOLUME_VALUE);
mController.setPreferenceGroup(mPreferenceGroup);
mController.onDeviceAdded(mPreference1);
mController.onDeviceAdded(mPreference2);
shadowOf(Looper.getMainLooper()).idle();
verify(mPreference1).setOrder(1);
verify(mPreference2).setOrder(0);
}
@Test
public void onDeviceAdded_setVolumeFromVolumeControlService() {
when(mPreference1.getProgress()).thenReturn(TEST_INVALID_VOLUME_VALUE);
mController.setVolumeMap(ImmutableMap.of(TEST_DEVICE_GROUP_ID1, TEST_VOLUME_VALUE));
mController.setPreferenceGroup(mPreferenceGroup);
mController.onDeviceAdded(mPreference1);
shadowOf(Looper.getMainLooper()).idle();
verify(mPreference1).setProgress(eq(TEST_VOLUME_VALUE));
}
@Test
public void onDeviceAdded_setVolumeFromAudioManager() {
when(mPreference1.getProgress()).thenReturn(TEST_INVALID_VOLUME_VALUE);
mController.setPreferenceGroup(mPreferenceGroup);
mController.onDeviceAdded(mPreference1);
shadowOf(Looper.getMainLooper()).idle();
verify(mPreference1).setProgress(eq(26));
}
@Test
public void onDeviceRemoved_notLastDevice_isVisible() {
mPreferenceGroup.addPreference(mPreference2);
mPreferenceGroup.addPreference(mPreference1);
mController.setPreferenceGroup(mPreferenceGroup);
mController.onDeviceRemoved(mPreference1);
verify(mPreferenceGroup, times(0)).setVisible(false);
assertThat(mPreferenceGroup.isVisible()).isTrue();
}
@Test
public void onDeviceRemoved_lastDevice_updateVisibility() {
mPreferenceGroup.addPreference(mPreference1);
mController.setPreferenceGroup(mPreferenceGroup);
mController.onDeviceRemoved(mPreference1);
verify(mPreferenceGroup).setVisible(false);
assertThat(mPreferenceGroup.isVisible()).isFalse();
}
@Test
public void updateVisibility_emptyPreferenceGroup_doNothing() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
verify(mPreferenceGroup, times(0)).setVisible(anyBoolean());
}
@Test
public void updateVisibility_flagOff_setVisibleToFalse() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mPreferenceGroup.addPreference(mPreference1);
when(mBroadcast.isEnabled(null)).thenReturn(true);
mController.setPreferenceGroup(mPreferenceGroup);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreferenceGroup.getPreferenceCount() > 0).isTrue();
verify(mPreferenceGroup).setVisible(false);
assertThat(mPreferenceGroup.isVisible()).isFalse();
}
@Test
public void updateVisibility_notEmptyPreferenceGroup_noSharing_setVisibleToFalse() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mPreferenceGroup.addPreference(mPreference1);
when(mBroadcast.isEnabled(null)).thenReturn(false);
mController.setPreferenceGroup(mPreferenceGroup);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreferenceGroup.getPreferenceCount() > 0).isTrue();
verify(mPreferenceGroup).setVisible(false);
assertThat(mPreferenceGroup.isVisible()).isFalse();
}
@Test
public void updateVisibility_notEmptyPreferenceGroup_isSharing_setVisibleToTrue() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mPreferenceGroup.addPreference(mPreference1);
when(mBroadcast.isEnabled(null)).thenReturn(true);
mController.setPreferenceGroup(mPreferenceGroup);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreferenceGroup.getPreferenceCount() > 0).isTrue();
verify(mPreferenceGroup).setVisible(true);
assertThat(mPreferenceGroup.isVisible()).isTrue();
}
@Test
public void settingsObserverOnChange_updatePreferenceOrder() {
Settings.Secure.putInt(
mContentResolver, SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID, TEST_DEVICE_GROUP_ID2);
when(mPreference1.getProgress()).thenReturn(TEST_VOLUME_VALUE);
when(mPreference2.getProgress()).thenReturn(TEST_VOLUME_VALUE);
mController.setPreferenceGroup(mPreferenceGroup);
mController.onDeviceAdded(mPreference1);
mController.onDeviceAdded(mPreference2);
shadowOf(Looper.getMainLooper()).idle();
Settings.Secure.putInt(
mContentResolver, SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID, TEST_DEVICE_GROUP_ID1);
mContentObserver.onChange(true);
shadowOf(Looper.getMainLooper()).idle();
verify(mPreference1).setOrder(0);
verify(mPreference2).setOrder(1);
}
}

View File

@@ -22,10 +22,7 @@ import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.connecteddevice.AvailableMediaDeviceGroupController;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import org.junit.Before;
import org.junit.Rule;
@@ -37,40 +34,28 @@ import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class AudioSharingFeatureProviderImplTest {
public class AudioSharingDeviceVolumePreferenceTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock private CachedBluetoothDevice mCachedDevice;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private DashboardFragment mFragment;
private Context mContext;
private AudioSharingFeatureProviderImpl mFeatureProvider;
private AudioSharingDeviceVolumePreference mPreference;
@Before
public void setUp() {
public void setup() {
mContext = ApplicationProvider.getApplicationContext();
mFeatureProvider = new AudioSharingFeatureProviderImpl();
mPreference = new AudioSharingDeviceVolumePreference(mContext, mCachedDevice);
}
@Test
public void createAudioSharingDevicePreferenceController_returnsNull() {
assertThat(
mFeatureProvider.createAudioSharingDevicePreferenceController(
mContext, mFragment, /* lifecycle= */ null))
.isNull();
public void getCachedDevice_returnsDevice() {
assertThat(mPreference.getCachedDevice()).isEqualTo(mCachedDevice);
}
@Test
public void createAvailableMediaDeviceGroupController_returnsNull() {
assertThat(
mFeatureProvider.createAvailableMediaDeviceGroupController(
mContext, /* fragment= */ null, /* lifecycle= */ null))
.isInstanceOf(AvailableMediaDeviceGroupController.class);
}
@Test
public void isAudioSharingFilterMatched_returnsFalse() {
assertThat(mFeatureProvider.isAudioSharingFilterMatched(mCachedDevice, mLocalBtManager))
.isFalse();
public void initialize_setupMaxMin() {
mPreference.initialize();
assertThat(mPreference.getMax()).isEqualTo(AudioSharingDeviceVolumePreference.MAX_VOLUME);
assertThat(mPreference.getMin()).isEqualTo(AudioSharingDeviceVolumePreference.MIN_VOLUME);
}
}

View File

@@ -0,0 +1,233 @@
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.shadows.ShadowLooper.shadowMainLooper;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothStatusCodes;
import android.platform.test.flag.junit.SetFlagsRule;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowAlertDialogCompat;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.androidx.fragment.FragmentController;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowAlertDialogCompat.class,
ShadowBluetoothAdapter.class,
})
public class AudioSharingDialogFragmentTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private static final String TEST_DEVICE_NAME1 = "test1";
private static final String TEST_DEVICE_NAME2 = "test2";
private static final String TEST_DEVICE_NAME3 = "test3";
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM1 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME1, /* groupId= */ 1, /* isActive= */ false);
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM2 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME2, /* groupId= */ 2, /* isActive= */ false);
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM3 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME3, /* groupId= */ 3, /* isActive= */ false);
private Fragment mParent;
private AudioSharingDialogFragment mFragment;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
@Before
public void setUp() {
ShadowAlertDialogCompat.reset();
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mFragment = new AudioSharingDialogFragment();
mParent = new Fragment();
FragmentController.setupFragment(
mParent, FragmentActivity.class, /* containerViewId= */ 0, /* bundle= */ null);
}
@Test
public void onCreateDialog_flagOff_dialogNotExist() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, new ArrayList<>(), (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNull();
}
@Test
public void onCreateDialog_flagOn_noConnectedDevice() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, new ArrayList<>(), (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
TextView description = dialog.findViewById(R.id.description_text);
ImageView image = dialog.findViewById(R.id.description_image);
Button shareBtn = dialog.findViewById(R.id.positive_btn);
Button cancelBtn = dialog.findViewById(R.id.negative_btn);
assertThat(dialog.isShowing()).isTrue();
assertThat(description.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(description.getText().toString())
.isEqualTo(mParent.getString(R.string.audio_sharing_dialog_connect_device_content));
assertThat(image.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(shareBtn.getVisibility()).isEqualTo(View.GONE);
assertThat(cancelBtn.getVisibility()).isEqualTo(View.GONE);
}
@Test
public void onCreateDialog_noConnectedDevice_dialogDismiss() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, new ArrayList<>(), (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(android.R.id.button2).performClick();
shadowMainLooper().idle();
assertThat(dialog.isShowing()).isFalse();
}
@Test
public void onCreateDialog_flagOn_singleConnectedDevice() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArrayList<AudioSharingDeviceItem> list = new ArrayList<>();
list.add(TEST_DEVICE_ITEM1);
mFragment.show(mParent, list, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
TextView title = dialog.findViewById(R.id.title_text);
TextView description = dialog.findViewById(R.id.description_text);
ImageView image = dialog.findViewById(R.id.description_image);
Button shareBtn = dialog.findViewById(R.id.positive_btn);
Button cancelBtn = dialog.findViewById(R.id.negative_btn);
assertThat(dialog.isShowing()).isTrue();
assertThat(title.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_share_with_dialog_title, TEST_DEVICE_NAME1));
assertThat(description.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(description.getText().toString())
.isEqualTo(mParent.getString(R.string.audio_sharing_dialog_share_content));
assertThat(image.getVisibility()).isEqualTo(View.GONE);
assertThat(shareBtn.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(cancelBtn.getVisibility()).isEqualTo(View.VISIBLE);
}
@Test
public void onCreateDialog_singleConnectedDevice_dialogDismiss() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArrayList<AudioSharingDeviceItem> list = new ArrayList<>();
list.add(TEST_DEVICE_ITEM1);
mFragment.show(mParent, list, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(R.id.negative_btn).performClick();
assertThat(dialog.isShowing()).isFalse();
}
@Test
public void onCreateDialog_singleConnectedDevice_shareClicked() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArrayList<AudioSharingDeviceItem> list = new ArrayList<>();
list.add(TEST_DEVICE_ITEM1);
AtomicBoolean isShareBtnClicked = new AtomicBoolean(false);
mFragment.show(mParent, list, (item) -> isShareBtnClicked.set(true));
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(R.id.positive_btn).performClick();
assertThat(dialog.isShowing()).isFalse();
assertThat(isShareBtnClicked.get()).isTrue();
}
@Test
public void onCreateDialog_flagOn_multipleConnectedDevice() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArrayList<AudioSharingDeviceItem> list = new ArrayList<>();
list.add(TEST_DEVICE_ITEM1);
list.add(TEST_DEVICE_ITEM2);
list.add(TEST_DEVICE_ITEM3);
mFragment.show(mParent, list, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
TextView description = dialog.findViewById(R.id.description_text);
ImageView image = dialog.findViewById(R.id.description_image);
Button shareBtn = dialog.findViewById(R.id.positive_btn);
Button cancelBtn = dialog.findViewById(R.id.negative_btn);
RecyclerView recyclerView = dialog.findViewById(R.id.device_btn_list);
assertThat(dialog.isShowing()).isTrue();
assertThat(description.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(description.getText().toString())
.isEqualTo(mParent.getString(R.string.audio_sharing_dialog_share_more_content));
assertThat(image.getVisibility()).isEqualTo(View.GONE);
assertThat(shareBtn.getVisibility()).isEqualTo(View.GONE);
assertThat(cancelBtn.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(recyclerView.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(recyclerView.getAdapter().getItemCount()).isEqualTo(3);
}
@Test
public void onCreateDialog_multipleConnectedDevice_dialogDismiss() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArrayList<AudioSharingDeviceItem> list = new ArrayList<>();
list.add(TEST_DEVICE_ITEM1);
list.add(TEST_DEVICE_ITEM2);
list.add(TEST_DEVICE_ITEM3);
mFragment.show(mParent, list, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(R.id.negative_btn).performClick();
assertThat(dialog.isShowing()).isFalse();
}
}

View File

@@ -0,0 +1,385 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothStatusCodes;
import android.content.Context;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.bluetooth.Utils;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LeAudioProfile;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.flags.Flags;
import com.google.common.collect.ImmutableList;
import com.google.common.truth.Correspondence;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.androidx.fragment.FragmentController;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
})
public class AudioSharingDialogHandlerTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private static final String TEST_DEVICE_NAME1 = "test1";
private static final String TEST_DEVICE_NAME2 = "test2";
private static final String TEST_DEVICE_NAME3 = "test3";
private static final String TEST_DEVICE_NAME4 = "test4";
private static final String TEST_DEVICE_ADDRESS = "xx:xx:xx:xx";
private static final Correspondence<Fragment, String> TAG_EQUALS =
Correspondence.from(
(Fragment fragment, String tag) ->
fragment instanceof DialogFragment
&& ((DialogFragment) fragment).getTag().equals(tag),
"is equal to");
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private LocalBluetoothProfileManager mLocalBtProfileManager;
@Mock private CachedBluetoothDeviceManager mCacheManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private CachedBluetoothDevice mCachedDevice1;
@Mock private CachedBluetoothDevice mCachedDevice2;
@Mock private CachedBluetoothDevice mCachedDevice3;
@Mock private CachedBluetoothDevice mCachedDevice4;
@Mock private BluetoothDevice mDevice1;
@Mock private BluetoothDevice mDevice2;
@Mock private BluetoothDevice mDevice3;
@Mock private BluetoothDevice mDevice4;
@Mock private LeAudioProfile mLeAudioProfile;
private Fragment mParentFragment;
@Mock private BluetoothLeBroadcastReceiveState mState;
private Context mContext;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private AudioSharingDialogHandler mHandler;
@Before
public void setup() {
mContext = ApplicationProvider.getApplicationContext();
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBtManager = Utils.getLocalBtManager(mContext);
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mLocalBtManager.getProfileManager()).thenReturn(mLocalBtProfileManager);
when(mLocalBtProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
when(mLocalBtProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
List<Long> bisSyncState = new ArrayList<>();
bisSyncState.add(1L);
when(mState.getBisSyncState()).thenReturn(bisSyncState);
when(mLeAudioProfile.isEnabled(any())).thenReturn(true);
when(mCachedDevice1.getName()).thenReturn(TEST_DEVICE_NAME1);
when(mCachedDevice1.getDevice()).thenReturn(mDevice1);
when(mCachedDevice1.getProfiles()).thenReturn(List.of(mLeAudioProfile));
when(mCachedDevice1.getGroupId()).thenReturn(1);
when(mCachedDevice2.getName()).thenReturn(TEST_DEVICE_NAME2);
when(mCachedDevice2.getAddress()).thenReturn(TEST_DEVICE_ADDRESS);
when(mCachedDevice2.getDevice()).thenReturn(mDevice2);
when(mCachedDevice2.getProfiles()).thenReturn(List.of());
when(mCachedDevice2.getGroupId()).thenReturn(2);
when(mCachedDevice3.getName()).thenReturn(TEST_DEVICE_NAME3);
when(mCachedDevice3.getDevice()).thenReturn(mDevice3);
when(mCachedDevice3.getProfiles()).thenReturn(List.of(mLeAudioProfile));
when(mCachedDevice3.getGroupId()).thenReturn(3);
when(mCachedDevice4.getName()).thenReturn(TEST_DEVICE_NAME4);
when(mCachedDevice4.getDevice()).thenReturn(mDevice4);
when(mCachedDevice4.getProfiles()).thenReturn(List.of(mLeAudioProfile));
when(mCachedDevice4.getGroupId()).thenReturn(4);
when(mLocalBtManager.getCachedDeviceManager()).thenReturn(mCacheManager);
when(mCacheManager.findDevice(mDevice1)).thenReturn(mCachedDevice1);
when(mCacheManager.findDevice(mDevice2)).thenReturn(mCachedDevice2);
when(mCacheManager.findDevice(mDevice3)).thenReturn(mCachedDevice3);
when(mCacheManager.findDevice(mDevice4)).thenReturn(mCachedDevice4);
mParentFragment = new Fragment();
FragmentController.setupFragment(
mParentFragment,
FragmentActivity.class,
0 /* containerViewId */,
null /* bundle */);
mHandler = new AudioSharingDialogHandler(mContext, mParentFragment);
}
@Test
public void handleUserTriggeredNonLeaDeviceConnected_noSharing_setActive() {
setUpBroadcast(false);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice2);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mHandler.handleDeviceConnected(mCachedDevice2, /* userTriggered= */ true);
shadowOf(Looper.getMainLooper()).idle();
verify(mCachedDevice2).setActive();
}
@Test
public void handleUserTriggeredNonLeaDeviceConnected_sharing_showStopDialog() {
setUpBroadcast(true);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice2);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mState));
mHandler.handleDeviceConnected(mCachedDevice2, /* userTriggered= */ true);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingStopDialogFragment.tag());
}
@Test
public void handleUserTriggeredLeaDeviceConnected_noSharingNoTwoLeaDevices_setActive() {
setUpBroadcast(false);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ true);
shadowOf(Looper.getMainLooper()).idle();
verify(mCachedDevice1).setActive();
}
@Test
public void handleUserTriggeredLeaDeviceConnected_noSharingTwoLeaDevices_showJoinDialog() {
setUpBroadcast(false);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1, mDevice3);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ true);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingJoinDialogFragment.tag());
}
@Test
public void handleUserTriggeredLeaDeviceConnected_sharing_showJoinDialog() {
setUpBroadcast(true);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1, mDevice3);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(mDevice1)).thenReturn(ImmutableList.of());
when(mAssistant.getAllSources(mDevice3)).thenReturn(ImmutableList.of(mState));
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ true);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingJoinDialogFragment.tag());
}
@Test
public void
handleUserTriggeredLeaDeviceConnected_sharingWithTwoLeaDevices_showDisconnectDialog() {
setUpBroadcast(true);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1, mDevice3, mDevice4);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(mDevice1)).thenReturn(ImmutableList.of());
when(mAssistant.getAllSources(mDevice3)).thenReturn(ImmutableList.of(mState));
when(mAssistant.getAllSources(mDevice4)).thenReturn(ImmutableList.of(mState));
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ true);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingDisconnectDialogFragment.tag());
}
@Test
public void handleNonLeaDeviceConnected_noSharing_doNothing() {
setUpBroadcast(false);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice2);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mHandler.handleDeviceConnected(mCachedDevice2, /* userTriggered= */ false);
shadowOf(Looper.getMainLooper()).idle();
verify(mCachedDevice2, times(0)).setActive();
}
@Test
public void handleNonLeaDeviceConnected_sharing_showStopDialog() {
setUpBroadcast(true);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice2);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mState));
mHandler.handleDeviceConnected(mCachedDevice2, /* userTriggered= */ false);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingStopDialogFragment.tag());
}
@Test
public void handleLeaDeviceConnected_noSharingNoTwoLeaDevices_doNothing() {
setUpBroadcast(false);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ false);
shadowOf(Looper.getMainLooper()).idle();
verify(mCachedDevice1, times(0)).setActive();
}
@Test
public void handleLeaDeviceConnected_noSharingTwoLeaDevices_showJoinDialog() {
setUpBroadcast(false);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1, mDevice3);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ false);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingJoinDialogFragment.tag());
}
@Test
public void handleLeaDeviceConnected_sharing_showJoinDialog() {
setUpBroadcast(true);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1, mDevice3);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(mDevice1)).thenReturn(ImmutableList.of());
when(mAssistant.getAllSources(mDevice3)).thenReturn(ImmutableList.of(mState));
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ false);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingJoinDialogFragment.tag());
}
@Test
public void handleLeaDeviceConnected_sharingWithTwoLeaDevices_showDisconnectDialog() {
setUpBroadcast(true);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1, mDevice3, mDevice4);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(mDevice1)).thenReturn(ImmutableList.of());
when(mAssistant.getAllSources(mDevice3)).thenReturn(ImmutableList.of(mState));
when(mAssistant.getAllSources(mDevice4)).thenReturn(ImmutableList.of(mState));
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ false);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingDisconnectDialogFragment.tag());
}
@Test
public void closeOpeningDialogsForLeaDevice_closeJoinDialog() {
// Show join dialog
setUpBroadcast(false);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice1, mDevice3);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of());
mHandler.handleDeviceConnected(mCachedDevice1, /* userTriggered= */ true);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingJoinDialogFragment.tag());
// Close opening dialogs
mHandler.closeOpeningDialogsForLeaDevice(mCachedDevice1);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments()).isEmpty();
}
@Test
public void closeOpeningDialogsForNonLeaDevice_closeStopDialog() {
// Show stop dialog
setUpBroadcast(true);
ImmutableList<BluetoothDevice> deviceList = ImmutableList.of(mDevice2);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(deviceList);
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mState));
mHandler.handleDeviceConnected(mCachedDevice2, /* userTriggered= */ true);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments())
.comparingElementsUsing(TAG_EQUALS)
.containsExactly(AudioSharingStopDialogFragment.tag());
// Close opening dialogs
mHandler.closeOpeningDialogsForNonLeaDevice(mCachedDevice2);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mParentFragment.getChildFragmentManager().getFragments()).isEmpty();
}
private void setUpBroadcast(boolean isBroadcasting) {
when(mBroadcast.isEnabled(any())).thenReturn(isBroadcasting);
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class AudioSharingDialogHelperTest {
private static final String TAG = "test";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock FragmentManager mFragmentManager;
@Mock DialogFragment mFragment;
@Mock AlertDialog mDialog;
@Mock TextView mTextView;
@Test
public void updateMessageStyle_updateStyle() {
when(mDialog.findViewById(android.R.id.message)).thenReturn(mTextView);
AudioSharingDialogHelper.updateMessageStyle(mDialog);
Typeface typeface = Typeface.create(Typeface.DEFAULT_FAMILY, Typeface.NORMAL);
verify(mTextView).setTypeface(typeface);
verify(mTextView).setTextDirection(View.TEXT_DIRECTION_LOCALE);
verify(mTextView).setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
verify(mTextView).setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
}
@Test
public void getDialogIfShowing_notShowing_returnNull() {
when(mFragmentManager.findFragmentByTag(TAG)).thenReturn(mFragment);
when(mFragment.getDialog()).thenReturn(mDialog);
when(mDialog.isShowing()).thenReturn(false);
assertThat(AudioSharingDialogHelper.getDialogIfShowing(mFragmentManager, TAG)).isNull();
}
@Test
public void getDialogIfShowing_showing_returnDialog() {
when(mFragmentManager.findFragmentByTag(TAG)).thenReturn(mFragment);
when(mFragment.getDialog()).thenReturn(mDialog);
when(mDialog.isShowing()).thenReturn(true);
assertThat(AudioSharingDialogHelper.getDialogIfShowing(mFragmentManager, TAG))
.isEqualTo(mDialog);
}
}

View File

@@ -0,0 +1,238 @@
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import static org.robolectric.shadows.ShadowLooper.shadowMainLooper;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothStatusCodes;
import android.platform.test.flag.junit.SetFlagsRule;
import android.widget.Button;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowAlertDialogCompat;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.androidx.fragment.FragmentController;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowAlertDialogCompat.class,
ShadowBluetoothAdapter.class,
})
public class AudioSharingDisconnectDialogFragmentTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private static final String TEST_DEVICE_NAME1 = "test1";
private static final String TEST_DEVICE_NAME2 = "test2";
private static final String TEST_DEVICE_NAME3 = "test3";
private static final int TEST_GROUP_ID1 = 1;
private static final int TEST_GROUP_ID2 = 2;
private static final int TEST_GROUP_ID3 = 3;
private static final String TEST_ADDRESS1 = "XX:11";
private static final String TEST_ADDRESS3 = "XX:33";
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM1 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME1, TEST_GROUP_ID1, /* isActive= */ true);
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM2 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME2, TEST_GROUP_ID2, /* isActive= */ false);
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM3 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME3, TEST_GROUP_ID3, /* isActive= */ false);
@Mock private BluetoothDevice mDevice1;
@Mock private BluetoothDevice mDevice3;
@Mock private CachedBluetoothDevice mCachedDevice1;
@Mock private CachedBluetoothDevice mCachedDevice3;
private Fragment mParent;
private AudioSharingDisconnectDialogFragment mFragment;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private ArrayList<AudioSharingDeviceItem> mDeviceItems = new ArrayList<>();
@Before
public void setUp() {
AlertDialog latestAlertDialog = ShadowAlertDialogCompat.getLatestAlertDialog();
if (latestAlertDialog != null) {
latestAlertDialog.dismiss();
ShadowAlertDialogCompat.reset();
}
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
when(mDevice1.getAnonymizedAddress()).thenReturn(TEST_ADDRESS1);
when(mDevice3.getAnonymizedAddress()).thenReturn(TEST_ADDRESS3);
when(mCachedDevice1.getName()).thenReturn(TEST_DEVICE_NAME1);
when(mCachedDevice1.getDevice()).thenReturn(mDevice1);
when(mCachedDevice1.getGroupId()).thenReturn(TEST_GROUP_ID1);
when(mCachedDevice3.getName()).thenReturn(TEST_DEVICE_NAME3);
when(mCachedDevice3.getDevice()).thenReturn(mDevice3);
when(mCachedDevice3.getGroupId()).thenReturn(TEST_GROUP_ID3);
mFragment = new AudioSharingDisconnectDialogFragment();
mParent = new Fragment();
FragmentController.setupFragment(
mParent, FragmentActivity.class, /* containerViewId= */ 0, /* bundle= */ null);
}
@Test
public void onCreateDialog_flagOff_dialogNotExist() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mDeviceItems = new ArrayList<>();
mDeviceItems.add(TEST_DEVICE_ITEM1);
mDeviceItems.add(TEST_DEVICE_ITEM2);
mFragment.show(mParent, mDeviceItems, mCachedDevice3, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNull();
}
@Test
public void onCreateDialog_flagOn_dialogShowBtnForTwoDevices() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mDeviceItems = new ArrayList<>();
mDeviceItems.add(TEST_DEVICE_ITEM1);
mDeviceItems.add(TEST_DEVICE_ITEM2);
mFragment.show(mParent, mDeviceItems, mCachedDevice3, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog.isShowing()).isTrue();
RecyclerView view = dialog.findViewById(R.id.device_btn_list);
assertThat(view.getAdapter().getItemCount()).isEqualTo(2);
}
@Test
public void onCreateDialog_dialogIsShowingForSameGroup_updateDialog() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mDeviceItems = new ArrayList<>();
mDeviceItems.add(TEST_DEVICE_ITEM1);
mDeviceItems.add(TEST_DEVICE_ITEM2);
mFragment.show(mParent, mDeviceItems, mCachedDevice3, (item) -> {});
shadowMainLooper().idle();
AtomicBoolean isItemBtnClicked = new AtomicBoolean(false);
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog.isShowing()).isTrue();
RecyclerView view = dialog.findViewById(R.id.device_btn_list);
assertThat(view.getAdapter().getItemCount()).isEqualTo(2);
Button btn1 =
view.findViewHolderForAdapterPosition(0).itemView.findViewById(R.id.device_button);
assertThat(btn1.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_disconnect_device_button_label,
TEST_DEVICE_NAME1));
Button btn2 =
view.findViewHolderForAdapterPosition(1).itemView.findViewById(R.id.device_button);
assertThat(btn2.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_disconnect_device_button_label,
TEST_DEVICE_NAME2));
// Update dialog content for device with same group
mFragment.show(mParent, mDeviceItems, mCachedDevice3, (item) -> isItemBtnClicked.set(true));
shadowMainLooper().idle();
dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog.isShowing()).isTrue();
btn1 = view.findViewHolderForAdapterPosition(0).itemView.findViewById(R.id.device_button);
btn1.performClick();
assertThat(isItemBtnClicked.get()).isTrue();
}
@Test
public void onCreateDialog_dialogIsShowingForNewGroup_updateDialog() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mDeviceItems = new ArrayList<>();
mDeviceItems.add(TEST_DEVICE_ITEM1);
mDeviceItems.add(TEST_DEVICE_ITEM2);
mFragment.show(mParent, mDeviceItems, mCachedDevice3, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog.isShowing()).isTrue();
RecyclerView view = dialog.findViewById(R.id.device_btn_list);
assertThat(view.getAdapter().getItemCount()).isEqualTo(2);
// Show new dialog for device with new group
ArrayList<AudioSharingDeviceItem> newDeviceItems = new ArrayList<>();
newDeviceItems.add(TEST_DEVICE_ITEM2);
newDeviceItems.add(TEST_DEVICE_ITEM3);
mFragment.show(mParent, newDeviceItems, mCachedDevice1, (item) -> {});
shadowMainLooper().idle();
dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog.isShowing()).isTrue();
view = dialog.findViewById(R.id.device_btn_list);
assertThat(view.getAdapter().getItemCount()).isEqualTo(2);
Button btn1 =
view.findViewHolderForAdapterPosition(0).itemView.findViewById(R.id.device_button);
assertThat(btn1.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_disconnect_device_button_label,
TEST_DEVICE_NAME2));
Button btn2 =
view.findViewHolderForAdapterPosition(1).itemView.findViewById(R.id.device_button);
assertThat(btn2.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_disconnect_device_button_label,
TEST_DEVICE_NAME3));
}
@Test
public void onCreateDialog_clickCancel_dialogDismiss() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mDeviceItems = new ArrayList<>();
mDeviceItems.add(TEST_DEVICE_ITEM1);
mDeviceItems.add(TEST_DEVICE_ITEM2);
mFragment.show(mParent, mDeviceItems, mCachedDevice3, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog.isShowing()).isTrue();
dialog.findViewById(R.id.negative_btn).performClick();
assertThat(dialog.isShowing()).isFalse();
}
}

View File

@@ -0,0 +1,231 @@
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import static org.robolectric.shadows.ShadowLooper.shadowMainLooper;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothStatusCodes;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowAlertDialogCompat;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.androidx.fragment.FragmentController;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowAlertDialogCompat.class,
ShadowBluetoothAdapter.class,
})
public class AudioSharingJoinDialogFragmentTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private static final String TEST_DEVICE_NAME1 = "test1";
private static final String TEST_DEVICE_NAME2 = "test2";
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM1 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME1, /* groupId= */ 1, /* isActive= */ true);
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM2 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME2, /* groupId= */ 2, /* isActive= */ false);
private static final AudioSharingJoinDialogFragment.DialogEventListener EMPTY_EVENT_LISTENER =
new AudioSharingJoinDialogFragment.DialogEventListener() {
@Override
public void onShareClick() {}
@Override
public void onCancelClick() {}
};
@Mock private CachedBluetoothDevice mCachedDevice1;
@Mock private CachedBluetoothDevice mCachedDevice2;
private Fragment mParent;
private AudioSharingJoinDialogFragment mFragment;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
@Before
public void setUp() {
AlertDialog latestAlertDialog = ShadowAlertDialogCompat.getLatestAlertDialog();
if (latestAlertDialog != null) {
latestAlertDialog.dismiss();
ShadowAlertDialogCompat.reset();
}
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
when(mCachedDevice1.getName()).thenReturn(TEST_DEVICE_NAME1);
when(mCachedDevice2.getName()).thenReturn(TEST_DEVICE_NAME2);
mFragment = new AudioSharingJoinDialogFragment();
mParent = new Fragment();
FragmentController.setupFragment(
mParent, FragmentActivity.class, /* containerViewId= */ 0, /* bundle= */ null);
}
@Test
public void onCreateDialog_flagOff_dialogNotExist() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, new ArrayList<>(), mCachedDevice2, EMPTY_EVENT_LISTENER);
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNull();
}
@Test
public void onCreateDialog_flagOn_dialogShowTextForSingleDevice() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, new ArrayList<>(), mCachedDevice2, EMPTY_EVENT_LISTENER);
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
ShadowAlertDialogCompat shadowDialog = ShadowAlertDialogCompat.shadowOf(dialog);
assertThat(shadowDialog.getMessage().toString()).isEqualTo(TEST_DEVICE_NAME2);
}
@Test
public void onCreateDialog_flagOn_dialogShowTextForTwoDevice() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArrayList<AudioSharingDeviceItem> list = new ArrayList<>();
list.add(TEST_DEVICE_ITEM1);
mFragment.show(mParent, list, mCachedDevice2, EMPTY_EVENT_LISTENER);
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
ShadowAlertDialogCompat shadowDialog = ShadowAlertDialogCompat.shadowOf(dialog);
assertThat(shadowDialog.getMessage().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_share_dialog_subtitle,
TEST_DEVICE_NAME1,
TEST_DEVICE_NAME2));
}
@Test
public void onCreateDialog_dialogIsShowing_updateDialog() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArrayList<AudioSharingDeviceItem> list = new ArrayList<>();
list.add(TEST_DEVICE_ITEM1);
mFragment.show(mParent, list, mCachedDevice2, EMPTY_EVENT_LISTENER);
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
// Update the content
ArrayList<AudioSharingDeviceItem> list2 = new ArrayList<>();
list2.add(TEST_DEVICE_ITEM2);
mFragment.show(mParent, list2, mCachedDevice1, EMPTY_EVENT_LISTENER);
shadowMainLooper().idle();
dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
ShadowAlertDialogCompat shadowDialog = ShadowAlertDialogCompat.shadowOf(dialog);
assertThat(shadowDialog.getMessage().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_share_dialog_subtitle,
TEST_DEVICE_NAME2,
TEST_DEVICE_NAME1));
}
@Test
public void onCreateDialog_clickCancel_dialogDismiss() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, new ArrayList<>(), mCachedDevice2, EMPTY_EVENT_LISTENER);
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(R.id.negative_btn).performClick();
assertThat(dialog.isShowing()).isFalse();
}
@Test
public void onCreateDialog_clickBtn_callbackTriggered() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
AtomicBoolean isShareBtnClicked = new AtomicBoolean(false);
mFragment.show(
mParent,
new ArrayList<>(),
mCachedDevice2,
new AudioSharingJoinDialogFragment.DialogEventListener() {
@Override
public void onShareClick() {
isShareBtnClicked.set(true);
}
@Override
public void onCancelClick() {}
});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(R.id.positive_btn).performClick();
assertThat(dialog.isShowing()).isFalse();
assertThat(isShareBtnClicked.get()).isTrue();
}
@Test
public void onCreateDialog_clickCancel_callbackTriggered() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
AtomicBoolean isCancelBtnClicked = new AtomicBoolean(false);
mFragment.show(
mParent,
new ArrayList<>(),
mCachedDevice2,
new AudioSharingJoinDialogFragment.DialogEventListener() {
@Override
public void onShareClick() {}
@Override
public void onCancelClick() {
isCancelBtnClicked.set(true);
}
});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(R.id.negative_btn).performClick();
assertThat(dialog.isShowing()).isFalse();
assertThat(isCancelBtnClicked.get()).isTrue();
}
}

View File

@@ -0,0 +1,185 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothStatusCodes;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowBluetoothAdapter.class})
public class AudioSharingPlaySoundPreferenceControllerTest {
private static final String PREF_KEY = "audio_sharing_play_sound";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Spy Context mContext = ApplicationProvider.getApplicationContext();
@Mock private PreferenceScreen mScreen;
@Mock private Ringtone mRingtone;
private AudioSharingPlaySoundPreferenceController mController;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private Preference mPreference;
@Before
public void setUp() {
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
when(mRingtone.getStreamType()).thenReturn(AudioManager.STREAM_MUSIC);
when(mRingtone.getAudioAttributes()).thenReturn(new AudioAttributes.Builder().build());
mController = new AudioSharingPlaySoundPreferenceController(mContext);
mController.setRingtone(mRingtone);
mPreference = new Preference(mContext);
when(mScreen.findPreference(PREF_KEY)).thenReturn(mPreference);
}
@Test
public void getAvailabilityStatus_flagOn_available() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_flagOff_unsupported() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void getAvailabilityStatus_nullRingtone_unsupported() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setRingtone(null);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void displayPreference_visible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mPreference.setVisible(false);
mController.displayPreference(mScreen);
assertThat(mPreference.isVisible()).isTrue();
}
@Test
public void displayPreference_nullRingtone_invisible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mPreference.setVisible(true);
mController.setRingtone(null);
mController.displayPreference(mScreen);
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void displayPreference_flagOff_invisible() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mPreference.setVisible(true);
mController.displayPreference(mScreen);
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void getPreferenceKey_returnsCorrectKey() {
assertThat(mController.getPreferenceKey()).isEqualTo(PREF_KEY);
}
@Test
public void clickPreference_ringtoneIsNull_doNothing() {
mController.setRingtone(null);
when(mRingtone.isPlaying()).thenReturn(false);
doNothing().when(mRingtone).play();
mController.displayPreference(mScreen);
mPreference.performClick();
verify(mRingtone, times(0)).play();
}
@Test
public void clickPreference_isPlaying_doNothing() {
when(mRingtone.isPlaying()).thenReturn(true);
doNothing().when(mRingtone).play();
mController.displayPreference(mScreen);
mPreference.performClick();
verify(mRingtone, times(0)).play();
}
@Test
public void clickPreference_notPlaying_play() {
when(mRingtone.isPlaying()).thenReturn(false);
doNothing().when(mRingtone).play();
mController.displayPreference(mScreen);
mPreference.performClick();
verify(mRingtone).play();
}
@Test
public void nonStop_isPlaying_stop() {
when(mRingtone.isPlaying()).thenReturn(true);
doNothing().when(mRingtone).stop();
mController.onStop(mLifecycleOwner);
verify(mRingtone).stop();
}
@Test
public void nonStop_notPlaying_doNothing() {
when(mRingtone.isPlaying()).thenReturn(false);
doNothing().when(mRingtone).stop();
mController.onStop(mLifecycleOwner);
verify(mRingtone, times(0)).stop();
}
}

View File

@@ -0,0 +1,169 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static android.bluetooth.BluetoothAdapter.STATE_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_ON;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothLeBroadcast;
import android.bluetooth.BluetoothStatusCodes;
import android.content.Context;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settings.bluetooth.Utils;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settings.testutils.shadow.ShadowThreadUtils;
import com.android.settingslib.bluetooth.BluetoothEventManager;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
ShadowThreadUtils.class
})
public class AudioSharingPreferenceControllerTest {
private static final String PREF_KEY = "audio_sharing_settings";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Spy Context mContext = ApplicationProvider.getApplicationContext();
@Mock private PreferenceScreen mScreen;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private BluetoothEventManager mBtEventManager;
@Mock private LocalBluetoothProfileManager mLocalBtProfileManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
private AudioSharingPreferenceController mController;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private LocalBluetoothManager mLocalBluetoothManager;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private Preference mPreference;
@Before
public void setUp() {
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBluetoothManager = Utils.getLocalBtManager(mContext);
when(mLocalBluetoothManager.getEventManager()).thenReturn(mBtEventManager);
when(mLocalBluetoothManager.getProfileManager()).thenReturn(mLocalBtProfileManager);
when(mLocalBtProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
mController = new AudioSharingPreferenceController(mContext, PREF_KEY);
mPreference = new Preference(mContext);
when(mScreen.findPreference(PREF_KEY)).thenReturn(mPreference);
}
@Test
public void onStart_registerCallback() {
mController.onStart(mLifecycleOwner);
verify(mBtEventManager).registerCallback(mController);
verify(mBroadcast).registerServiceCallBack(any(), any(BluetoothLeBroadcast.Callback.class));
}
@Test
public void onStop_unregisterCallback() {
mController.onStop(mLifecycleOwner);
verify(mBtEventManager).unregisterCallback(mController);
verify(mBroadcast).unregisterServiceCallBack(any(BluetoothLeBroadcast.Callback.class));
}
@Test
public void getAvailabilityStatus_flagOn() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_flagOff() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void getSummary_broadcastOn() {
when(mBroadcast.isEnabled(any())).thenReturn(true);
assertThat(mController.getSummary().toString())
.isEqualTo(mContext.getString(R.string.audio_sharing_summary_on));
}
@Test
public void getSummary_broadcastOff() {
when(mBroadcast.isEnabled(any())).thenReturn(false);
assertThat(mController.getSummary().toString())
.isEqualTo(mContext.getString(R.string.audio_sharing_summary_off));
}
@Test
public void onBluetoothStateChanged_refreshSummary() {
mController.displayPreference(mScreen);
when(mBroadcast.isEnabled(any())).thenReturn(true);
mController.onBluetoothStateChanged(STATE_ON);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.getSummary().toString())
.isEqualTo(mContext.getString(R.string.audio_sharing_summary_on));
when(mBroadcast.isEnabled(any())).thenReturn(false);
mController.onBluetoothStateChanged(STATE_OFF);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.getSummary().toString())
.isEqualTo(mContext.getString(R.string.audio_sharing_summary_off));
}
}

View File

@@ -0,0 +1,210 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast.ACTION_LE_AUDIO_SHARING_STATE_CHANGE;
import static com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast.BROADCAST_STATE_OFF;
import static com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast.BROADCAST_STATE_ON;
import static com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast.EXTRA_LE_AUDIO_SHARING_STATE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import android.app.Notification;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothStatusCodes;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.platform.test.flag.junit.SetFlagsRule;
import com.android.settings.bluetooth.Utils;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settingslib.R;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowApplication;
import java.util.List;
import java.util.stream.Collectors;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowBluetoothAdapter.class, ShadowBluetoothUtils.class})
public class AudioSharingReceiverTest {
private static final String ACTION_LE_AUDIO_SHARING_STOP =
"com.android.settings.action.BLUETOOTH_LE_AUDIO_SHARING_STOP";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private Context mContext;
private ShadowApplication mShadowApplication;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private LocalBluetoothManager mLocalBluetoothManager;
@Mock private LocalBluetoothProfileManager mLocalBtProfileManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private NotificationManager mNm;
@Before
public void setUp() {
mContext = RuntimeEnvironment.getApplication();
mShadowApplication = Shadow.extract(mContext);
mShadowApplication.setSystemService(Context.NOTIFICATION_SERVICE, mNm);
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBluetoothManager = Utils.getLocalBtManager(mContext);
when(mLocalBluetoothManager.getProfileManager()).thenReturn(mLocalBtProfileManager);
when(mLocalBtProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
}
@Test
public void broadcastReceiver_isRegistered() {
List<ShadowApplication.Wrapper> registeredReceivers =
mShadowApplication.getRegisteredReceivers();
int matchedCount =
registeredReceivers.stream()
.filter(
receiver ->
AudioSharingReceiver.class
.getSimpleName()
.equals(
receiver.broadcastReceiver
.getClass()
.getSimpleName()))
.collect(Collectors.toList())
.size();
assertThat(matchedCount).isEqualTo(1);
}
@Test
public void broadcastReceiver_receiveAudioSharingStateChangeIntentFlagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Intent intent = new Intent(ACTION_LE_AUDIO_SHARING_STATE_CHANGE);
intent.setPackage(mContext.getPackageName());
intent.putExtra(EXTRA_LE_AUDIO_SHARING_STATE, BROADCAST_STATE_ON);
AudioSharingReceiver audioSharingReceiver = getAudioSharingReceiver(intent);
audioSharingReceiver.onReceive(mContext, intent);
verifyNoInteractions(mNm);
}
@Test
public void broadcastReceiver_receiveAudioSharingStateChangeIntentNoState_doNothing() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Intent intent = new Intent(ACTION_LE_AUDIO_SHARING_STATE_CHANGE);
intent.setPackage(mContext.getPackageName());
AudioSharingReceiver audioSharingReceiver = getAudioSharingReceiver(intent);
audioSharingReceiver.onReceive(mContext, intent);
verifyNoInteractions(mNm);
}
@Test
public void broadcastReceiver_receiveAudioSharingStateChangeIntentOnState_showNotification() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Intent intent = new Intent(ACTION_LE_AUDIO_SHARING_STATE_CHANGE);
intent.setPackage(mContext.getPackageName());
intent.putExtra(EXTRA_LE_AUDIO_SHARING_STATE, BROADCAST_STATE_ON);
AudioSharingReceiver audioSharingReceiver = getAudioSharingReceiver(intent);
audioSharingReceiver.onReceive(mContext, intent);
verify(mNm, times(1))
.notify(eq(R.drawable.ic_bt_le_audio_sharing), any(Notification.class));
}
@Test
public void
broadcastReceiver_receiveAudioSharingStateChangeIntentOffState_cancelNotification() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Intent intent = new Intent(ACTION_LE_AUDIO_SHARING_STATE_CHANGE);
intent.setPackage(mContext.getPackageName());
intent.putExtra(EXTRA_LE_AUDIO_SHARING_STATE, BROADCAST_STATE_OFF);
AudioSharingReceiver audioSharingReceiver = getAudioSharingReceiver(intent);
audioSharingReceiver.onReceive(mContext, intent);
verify(mNm, times(1)).cancel(R.drawable.ic_bt_le_audio_sharing);
}
@Test
public void broadcastReceiver_receiveAudioSharingStopIntentFlagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
Intent intent = new Intent(ACTION_LE_AUDIO_SHARING_STOP);
intent.setPackage(mContext.getPackageName());
AudioSharingReceiver audioSharingReceiver = getAudioSharingReceiver(intent);
audioSharingReceiver.onReceive(mContext, intent);
verifyNoInteractions(mBroadcast);
}
@Test
public void broadcastReceiver_receiveAudioSharingStopIntent_stopBroadcast() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
int broadcastId = 1;
when(mBroadcast.getLatestBroadcastId()).thenReturn(broadcastId);
Intent intent = new Intent(ACTION_LE_AUDIO_SHARING_STOP);
intent.setPackage(mContext.getPackageName());
AudioSharingReceiver audioSharingReceiver = getAudioSharingReceiver(intent);
audioSharingReceiver.onReceive(mContext, intent);
verify(mBroadcast, times(1)).stopBroadcast(broadcastId);
}
private AudioSharingReceiver getAudioSharingReceiver(Intent intent) {
assertThat(mShadowApplication.hasReceiverForIntent(intent)).isTrue();
List<BroadcastReceiver> receiversForIntent =
mShadowApplication.getReceiversForIntent(intent);
assertThat(receiversForIntent).hasSize(1);
BroadcastReceiver broadcastReceiver = receiversForIntent.get(0);
assertThat(broadcastReceiver).isInstanceOf(AudioSharingReceiver.class);
return (AudioSharingReceiver) broadcastReceiver;
}
}

View File

@@ -0,0 +1,242 @@
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import static org.robolectric.shadows.ShadowLooper.shadowMainLooper;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothStatusCodes;
import android.platform.test.flag.junit.SetFlagsRule;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.android.settings.R;
import com.android.settings.testutils.shadow.ShadowAlertDialogCompat;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.flags.Flags;
import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.androidx.fragment.FragmentController;
import java.util.concurrent.atomic.AtomicBoolean;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowAlertDialogCompat.class,
ShadowBluetoothAdapter.class,
})
public class AudioSharingStopDialogFragmentTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private static final String TEST_DEVICE_NAME1 = "test1";
private static final String TEST_DEVICE_NAME2 = "test2";
private static final String TEST_DEVICE_NAME3 = "test3";
private static final int TEST_DEVICE_GROUP_ID1 = 1;
private static final int TEST_DEVICE_GROUP_ID2 = 2;
private static final int TEST_DEVICE_GROUP_ID3 = 3;
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM2 =
new AudioSharingDeviceItem(
TEST_DEVICE_NAME2, TEST_DEVICE_GROUP_ID2, /* isActive= */ false);
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM3 =
new AudioSharingDeviceItem(
TEST_DEVICE_NAME3, TEST_DEVICE_GROUP_ID3, /* isActive= */ false);
@Mock private CachedBluetoothDevice mCachedDevice1;
@Mock private CachedBluetoothDevice mCachedDevice2;
@Mock private BluetoothDevice mDevice1;
@Mock private BluetoothDevice mDevice2;
private Fragment mParent;
private AudioSharingStopDialogFragment mFragment;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
@Before
public void setUp() {
AlertDialog latestAlertDialog = ShadowAlertDialogCompat.getLatestAlertDialog();
if (latestAlertDialog != null) {
latestAlertDialog.dismiss();
ShadowAlertDialogCompat.reset();
}
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
when(mCachedDevice1.getName()).thenReturn(TEST_DEVICE_NAME1);
when(mCachedDevice1.getGroupId()).thenReturn(TEST_DEVICE_GROUP_ID1);
when(mCachedDevice1.getDevice()).thenReturn(mDevice1);
when(mCachedDevice2.getName()).thenReturn(TEST_DEVICE_NAME2);
when(mCachedDevice2.getGroupId()).thenReturn(TEST_DEVICE_GROUP_ID2);
when(mCachedDevice2.getDevice()).thenReturn(mDevice2);
mFragment = new AudioSharingStopDialogFragment();
mParent = new Fragment();
FragmentController.setupFragment(
mParent, FragmentActivity.class, /* containerViewId= */ 0, /* bundle= */ null);
}
@Test
public void onCreateDialog_flagOff_dialogNotExist() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, ImmutableList.of(), mCachedDevice1, () -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNull();
}
@Test
public void onCreateDialog_oneDeviceInSharing_showDialogWithCorrectMessage() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, ImmutableList.of(TEST_DEVICE_ITEM2), mCachedDevice1, () -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
TextView view = dialog.findViewById(R.id.description_text);
assertThat(view.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_stop_dialog_content, TEST_DEVICE_NAME2));
}
@Test
public void onCreateDialog_twoDeviceInSharing_showDialogWithCorrectMessage() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(
mParent,
ImmutableList.of(TEST_DEVICE_ITEM2, TEST_DEVICE_ITEM3),
mCachedDevice1,
() -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
TextView view = dialog.findViewById(R.id.description_text);
assertThat(view.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_stop_dialog_with_two_content,
TEST_DEVICE_NAME2,
TEST_DEVICE_NAME3));
}
@Test
public void onCreateDialog_dialogIsShowingForSameDevice_updateDialog() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, ImmutableList.of(), mCachedDevice1, () -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
TextView view = dialog.findViewById(R.id.description_text);
assertThat(view.getText().toString())
.isEqualTo(mParent.getString(R.string.audio_sharing_stop_dialog_with_more_content));
// Update the content
AtomicBoolean isStopBtnClicked = new AtomicBoolean(false);
mFragment.show(
mParent, ImmutableList.of(), mCachedDevice1, () -> isStopBtnClicked.set(true));
shadowMainLooper().idle();
dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
dialog.findViewById(android.R.id.button1).performClick();
shadowMainLooper().idle();
assertThat(dialog.isShowing()).isFalse();
assertThat(isStopBtnClicked.get()).isTrue();
}
@Test
public void onCreateDialog_dialogIsShowingForNewDevice_showNewDialog() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, ImmutableList.of(), mCachedDevice1, () -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
TextView view = dialog.findViewById(R.id.description_text);
assertThat(view.getText().toString())
.isEqualTo(mParent.getString(R.string.audio_sharing_stop_dialog_with_more_content));
TextView title = dialog.findViewById(R.id.title_text);
assertThat(title.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_stop_dialog_title, TEST_DEVICE_NAME1));
// Show new dialog
mFragment.show(mParent, ImmutableList.of(), mCachedDevice2, () -> {});
shadowMainLooper().idle();
dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
view = dialog.findViewById(R.id.description_text);
assertThat(view.getText().toString())
.isEqualTo(mParent.getString(R.string.audio_sharing_stop_dialog_with_more_content));
title = dialog.findViewById(R.id.title_text);
assertThat(title.getText().toString())
.isEqualTo(
mParent.getString(
R.string.audio_sharing_stop_dialog_title, TEST_DEVICE_NAME2));
}
@Test
public void onCreateDialog_clickCancel_dialogDismiss() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, ImmutableList.of(), mCachedDevice1, () -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(android.R.id.button2).performClick();
shadowMainLooper().idle();
assertThat(dialog.isShowing()).isFalse();
}
@Test
public void onCreateDialog_clickShare_callbackTriggered() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
AtomicBoolean isStopBtnClicked = new AtomicBoolean(false);
mFragment.show(
mParent, ImmutableList.of(), mCachedDevice1, () -> isStopBtnClicked.set(true));
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
dialog.findViewById(android.R.id.button1).performClick();
shadowMainLooper().idle();
assertThat(dialog.isShowing()).isFalse();
assertThat(isStopBtnClicked.get()).isTrue();
}
}

View File

@@ -0,0 +1,365 @@
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcast;
import android.bluetooth.BluetoothLeBroadcastAssistant;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothStatusCodes;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import android.widget.CompoundButton;
import androidx.lifecycle.LifecycleOwner;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.bluetooth.Utils;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settings.testutils.shadow.ShadowThreadUtils;
import com.android.settings.widget.SettingsMainSwitchBar;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.bluetooth.VolumeControlProfile;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import java.util.concurrent.Executor;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
ShadowThreadUtils.class,
})
public class AudioSharingSwitchBarControllerTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Spy Context mContext = ApplicationProvider.getApplicationContext();
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private CachedBluetoothDeviceManager mDeviceManager;
@Mock private LocalBluetoothProfileManager mBtProfileManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private VolumeControlProfile mVolumeControl;
@Mock private CompoundButton mBtnView;
@Mock private CachedBluetoothDevice mCachedDevice;
@Mock private BluetoothDevice mDevice;
private SettingsMainSwitchBar mSwitchBar;
private AudioSharingSwitchBarController mController;
private AudioSharingSwitchBarController.OnAudioSharingStateChangedListener mListener;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private boolean mOnAudioSharingStateChanged;
private boolean mOnAudioSharingServiceConnected;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private LocalBluetoothManager mLocalBluetoothManager;
@Before
public void setUp() {
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBluetoothManager = Utils.getLocalBtManager(mContext);
when(mLocalBluetoothManager.getProfileManager()).thenReturn(mBtProfileManager);
when(mLocalBluetoothManager.getCachedDeviceManager()).thenReturn(mDeviceManager);
when(mDeviceManager.findDevice(mDevice)).thenReturn(mCachedDevice);
when(mCachedDevice.getDevice()).thenReturn(mDevice);
when(mCachedDevice.getGroupId()).thenReturn(1);
when(mCachedDevice.getName()).thenReturn("test");
when(mBtProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
when(mBtProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
when(mBtProfileManager.getVolumeControlProfile()).thenReturn(mVolumeControl);
when(mVolumeControl.isProfileReady()).thenReturn(true);
when(mBroadcast.isProfileReady()).thenReturn(true);
doNothing()
.when(mBroadcast)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcast.Callback.class));
doNothing()
.when(mBroadcast)
.unregisterServiceCallBack(any(BluetoothLeBroadcast.Callback.class));
when(mAssistant.isProfileReady()).thenReturn(true);
doNothing()
.when(mAssistant)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
doNothing()
.when(mAssistant)
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
mSwitchBar = new SettingsMainSwitchBar(mContext);
mSwitchBar.setDisabledByAdmin(mock(RestrictedLockUtils.EnforcedAdmin.class));
mOnAudioSharingStateChanged = false;
mOnAudioSharingServiceConnected = false;
mListener =
new AudioSharingSwitchBarController.OnAudioSharingStateChangedListener() {
@Override
public void onAudioSharingStateChanged() {
mOnAudioSharingStateChanged = true;
}
@Override
public void onAudioSharingProfilesConnected() {
mOnAudioSharingServiceConnected = true;
}
};
mController = new AudioSharingSwitchBarController(mContext, mSwitchBar, mListener);
}
@Test
public void bluetoothOff_switchDisabled() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mSwitchBar.isEnabled()).isTrue();
mContext.registerReceiver(
mController.mReceiver,
mController.mIntentFilter,
Context.RECEIVER_EXPORTED_UNAUDITED);
mShadowBluetoothAdapter.setEnabled(false);
when(mBroadcast.isEnabled(null)).thenReturn(false);
Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
mContext.sendBroadcast(intent);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mSwitchBar.isEnabled()).isFalse();
assertThat(mSwitchBar.isChecked()).isFalse();
assertThat(mOnAudioSharingStateChanged).isTrue();
assertThat(mOnAudioSharingServiceConnected).isFalse();
}
@Test
public void onServiceConnected_switchEnabled() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(null)).thenReturn(true);
mController.onServiceConnected();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mSwitchBar.isEnabled()).isTrue();
assertThat(mSwitchBar.isChecked()).isTrue();
assertThat(mOnAudioSharingStateChanged).isTrue();
assertThat(mOnAudioSharingServiceConnected).isTrue();
verify(mBtProfileManager).removeServiceListener(mController);
}
@Test
public void getAvailabilityStatus_flagOn() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_flagOff() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void onStart_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mContext, times(0))
.registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class), anyInt());
verify(mBroadcast, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcast.Callback.class));
verify(mAssistant, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mBtProfileManager, times(0)).addServiceListener(mController);
}
@Test
public void onStart_flagOnProfileNotReady_registerProfileCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(null)).thenReturn(false);
when(mBroadcast.isProfileReady()).thenReturn(false);
mController.onStart(mLifecycleOwner);
shadowOf(Looper.getMainLooper()).idle();
verify(mContext)
.registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class), anyInt());
verify(mBroadcast, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcast.Callback.class));
verify(mAssistant, times(0))
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mBtProfileManager).addServiceListener(mController);
assertThat(mSwitchBar.isChecked()).isFalse();
assertThat(mSwitchBar.isEnabled()).isFalse();
}
@Test
public void onStart_flagOn_registerCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(null)).thenReturn(true);
mController.onStart(mLifecycleOwner);
shadowOf(Looper.getMainLooper()).idle();
verify(mContext)
.registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class), anyInt());
verify(mBroadcast)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcast.Callback.class));
verify(mAssistant)
.registerServiceCallBack(
any(Executor.class), any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mBtProfileManager, times(0)).addServiceListener(mController);
assertThat(mSwitchBar.isChecked()).isTrue();
assertThat(mSwitchBar.isEnabled()).isTrue();
}
@Test
public void onStop_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStop(mLifecycleOwner);
verify(mContext, times(0)).unregisterReceiver(any(BroadcastReceiver.class));
verify(mBroadcast, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcast.Callback.class));
verify(mAssistant, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
verify(mBtProfileManager, times(0)).removeServiceListener(mController);
}
@Test
public void onStop_flagOn_notRegistered_doNothing() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(false);
doNothing().when(mContext).unregisterReceiver(any(BroadcastReceiver.class));
mController.onStop(mLifecycleOwner);
verify(mContext).unregisterReceiver(any(BroadcastReceiver.class));
verify(mBtProfileManager).removeServiceListener(mController);
verify(mBroadcast, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcast.Callback.class));
verify(mAssistant, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
}
@Test
public void onStop_flagOn_registered_unregisterCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mContext.registerReceiver(
mController.mReceiver,
mController.mIntentFilter,
Context.RECEIVER_EXPORTED_UNAUDITED);
mController.onStop(mLifecycleOwner);
verify(mContext).unregisterReceiver(mController.mReceiver);
verify(mBtProfileManager).removeServiceListener(mController);
verify(mBroadcast).unregisterServiceCallBack(any(BluetoothLeBroadcast.Callback.class));
verify(mAssistant)
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
}
@Test
public void onCheckedChangedToChecked_sharing_doNothing() {
when(mBtnView.isEnabled()).thenReturn(true);
when(mBroadcast.isEnabled(null)).thenReturn(true);
mController.onCheckedChanged(mBtnView, /* isChecked= */ true);
verify(mBroadcast, times(0)).startPrivateBroadcast();
}
@Test
public void onCheckedChangedToChecked_noConnectedLeaDevices_notStartAudioSharing() {
when(mBtnView.isEnabled()).thenReturn(true);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(ImmutableList.of());
doNothing().when(mBroadcast).startPrivateBroadcast();
mController.onCheckedChanged(mBtnView, /* isChecked= */ true);
assertThat(mSwitchBar.isChecked()).isFalse();
verify(mBroadcast, times(0)).startPrivateBroadcast();
}
@Test
public void onCheckedChangedToChecked_notSharing_withConnectedLeaDevices_startAudioSharing() {
when(mBtnView.isEnabled()).thenReturn(true);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(ImmutableList.of(mDevice));
doNothing().when(mBroadcast).startPrivateBroadcast();
mController.onCheckedChanged(mBtnView, /* isChecked= */ true);
verify(mBroadcast).startPrivateBroadcast();
}
@Test
public void onCheckedChangedToUnChecked_notSharing_doNothing() {
when(mBtnView.isEnabled()).thenReturn(true);
when(mBroadcast.isEnabled(null)).thenReturn(false);
when(mBroadcast.getLatestBroadcastId()).thenReturn(1);
mController.onCheckedChanged(mBtnView, /* isChecked= */ false);
verify(mBroadcast, times(0)).stopBroadcast(anyInt());
}
@Test
public void onCheckedChangedToUnChecked_sharing_stopAudioSharing() {
when(mBtnView.isEnabled()).thenReturn(true);
when(mBroadcast.isEnabled(null)).thenReturn(true);
when(mBroadcast.getLatestBroadcastId()).thenReturn(1);
doNothing().when(mBroadcast).stopBroadcast(anyInt());
mController.onCheckedChanged(mBtnView, /* isChecked= */ false);
verify(mBroadcast).stopBroadcast(1);
}
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.shadows.ShadowLooper.shadowMainLooper;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothStatusCodes;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.android.settings.testutils.shadow.ShadowAlertDialogCompat;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.androidx.fragment.FragmentController;
import java.util.ArrayList;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowAlertDialogCompat.class,
ShadowBluetoothAdapter.class,
})
public class CallsAndAlarmsDialogFragmentTest {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private static final String TEST_DEVICE_NAME1 = "test1";
private static final String TEST_DEVICE_NAME2 = "test2";
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM1 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME1, /* groupId= */ 1, /* isActive= */ true);
private static final AudioSharingDeviceItem TEST_DEVICE_ITEM2 =
new AudioSharingDeviceItem(TEST_DEVICE_NAME2, /* groupId= */ 1, /* isActive= */ true);
private Fragment mParent;
private CallsAndAlarmsDialogFragment mFragment;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
@Before
public void setUp() {
ShadowAlertDialogCompat.reset();
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mFragment = new CallsAndAlarmsDialogFragment();
mParent = new Fragment();
FragmentController.setupFragment(
mParent, FragmentActivity.class, /* containerViewId= */ 0, /* bundle= */ null);
}
@Test
public void onCreateDialog_flagOff_dialogNotExist() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mFragment.show(mParent, new ArrayList<>(), (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog).isNull();
}
@Test
public void onCreateDialog_showCorrectItems() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
ArrayList<AudioSharingDeviceItem> deviceItemList = new ArrayList<>();
deviceItemList.add(TEST_DEVICE_ITEM1);
deviceItemList.add(TEST_DEVICE_ITEM2);
mFragment.show(mParent, deviceItemList, (item) -> {});
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(dialog.getListView().getCount()).isEqualTo(2);
}
}

View File

@@ -0,0 +1,381 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.android.settings.connecteddevice.audiosharing.AudioSharingUtils.SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothCsipSetCoordinator;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeBroadcastAssistant;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothStatusCodes;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.Settings;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settings.bluetooth.Utils;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settings.testutils.shadow.ShadowThreadUtils;
import com.android.settingslib.bluetooth.BluetoothEventManager;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.bluetooth.VolumeControlProfile;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
ShadowThreadUtils.class,
})
public class CallsAndAlarmsPreferenceControllerTest {
private static final String PREF_KEY = "calls_and_alarms";
private static final String TEST_DEVICE_NAME1 = "test1";
private static final String TEST_DEVICE_NAME2 = "test2";
private static final int TEST_DEVICE_GROUP_ID1 = 1;
private static final int TEST_DEVICE_GROUP_ID2 = 2;
private static final String TEST_SETTINGS_KEY =
"bluetooth_le_broadcast_fallback_active_group_id";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Spy Context mContext = ApplicationProvider.getApplicationContext();
@Mock private PreferenceScreen mScreen;
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private BluetoothEventManager mBtEventManager;
@Mock private LocalBluetoothProfileManager mBtProfileManager;
@Mock private CachedBluetoothDeviceManager mCacheManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private VolumeControlProfile mVolumeControl;
@Mock private BluetoothDevice mDevice1;
@Mock private BluetoothDevice mDevice2;
@Mock private BluetoothDevice mDevice3;
@Mock private CachedBluetoothDevice mCachedDevice1;
@Mock private CachedBluetoothDevice mCachedDevice2;
@Mock private CachedBluetoothDevice mCachedDevice3;
@Mock private BluetoothLeBroadcastReceiveState mState;
@Mock private ContentResolver mContentResolver;
private CallsAndAlarmsPreferenceController mController;
@Spy private ContentObserver mContentObserver;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private LocalBluetoothManager mBtManager;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private Preference mPreference;
@Before
public void setUp() {
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mBtManager = Utils.getLocalBtManager(mContext);
when(mBtManager.getEventManager()).thenReturn(mBtEventManager);
when(mBtManager.getProfileManager()).thenReturn(mBtProfileManager);
when(mBtManager.getCachedDeviceManager()).thenReturn(mCacheManager);
when(mBtProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
when(mBtProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
when(mBtProfileManager.getVolumeControlProfile()).thenReturn(mVolumeControl);
when(mBroadcast.isProfileReady()).thenReturn(true);
when(mAssistant.isProfileReady()).thenReturn(true);
when(mVolumeControl.isProfileReady()).thenReturn(true);
List<Long> bisSyncState = new ArrayList<>();
bisSyncState.add(1L);
when(mState.getBisSyncState()).thenReturn(bisSyncState);
when(mContext.getContentResolver()).thenReturn(mContentResolver);
mController = new CallsAndAlarmsPreferenceController(mContext);
mController.init(null);
mContentObserver = mController.getSettingsObserver();
mPreference = new Preference(mContext);
when(mScreen.findPreference(PREF_KEY)).thenReturn(mPreference);
}
@Test
public void onStart_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mBtEventManager, times(0)).registerCallback(mController);
verify(mContentResolver, times(0))
.registerContentObserver(
Settings.Secure.getUriFor(SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID),
false,
mContentObserver);
verify(mAssistant, times(0))
.registerServiceCallBack(any(), any(BluetoothLeBroadcastAssistant.Callback.class));
}
@Test
public void onStart_flagOn_registerCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mBtEventManager).registerCallback(mController);
verify(mContentResolver)
.registerContentObserver(
Settings.Secure.getUriFor(SETTINGS_KEY_FALLBACK_DEVICE_GROUP_ID),
false,
mContentObserver);
verify(mAssistant)
.registerServiceCallBack(any(), any(BluetoothLeBroadcastAssistant.Callback.class));
}
@Test
public void onStop_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mController.onStop(mLifecycleOwner);
verify(mBtEventManager, times(0)).unregisterCallback(mController);
verify(mContentResolver, times(0)).unregisterContentObserver(mContentObserver);
verify(mAssistant, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
}
@Test
public void onStop_flagOn_notRegistered_doNothing() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(false);
mController.onStop(mLifecycleOwner);
verify(mBtEventManager, times(0)).unregisterCallback(mController);
verify(mContentResolver, times(0)).unregisterContentObserver(mContentObserver);
verify(mAssistant, times(0))
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
}
@Test
public void onStop_flagOn_registered_unregisterCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.setCallbacksRegistered(true);
mController.onStop(mLifecycleOwner);
verify(mBtEventManager).unregisterCallback(mController);
verify(mContentResolver).unregisterContentObserver(mContentObserver);
verify(mAssistant)
.unregisterServiceCallBack(any(BluetoothLeBroadcastAssistant.Callback.class));
}
@Test
public void getAvailabilityStatus_flagOn() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_flagOff() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void updateVisibility_flagOff_invisible() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(any())).thenReturn(true);
mController.displayPreference(mScreen);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void updateVisibility_broadcastOffBluetoothOff_invisible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(any())).thenReturn(false);
mShadowBluetoothAdapter.setEnabled(false);
mController.displayPreference(mScreen);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void updateVisibility_broadcastOnBluetoothOff_invisible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(any())).thenReturn(true);
mShadowBluetoothAdapter.setEnabled(false);
mController.displayPreference(mScreen);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void updateVisibility_broadcastOffBluetoothOn_invisible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(any())).thenReturn(false);
mController.displayPreference(mScreen);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void updateVisibility_broadcastOnBluetoothOn_visible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isEnabled(any())).thenReturn(true);
mController.displayPreference(mScreen);
mController.updateVisibility();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isTrue();
}
@Test
public void onProfileConnectionStateChanged_noDeviceInSharing_updateSummary() {
Settings.Secure.putInt(mContentResolver, TEST_SETTINGS_KEY, TEST_DEVICE_GROUP_ID1);
when(mBroadcast.isEnabled(any())).thenReturn(true);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(ImmutableList.of());
mController.displayPreference(mScreen);
mPreference.setSummary("test");
mController.onProfileConnectionStateChanged(
mCachedDevice1,
BluetoothAdapter.STATE_DISCONNECTED,
BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.getSummary().toString()).isEmpty();
}
@Test
public void onFallbackDeviceChanged_updateSummary() {
Settings.Secure.putInt(mContentResolver, TEST_SETTINGS_KEY, TEST_DEVICE_GROUP_ID1);
when(mCachedDevice1.getGroupId()).thenReturn(TEST_DEVICE_GROUP_ID1);
when(mCachedDevice1.getDevice()).thenReturn(mDevice1);
when(mCachedDevice1.getName()).thenReturn(TEST_DEVICE_NAME1);
when(mCacheManager.findDevice(mDevice1)).thenReturn(mCachedDevice1);
when(mBroadcast.isEnabled(any())).thenReturn(true);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(ImmutableList.of(mDevice1));
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mState));
mController.displayPreference(mScreen);
mContentObserver.onChange(true);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.getSummary().toString())
.isEqualTo(
mContext.getString(
R.string.audio_sharing_call_audio_description, TEST_DEVICE_NAME1));
}
@Test
public void displayPreference_showCorrectSummary() {
Settings.Secure.putInt(mContentResolver, TEST_SETTINGS_KEY, TEST_DEVICE_GROUP_ID1);
when(mCachedDevice1.getGroupId()).thenReturn(TEST_DEVICE_GROUP_ID1);
when(mCachedDevice1.getDevice()).thenReturn(mDevice1);
when(mCachedDevice2.getGroupId()).thenReturn(TEST_DEVICE_GROUP_ID1);
when(mCachedDevice2.getDevice()).thenReturn(mDevice2);
when(mCachedDevice1.getMemberDevice()).thenReturn(ImmutableSet.of(mCachedDevice2));
when(mCachedDevice1.getName()).thenReturn(TEST_DEVICE_NAME1);
when(mCachedDevice3.getGroupId()).thenReturn(TEST_DEVICE_GROUP_ID2);
when(mCachedDevice3.getDevice()).thenReturn(mDevice3);
when(mCachedDevice3.getName()).thenReturn(TEST_DEVICE_NAME2);
when(mCacheManager.findDevice(mDevice1)).thenReturn(mCachedDevice1);
when(mCacheManager.findDevice(mDevice2)).thenReturn(mCachedDevice2);
when(mCacheManager.findDevice(mDevice3)).thenReturn(mCachedDevice3);
when(mBroadcast.isEnabled(any())).thenReturn(true);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(ImmutableList.of(mDevice1, mDevice2, mDevice3));
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mState));
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.getSummary().toString())
.isEqualTo(
mContext.getString(
R.string.audio_sharing_call_audio_description, TEST_DEVICE_NAME1));
}
@Test
public void displayPreference_noFallbackDeviceInSharing_showEmptySummary() {
Settings.Secure.putInt(mContentResolver, TEST_SETTINGS_KEY, TEST_DEVICE_GROUP_ID2);
when(mCachedDevice1.getGroupId()).thenReturn(TEST_DEVICE_GROUP_ID1);
when(mCachedDevice1.getDevice()).thenReturn(mDevice1);
when(mCachedDevice1.getName()).thenReturn(TEST_DEVICE_NAME1);
when(mCacheManager.findDevice(mDevice1)).thenReturn(mCachedDevice1);
when(mBroadcast.isEnabled(any())).thenReturn(true);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(ImmutableList.of(mDevice1));
when(mAssistant.getAllSources(any())).thenReturn(ImmutableList.of(mState));
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.getSummary().toString()).isEmpty();
}
@Test
public void displayPreference_noFallbackDevice_showEmptySummary() {
Settings.Secure.putInt(
mContentResolver, TEST_SETTINGS_KEY, BluetoothCsipSetCoordinator.GROUP_ID_INVALID);
when(mBroadcast.isEnabled(any())).thenReturn(true);
when(mAssistant.getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED}))
.thenReturn(ImmutableList.of());
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.getSummary().toString()).isEmpty();
}
}

View File

@@ -0,0 +1,247 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothStatusCodes;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Looper;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.bluetooth.Utils;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcast;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import com.android.settingslib.bluetooth.VolumeControlProfile;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.flags.Flags;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowBluetoothAdapter.class,
ShadowBluetoothUtils.class,
})
public class StreamSettingsCategoryControllerTest {
private static final String KEY = "audio_sharing_stream_settings_category";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Spy Context mContext = ApplicationProvider.getApplicationContext();
@Mock private LocalBluetoothManager mLocalBtManager;
@Mock private LocalBluetoothProfileManager mBtProfileManager;
@Mock private LocalBluetoothLeBroadcast mBroadcast;
@Mock private LocalBluetoothLeBroadcastAssistant mAssistant;
@Mock private VolumeControlProfile mVolumeControl;
@Mock private PreferenceScreen mScreen;
private StreamSettingsCategoryController mController;
private Lifecycle mLifecycle;
private LifecycleOwner mLifecycleOwner;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private LocalBluetoothManager mLocalBluetoothManager;
private Preference mPreference;
@Before
public void setUp() {
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
mShadowBluetoothAdapter.setIsLeAudioBroadcastSourceSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mShadowBluetoothAdapter.setIsLeAudioBroadcastAssistantSupported(
BluetoothStatusCodes.FEATURE_SUPPORTED);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBtManager;
mLocalBluetoothManager = Utils.getLocalBtManager(mContext);
when(mLocalBluetoothManager.getProfileManager()).thenReturn(mBtProfileManager);
when(mBtProfileManager.getLeAudioBroadcastProfile()).thenReturn(mBroadcast);
when(mBtProfileManager.getLeAudioBroadcastAssistantProfile()).thenReturn(mAssistant);
when(mBtProfileManager.getVolumeControlProfile()).thenReturn(mVolumeControl);
when(mBroadcast.isProfileReady()).thenReturn(true);
when(mAssistant.isProfileReady()).thenReturn(true);
when(mVolumeControl.isProfileReady()).thenReturn(true);
mController = new StreamSettingsCategoryController(mContext, KEY);
mPreference = new Preference(mContext);
when(mScreen.findPreference(KEY)).thenReturn(mPreference);
}
@Test
public void bluetoothOff_updateVisibility() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mContext.registerReceiver(
mController.mReceiver,
mController.mIntentFilter,
Context.RECEIVER_EXPORTED_UNAUDITED);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isTrue();
mShadowBluetoothAdapter.setEnabled(false);
Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
mContext.sendBroadcast(intent);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void getAvailabilityStatus_flagOn() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_flagOff() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void onStart_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mContext, times(0))
.registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class), anyInt());
verify(mBtProfileManager, times(0)).addServiceListener(mController);
}
@Test
public void onStart_flagOn_registerCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStart(mLifecycleOwner);
verify(mContext)
.registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class), anyInt());
verify(mBtProfileManager, times(0)).addServiceListener(mController);
}
@Test
public void onStart_flagOnProfileNotReady_registerProfileManagerCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isProfileReady()).thenReturn(false);
mController.onStart(mLifecycleOwner);
verify(mContext)
.registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class), anyInt());
verify(mBtProfileManager).addServiceListener(mController);
}
@Test
public void onStop_flagOff_doNothing() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mController.onStop(mLifecycleOwner);
verify(mContext, times(0)).unregisterReceiver(any(BroadcastReceiver.class));
verify(mBtProfileManager, times(0)).removeServiceListener(mController);
}
@Test
public void onStop_flagOn_unregisterCallback() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
doNothing().when(mContext).unregisterReceiver(any(BroadcastReceiver.class));
mController.onStop(mLifecycleOwner);
verify(mContext).unregisterReceiver(any(BroadcastReceiver.class));
verify(mBtProfileManager).removeServiceListener(mController);
}
@Test
public void displayPreference_flagOff_preferenceInvisible() {
mSetFlagsRule.disableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mPreference.setVisible(true);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void displayPreference_BluetoothOff_preferenceInvisible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mPreference.setVisible(true);
mShadowBluetoothAdapter.setEnabled(false);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void displayPreference_BluetoothOnProfileNotReady_preferenceInvisible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mPreference.setVisible(true);
when(mBroadcast.isProfileReady()).thenReturn(false);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void displayPreference_BluetoothOnProfileReady_preferenceVisible() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
mPreference.setVisible(false);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isTrue();
}
@Test
public void onServiceConnected_updateVisibility() {
mSetFlagsRule.enableFlags(Flags.FLAG_ENABLE_LE_AUDIO_SHARING);
when(mBroadcast.isProfileReady()).thenReturn(false);
mController.displayPreference(mScreen);
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isFalse();
when(mBroadcast.isProfileReady()).thenReturn(true);
mController.onServiceConnected();
shadowOf(Looper.getMainLooper()).idle();
assertThat(mPreference.isVisible()).isTrue();
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.AddSourceBadCodeState.AUDIO_STREAM_ADD_SOURCE_BAD_CODE_STATE_SUMMARY;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class AddSourceBadCodeStateTest {
private AddSourceBadCodeState mInstance;
@Before
public void setUp() {
mInstance = AddSourceBadCodeState.getInstance();
}
@Test
public void testGetInstance() {
assertThat(mInstance).isNotNull();
assertThat(mInstance).isInstanceOf(SyncedState.class);
}
@Test
public void testGetSummary() {
int summary = mInstance.getSummary();
assertThat(summary).isEqualTo(AUDIO_STREAM_ADD_SOURCE_BAD_CODE_STATE_SUMMARY);
}
@Test
public void testGetStateEnum() {
AudioStreamsProgressCategoryController.AudioStreamState stateEnum =
mInstance.getStateEnum();
assertThat(stateEnum)
.isEqualTo(
AudioStreamsProgressCategoryController.AudioStreamState
.ADD_SOURCE_BAD_CODE);
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.AddSourceFailedState.AUDIO_STREAM_ADD_SOURCE_FAILED_STATE_SUMMARY;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class AddSourceFailedStateTest {
private AddSourceFailedState mInstance;
@Before
public void setUp() {
mInstance = AddSourceFailedState.getInstance();
}
@Test
public void testGetInstance() {
assertThat(mInstance).isNotNull();
assertThat(mInstance).isInstanceOf(SyncedState.class);
}
@Test
public void testGetSummary() {
int summary = mInstance.getSummary();
assertThat(summary).isEqualTo(AUDIO_STREAM_ADD_SOURCE_FAILED_STATE_SUMMARY);
}
@Test
public void testGetStateEnum() {
AudioStreamsProgressCategoryController.AudioStreamState stateEnum =
mInstance.getStateEnum();
assertThat(stateEnum)
.isEqualTo(
AudioStreamsProgressCategoryController.AudioStreamState.ADD_SOURCE_FAILED);
}
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.AddSourceWaitForResponseState.ADD_SOURCE_WAIT_FOR_RESPONSE_TIMEOUT_MILLIS;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothLeBroadcastMetadata;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowLooper;
import java.util.concurrent.TimeUnit;
@RunWith(RobolectricTestRunner.class)
public class AddSourceWaitForResponseStateTest {
private static final int BROADCAST_ID = 1;
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock private AudioStreamPreference mMockPreference;
@Mock private AudioStreamsProgressCategoryController mMockController;
@Mock private AudioStreamsHelper mMockHelper;
@Mock private BluetoothLeBroadcastMetadata mMockMetadata;
private AddSourceWaitForResponseState mInstance;
@Before
public void setUp() {
mInstance = AddSourceWaitForResponseState.getInstance();
}
@Test
public void testGetInstance() {
assertThat(mInstance).isNotNull();
assertThat(mInstance).isInstanceOf(AudioStreamStateHandler.class);
}
@Test
public void testGetSummary() {
int summary = mInstance.getSummary();
assertThat(summary)
.isEqualTo(
AddSourceWaitForResponseState
.AUDIO_STREAM_ADD_SOURCE_WAIT_FOR_RESPONSE_STATE_SUMMARY);
}
@Test
public void testGetStateEnum() {
AudioStreamsProgressCategoryController.AudioStreamState stateEnum =
mInstance.getStateEnum();
assertThat(stateEnum)
.isEqualTo(
AudioStreamsProgressCategoryController.AudioStreamState
.ADD_SOURCE_WAIT_FOR_RESPONSE);
}
@Test
public void testPerformAction_metadataIsNull_doNothing() {
when(mMockPreference.getAudioStreamMetadata()).thenReturn(null);
mInstance.performAction(mMockPreference, mMockController, mMockHelper);
verify(mMockHelper, never()).addSource(any());
}
@Test
public void testPerformAction_metadataIsNotNull_addSource() {
when(mMockPreference.getAudioStreamMetadata()).thenReturn(mMockMetadata);
mInstance.performAction(mMockPreference, mMockController, mMockHelper);
verify(mMockHelper).addSource(mMockMetadata);
verify(mMockController, never()).handleSourceFailedToConnect(anyInt());
}
@Test
public void testPerformAction_timeout_addSource_sourceFailedToConnect() {
when(mMockPreference.getAudioStreamMetadata()).thenReturn(mMockMetadata);
when(mMockPreference.isShown()).thenReturn(true);
when(mMockPreference.getAudioStreamState()).thenReturn(mInstance.getStateEnum());
when(mMockPreference.getAudioStreamBroadcastId()).thenReturn(BROADCAST_ID);
mInstance.performAction(mMockPreference, mMockController, mMockHelper);
ShadowLooper.idleMainLooper(ADD_SOURCE_WAIT_FOR_RESPONSE_TIMEOUT_MILLIS, TimeUnit.SECONDS);
verify(mMockHelper).addSource(mMockMetadata);
verify(mMockController).handleSourceFailedToConnect(BROADCAST_ID);
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import android.content.Context;
import android.view.View;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settings.connecteddevice.audiosharing.audiostreams.testshadows.ShadowAudioStreamsHelper;
import com.android.settings.testutils.shadow.ShadowThreadUtils;
import com.android.settingslib.widget.ActionButtonsPreference;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowThreadUtils.class,
ShadowAudioStreamsHelper.class,
})
public class AudioStreamButtonControllerTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
private static final String KEY = "audio_stream_button";
private static final int BROADCAST_ID = 1;
@Spy Context mContext = ApplicationProvider.getApplicationContext();
@Mock private AudioStreamsHelper mAudioStreamsHelper;
@Mock private PreferenceScreen mScreen;
@Mock private BluetoothLeBroadcastReceiveState mBroadcastReceiveState;
@Mock private ActionButtonsPreference mPreference;
private AudioStreamButtonController mController;
@Before
public void setUp() {
ShadowAudioStreamsHelper.setUseMock(mAudioStreamsHelper);
mController = new AudioStreamButtonController(mContext, KEY);
mController.init(BROADCAST_ID);
when(mScreen.findPreference(KEY)).thenReturn(mPreference);
when(mPreference.getContext()).thenReturn(mContext);
when(mPreference.setButton1Text(anyInt())).thenReturn(mPreference);
when(mPreference.setButton1Icon(anyInt())).thenReturn(mPreference);
when(mPreference.setButton1Enabled(anyBoolean())).thenReturn(mPreference);
when(mPreference.setButton1OnClickListener(any(View.OnClickListener.class)))
.thenReturn(mPreference);
}
@Test
public void testDisplayPreference_sourceConnected_setDisconnectButton() {
when(mAudioStreamsHelper.getAllConnectedSources())
.thenReturn(List.of(mBroadcastReceiveState));
when(mBroadcastReceiveState.getBroadcastId()).thenReturn(BROADCAST_ID);
mController.displayPreference(mScreen);
verify(mPreference).setButton1Enabled(true);
verify(mPreference).setButton1Text(R.string.audio_streams_disconnect);
verify(mPreference).setButton1Icon(com.android.settings.R.drawable.ic_settings_close);
verify(mPreference).setButton1OnClickListener(any(View.OnClickListener.class));
}
@Test
public void testDisplayPreference_sourceNotConnected_setConnectButton() {
when(mAudioStreamsHelper.getAllConnectedSources()).thenReturn(Collections.emptyList());
mController.displayPreference(mScreen);
verify(mPreference).setButton1Enabled(true);
verify(mPreference).setButton1Text(R.string.audio_streams_connect);
verify(mPreference).setButton1Icon(com.android.settings.R.drawable.ic_add_24dp);
verify(mPreference).setButton1OnClickListener(any(View.OnClickListener.class));
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.AudioStreamHeaderController.AUDIO_STREAM_HEADER_LISTENING_NOW_SUMMARY;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.AudioStreamHeaderController.AUDIO_STREAM_HEADER_NOT_LISTENING_SUMMARY;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import android.content.Context;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.connecteddevice.audiosharing.audiostreams.testshadows.ShadowAudioStreamsHelper;
import com.android.settings.connecteddevice.audiosharing.audiostreams.testshadows.ShadowEntityHeaderController;
import com.android.settings.testutils.shadow.ShadowThreadUtils;
import com.android.settings.widget.EntityHeaderController;
import com.android.settingslib.widget.LayoutPreference;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Collections;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowEntityHeaderController.class,
ShadowThreadUtils.class,
ShadowAudioStreamsHelper.class,
})
public class AudioStreamHeaderControllerTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
private static final String KEY = "audio_stream_header";
private static final int BROADCAST_ID = 1;
private static final String BROADCAST_NAME = "broadcast name";
@Spy Context mContext = ApplicationProvider.getApplicationContext();
@Mock private AudioStreamsHelper mAudioStreamsHelper;
@Mock private PreferenceScreen mScreen;
@Mock private BluetoothLeBroadcastReceiveState mBroadcastReceiveState;
@Mock private AudioStreamDetailsFragment mFragment;
@Mock private LayoutPreference mPreference;
@Mock private EntityHeaderController mHeaderController;
private AudioStreamHeaderController mController;
@Before
public void setUp() {
ShadowEntityHeaderController.setUseMock(mHeaderController);
ShadowAudioStreamsHelper.setUseMock(mAudioStreamsHelper);
mController = new AudioStreamHeaderController(mContext, KEY);
mController.init(mFragment, BROADCAST_NAME, BROADCAST_ID);
when(mScreen.findPreference(KEY)).thenReturn(mPreference);
when(mScreen.getContext()).thenReturn(mContext);
when(mPreference.getContext()).thenReturn(mContext);
}
@Test
public void testDisplayPreference_sourceConnected_setSummary() {
when(mAudioStreamsHelper.getAllConnectedSources())
.thenReturn(List.of(mBroadcastReceiveState));
when(mBroadcastReceiveState.getBroadcastId()).thenReturn(BROADCAST_ID);
mController.displayPreference(mScreen);
verify(mHeaderController).setLabel(BROADCAST_NAME);
verify(mHeaderController)
.setSummary(mContext.getString(AUDIO_STREAM_HEADER_LISTENING_NOW_SUMMARY));
verify(mHeaderController).done(true);
}
@Test
public void testDisplayPreference_sourceNotConnected_setSummary() {
when(mAudioStreamsHelper.getAllConnectedSources()).thenReturn(Collections.emptyList());
mController.displayPreference(mScreen);
verify(mHeaderController).setLabel(BROADCAST_NAME);
verify(mHeaderController).setSummary(AUDIO_STREAM_HEADER_NOT_LISTENING_SUMMARY);
verify(mHeaderController).done(true);
}
}

View File

@@ -0,0 +1,134 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static org.mockito.Mockito.*;
import android.content.Context;
import android.media.session.MediaController;
import android.media.session.MediaSessionManager;
import android.media.session.PlaybackState;
import com.android.settings.connecteddevice.audiosharing.audiostreams.testshadows.ShadowAudioStreamsHelper;
import com.android.settings.connecteddevice.audiosharing.audiostreams.testshadows.ShadowLocalMediaManager;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.media.BluetoothMediaDevice;
import com.android.settingslib.media.LocalMediaManager;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowAudioStreamsHelper.class,
ShadowLocalMediaManager.class,
})
public class MediaControlHelperTest {
private static final String FAKE_PACKAGE = "fake_package";
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
private Context mContext;
@Mock private LocalBluetoothManager mLocalBluetoothManager;
@Mock private MediaSessionManager mMediaSessionManager;
@Mock private MediaController mMediaController;
@Mock private CachedBluetoothDevice mCachedBluetoothDevice;
@Mock private PlaybackState mPlaybackState;
@Mock private LocalMediaManager mLocalMediaManager;
@Mock private BluetoothMediaDevice mBluetoothMediaDevice;
@Before
public void setUp() {
mContext = spy(RuntimeEnvironment.application);
when(mContext.getSystemService(MediaSessionManager.class)).thenReturn(mMediaSessionManager);
when(mMediaSessionManager.getActiveSessions(any())).thenReturn(List.of(mMediaController));
when(mMediaController.getPackageName()).thenReturn(FAKE_PACKAGE);
when(mMediaController.getPlaybackState()).thenReturn(mPlaybackState);
ShadowAudioStreamsHelper.resetCachedBluetoothDevice();
ShadowLocalMediaManager.setUseMock(mLocalMediaManager);
}
@Test
public void testStart_noBluetoothManager_doNothing() {
MediaControlHelper helper = new MediaControlHelper(mContext, null);
helper.start();
verify(mLocalMediaManager, never()).startScan();
}
@Test
public void testStart_noConnectedDevice_doNothing() {
MediaControlHelper helper = new MediaControlHelper(mContext, mLocalBluetoothManager);
helper.start();
verify(mLocalMediaManager, never()).startScan();
}
@Test
public void testStart_isStopped_onDeviceListUpdate_shouldNotStopMedia() {
ShadowAudioStreamsHelper.setCachedBluetoothDeviceInSharingOrLeConnected(
mCachedBluetoothDevice);
when(mPlaybackState.getState()).thenReturn(PlaybackState.STATE_STOPPED);
when(mLocalMediaManager.getCurrentConnectedDevice()).thenReturn(null);
MediaControlHelper helper = new MediaControlHelper(mContext, mLocalBluetoothManager);
helper.start();
ShadowLocalMediaManager.onDeviceListUpdate();
verify(mMediaController, never()).getTransportControls();
}
@Test
public void testStart_isPlaying_onDeviceListUpdate_noDevice_shouldNotStopMedia() {
ShadowAudioStreamsHelper.setCachedBluetoothDeviceInSharingOrLeConnected(
mCachedBluetoothDevice);
when(mPlaybackState.getState()).thenReturn(PlaybackState.STATE_PLAYING);
when(mLocalMediaManager.getCurrentConnectedDevice()).thenReturn(null);
MediaControlHelper helper = new MediaControlHelper(mContext, mLocalBluetoothManager);
helper.start();
ShadowLocalMediaManager.onDeviceListUpdate();
verify(mMediaController, never()).getTransportControls();
}
@Test
public void testStart_isPlaying_onDeviceListUpdate_deviceMatch_shouldStopMedia() {
ShadowAudioStreamsHelper.setCachedBluetoothDeviceInSharingOrLeConnected(
mCachedBluetoothDevice);
when(mPlaybackState.getState()).thenReturn(PlaybackState.STATE_PLAYING);
when(mLocalMediaManager.getCurrentConnectedDevice()).thenReturn(mBluetoothMediaDevice);
when(mBluetoothMediaDevice.getCachedDevice()).thenReturn(mCachedBluetoothDevice);
MediaControlHelper helper = new MediaControlHelper(mContext, mLocalBluetoothManager);
helper.start();
ShadowLocalMediaManager.onDeviceListUpdate();
verify(mMediaController).getTransportControls();
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.SourceAddedState.AUDIO_STREAM_SOURCE_ADDED_STATE_SUMMARY;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class SourceAddedStateTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
private SourceAddedState mInstance;
@Before
public void setUp() {
mInstance = SourceAddedState.getInstance();
}
@Test
public void testGetInstance() {
assertThat(mInstance).isNotNull();
assertThat(mInstance).isInstanceOf(SourceAddedState.class);
}
@Test
public void testGetSummary() {
int summary = mInstance.getSummary();
assertThat(summary).isEqualTo(AUDIO_STREAM_SOURCE_ADDED_STATE_SUMMARY);
}
@Test
public void testGetStateEnum() {
AudioStreamsProgressCategoryController.AudioStreamState stateEnum =
mInstance.getStateEnum();
assertThat(stateEnum)
.isEqualTo(AudioStreamsProgressCategoryController.AudioStreamState.SOURCE_ADDED);
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.AudioStreamStateHandler.EMPTY_STRING_RES;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robolectric.shadows.ShadowLooper.shadowMainLooper;
import android.app.AlertDialog;
import android.bluetooth.BluetoothLeBroadcastMetadata;
import android.content.Context;
import androidx.preference.Preference;
import androidx.test.core.app.ApplicationProvider;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowAlertDialog;
@RunWith(RobolectricTestRunner.class)
@Config(
shadows = {
ShadowAlertDialog.class,
})
public class SyncedStateTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock private AudioStreamsProgressCategoryController mMockController;
@Mock private AudioStreamPreference mMockPreference;
@Mock private BluetoothLeBroadcastMetadata mMockMetadata;
private Context mMockContext;
private SyncedState mInstance;
@Before
public void setUp() {
ShadowAlertDialog.reset();
mMockContext = spy(ApplicationProvider.getApplicationContext());
mInstance = SyncedState.getInstance();
}
@Test
public void testGetInstance() {
assertThat(mInstance).isNotNull();
assertThat(mInstance).isInstanceOf(AudioStreamStateHandler.class);
}
@Test
public void testGetSummary() {
int summary = mInstance.getSummary();
assertThat(summary).isEqualTo(EMPTY_STRING_RES);
}
@Test
public void testGetStateEnum() {
AudioStreamsProgressCategoryController.AudioStreamState stateEnum =
mInstance.getStateEnum();
assertThat(stateEnum)
.isEqualTo(AudioStreamsProgressCategoryController.AudioStreamState.SYNCED);
}
@Test
public void testGetOnClickListener_isNotEncrypted_handleSourceAddRequest() {
Preference.OnPreferenceClickListener listener =
mInstance.getOnClickListener(mMockController);
when(mMockPreference.getAudioStreamMetadata()).thenReturn(mMockMetadata);
listener.onPreferenceClick(mMockPreference);
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialog.getLatestAlertDialog();
assertThat(dialog).isNull();
verify(mMockController).handleSourceAddRequest(mMockPreference, mMockMetadata);
}
@Test
public void testGetOnClickListener_isEncrypted_passwordDialogShowing() {
Preference.OnPreferenceClickListener listener =
mInstance.getOnClickListener(mMockController);
when(mMockPreference.getAudioStreamMetadata()).thenReturn(mMockMetadata);
when(mMockPreference.getContext()).thenReturn(mMockContext);
when(mMockMetadata.isEncrypted()).thenReturn(true);
listener.onPreferenceClick(mMockPreference);
shadowMainLooper().idle();
AlertDialog dialog = ShadowAlertDialog.getLatestAlertDialog();
assertThat(dialog).isNotNull();
assertThat(dialog.isShowing()).isTrue();
verify(mMockController, never()).handleSourceAddRequest(mMockPreference, mMockMetadata);
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.WaitForSyncState.AUDIO_STREAM_WAIT_FOR_SYNC_STATE_SUMMARY;
import static com.android.settings.connecteddevice.audiosharing.audiostreams.WaitForSyncState.WAIT_FOR_SYNC_TIMEOUT_MILLIS;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothLeBroadcastMetadata;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowLooper;
import java.util.concurrent.TimeUnit;
@RunWith(RobolectricTestRunner.class)
public class WaitForSyncStateTest {
@Rule public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock private AudioStreamPreference mMockPreference;
@Mock private AudioStreamsProgressCategoryController mMockController;
@Mock private AudioStreamsHelper mMockHelper;
@Mock private BluetoothLeBroadcastMetadata mMockMetadata;
private WaitForSyncState mInstance;
@Before
public void setUp() {
mInstance = WaitForSyncState.getInstance();
}
@Test
public void testGetInstance() {
assertThat(mInstance).isNotNull();
assertThat(mInstance).isInstanceOf(AudioStreamStateHandler.class);
}
@Test
public void testGetSummary() {
int summary = mInstance.getSummary();
assertThat(summary).isEqualTo(AUDIO_STREAM_WAIT_FOR_SYNC_STATE_SUMMARY);
}
@Test
public void testGetStateEnum() {
AudioStreamsProgressCategoryController.AudioStreamState stateEnum =
mInstance.getStateEnum();
assertThat(stateEnum)
.isEqualTo(AudioStreamsProgressCategoryController.AudioStreamState.WAIT_FOR_SYNC);
}
@Test
public void testPerformAction_timeout_stateNotMatching_doNothing() {
when(mMockPreference.isShown()).thenReturn(true);
when(mMockPreference.getAudioStreamState())
.thenReturn(AudioStreamsProgressCategoryController.AudioStreamState.UNKNOWN);
mInstance.performAction(mMockPreference, mMockController, mMockHelper);
ShadowLooper.idleMainLooper(WAIT_FOR_SYNC_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
verify(mMockController, never()).handleSourceLost(anyInt());
}
@Test
public void testPerformAction_timeout_stateMatching_sourceLost() {
when(mMockPreference.isShown()).thenReturn(true);
when(mMockPreference.getAudioStreamState())
.thenReturn(AudioStreamsProgressCategoryController.AudioStreamState.WAIT_FOR_SYNC);
when(mMockPreference.getAudioStreamBroadcastId()).thenReturn(1);
when(mMockPreference.getAudioStreamMetadata()).thenReturn(mMockMetadata);
mInstance.performAction(mMockPreference, mMockController, mMockHelper);
ShadowLooper.idleMainLooper(WAIT_FOR_SYNC_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
verify(mMockController).handleSourceLost(1);
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams.testshadows;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import com.android.settings.connecteddevice.audiosharing.audiostreams.AudioStreamsHelper;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import java.util.List;
import java.util.Optional;
@Implements(value = AudioStreamsHelper.class, callThroughByDefault = false)
public class ShadowAudioStreamsHelper {
private static AudioStreamsHelper sMockHelper;
private static Optional<CachedBluetoothDevice> sCachedBluetoothDevice;
public static void setUseMock(AudioStreamsHelper mockAudioStreamsHelper) {
sMockHelper = mockAudioStreamsHelper;
}
/** Resets {@link CachedBluetoothDevice} */
public static void resetCachedBluetoothDevice() {
sCachedBluetoothDevice = Optional.empty();
}
public static void setCachedBluetoothDeviceInSharingOrLeConnected(
CachedBluetoothDevice cachedBluetoothDevice) {
sCachedBluetoothDevice = Optional.of(cachedBluetoothDevice);
}
@Implementation
public List<BluetoothLeBroadcastReceiveState> getAllConnectedSources() {
return sMockHelper.getAllConnectedSources();
}
/** Gets {@link CachedBluetoothDevice} in sharing or le connected */
@Implementation
public static Optional<CachedBluetoothDevice> getCachedBluetoothDeviceInSharingOrLeConnected(
LocalBluetoothManager manager) {
return sCachedBluetoothDevice;
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams.testshadows;
import android.app.Activity;
import android.view.View;
import androidx.fragment.app.Fragment;
import com.android.settings.widget.EntityHeaderController;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
@Implements(value = EntityHeaderController.class, callThroughByDefault = false)
public class ShadowEntityHeaderController {
private static EntityHeaderController sMockController;
public static void setUseMock(EntityHeaderController mockController) {
sMockController = mockController;
}
/** Returns new instance of {@link EntityHeaderController} */
@Implementation
public static EntityHeaderController newInstance(
Activity activity, Fragment fragment, View header) {
return sMockController;
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.connecteddevice.audiosharing.audiostreams.testshadows;
import com.android.settingslib.media.LocalMediaManager;
import com.android.settingslib.media.MediaDevice;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import java.util.Collections;
@Implements(value = LocalMediaManager.class, callThroughByDefault = false)
public class ShadowLocalMediaManager {
private static LocalMediaManager sMockManager;
private static LocalMediaManager.DeviceCallback sDeviceCallback;
public static void setUseMock(LocalMediaManager mockLocalMediaManager) {
sMockManager = mockLocalMediaManager;
}
/** Triggers onDeviceListUpdate of {@link LocalMediaManager.DeviceCallback} */
public static void onDeviceListUpdate() {
sDeviceCallback.onDeviceListUpdate(Collections.emptyList());
}
/** Starts scan */
@Implementation
public void startScan() {
sMockManager.startScan();
}
/** Registers {@link LocalMediaManager.DeviceCallback} */
@Implementation
public void registerCallback(LocalMediaManager.DeviceCallback deviceCallback) {
sMockManager.registerCallback(deviceCallback);
sDeviceCallback = deviceCallback;
}
@Implementation
public MediaDevice getCurrentConnectedDevice() {
return sMockManager.getCurrentConnectedDevice();
}
}