Merge tm-qpr-dev-plus-aosp-without-vendor@9129937

Bug: 248070379
Merged-In: I9ebe26c6a8058798ea654523ad1405a8447268b8
Change-Id: Ib8c6441f2165784804a1863bcfce6b05d20ecfd3
This commit is contained in:
Xin Li
2022-10-06 12:22:57 -07:00
525 changed files with 28375 additions and 16966 deletions

View File

@@ -118,18 +118,29 @@ public class AccessibilityQuickSettingsPrimarySwitchPreferenceControllerTest {
mController = new TestAccessibilityQuickSettingsPrimarySwitchPreferenceController(mContext,
TEST_KEY);
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
mController.displayPreference(mScreen);
}
@Test
public void setChecked_showTooltipView() {
mController.displayPreference(mScreen);
mController.setChecked(true);
assertThat(getLatestPopupWindow().isShowing()).isTrue();
}
@Test
public void setChecked_notCallDisplayPreference_notShowTooltipView() {
// Simulates the slice highlight menu that does not call {@link #displayPreference} before
// {@link #setChecked} called.
mController.setChecked(true);
assertThat(getLatestPopupWindow()).isNull();
}
@Test
public void setChecked_tooltipViewShown_notShowTooltipView() {
mController.displayPreference(mScreen);
mController.setChecked(true);
getLatestPopupWindow().dismiss();
mController.setChecked(false);
@@ -142,6 +153,7 @@ public class AccessibilityQuickSettingsPrimarySwitchPreferenceControllerTest {
@Test
@Config(shadows = ShadowFragment.class)
public void restoreValueFromSavedInstanceState_showTooltipView() {
mController.displayPreference(mScreen);
mController.setChecked(true);
final Bundle savedInstanceState = new Bundle();
savedInstanceState.putBoolean(KEY_SAVED_QS_TOOLTIP_RESHOW, /* value= */ true);

View File

@@ -45,7 +45,7 @@ import androidx.preference.PreferenceScreen;
import com.android.settings.AccessiblePreferenceCategory;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
import com.android.settings.testutils.shadow.ShadowAccountManager;
import com.android.settings.testutils.shadow.ShadowContentResolver;
@@ -77,7 +77,7 @@ public class AccountPreferenceControllerTest {
@Mock(answer = RETURNS_DEEP_STUBS)
private UserManager mUserManager;
@Mock(answer = RETURNS_DEEP_STUBS)
private SettingsPreferenceFragment mFragment;
private DashboardFragment mFragment;
@Mock(answer = RETURNS_DEEP_STUBS)
private AccountManager mAccountManager;
@Mock(answer = RETURNS_DEEP_STUBS)

View File

@@ -40,8 +40,8 @@ import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settings.SettingsActivity;
import com.android.settings.fuelgauge.BatteryDiffEntry;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.batteryusage.BatteryDiffEntry;
import com.android.settingslib.applications.ApplicationsState;
import org.junit.Before;
@@ -162,7 +162,8 @@ public class AppBatteryPreferenceControllerTest {
mController.updateBatteryWithDiffEntry();
assertThat(mBatteryPreference.getSummary()).isEqualTo("No battery use for past 24 hours");
assertThat(mBatteryPreference.getSummary().toString()).isEqualTo(
"No battery use since last full charge");
}
@Test
@@ -175,7 +176,8 @@ public class AppBatteryPreferenceControllerTest {
mController.updateBatteryWithDiffEntry();
assertThat(mBatteryPreference.getSummary()).isEqualTo("60% use for past 24 hours");
assertThat(mBatteryPreference.getSummary().toString()).isEqualTo(
"60% use since last full charge");
}
@Test

View File

@@ -16,26 +16,48 @@
package com.android.settings.biometrics.fingerprint;
import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_POWER_BUTTON;
import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_UDFPS_OPTICAL;
import static com.android.settings.biometrics.fingerprint.FingerprintEnrollEnrolling.KEY_STATE_PREVIOUS_ROTATION;
import static com.android.settings.biometrics.fingerprint.FingerprintEnrollEnrolling.SFPS_STAGE_NO_ANIMATION;
import static com.android.settings.biometrics.fingerprint.FingerprintEnrollEnrolling.SFPS_STAGE_RIGHT_EDGE;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never;
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 android.content.Intent;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.hardware.biometrics.ComponentInfoInternal;
import android.hardware.biometrics.SensorProperties;
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.EnrollmentCallback;
import android.hardware.fingerprint.FingerprintSensorProperties;
import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Vibrator;
import android.view.Display;
import android.view.Surface;
import android.widget.TextView;
import com.android.settings.R;
import com.android.settings.password.ChooseLockSettingsHelper;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowUtils;
import com.android.settings.widget.RingProgressBar;
import com.airbnb.lottie.LottieAnimationView;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -43,36 +65,38 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowUtils.class)
public class FingerprintEnrollEnrollingTest {
@Mock
private FingerprintManager mFingerprintManager;
@Mock private FingerprintManager mFingerprintManager;
@Mock private Vibrator mVibrator;
@Mock private LottieAnimationView mIllustrationLottie;
@Mock private FingerprintEnrollSidecar mSidecar;
@Mock private Display mMockDisplay;
private Resources.Theme mTheme;
private final int[] mSfpsStageThresholds = new int[]{0, 9, 13, 19, 25};
private FingerprintEnrollEnrolling mActivity;
private Context mContext;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ShadowUtils.setFingerprintManager(mFingerprintManager);
FakeFeatureFactory.setupForTest();
mActivity = Robolectric.buildActivity(
FingerprintEnrollEnrolling.class,
new Intent()
// Set the challenge token so the confirm screen will not be shown
.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE_TOKEN, new byte[0]))
.setup().get();
}
@After
public void tearDown() {
ShadowUtils.reset();
}
@Test
@@ -82,23 +106,207 @@ public class FingerprintEnrollEnrollingTest {
enrollmentCallback.onEnrollmentProgress(123);
enrollmentCallback.onEnrollmentHelp(
FingerprintManager.FINGERPRINT_ERROR_UNABLE_TO_PROCESS,
"test enrollment help");
FingerprintManager.FINGERPRINT_ERROR_UNABLE_TO_PROCESS, "test enrollment help");
TextView errorText = mActivity.findViewById(R.id.error_text);
assertThat(errorText.getText()).isEqualTo("test enrollment help");
}
@Test
public void fingerprintUdfpsEnrollSuccessProgress_shouldNotVibrate() {
initializeActivityFor(TYPE_UDFPS_OPTICAL);
mActivity.onEnrollmentProgressChange(1, 1);
verify(mVibrator, never()).vibrate(anyInt(), anyString(), any(), anyString(), any());
}
@Test
public void fingerprintRearEnrollSuccessProgress_shouldNotVibrate() {
initializeActivityFor(FingerprintSensorProperties.TYPE_REAR);
mActivity.onEnrollmentProgressChange(1, 1);
verify(mVibrator, never()).vibrate(anyInt(), anyString(), any(), anyString(), any());
}
@Test
public void fingerprintUdfpsOverlayEnrollment_gainFocus_shouldNotCancel() {
initializeActivityFor(TYPE_UDFPS_OPTICAL);
mActivity.onEnrollmentProgressChange(1, 1);
mActivity.onWindowFocusChanged(true);
verify(mActivity, never()).onCancelEnrollment(anyInt());
}
@Test
public void fingerprintUdfpsOverlayEnrollment_loseFocus_shouldCancel() {
initializeActivityFor(TYPE_UDFPS_OPTICAL);
mActivity.onEnrollmentProgressChange(1, 1);
mActivity.onWindowFocusChanged(false);
verify(mActivity, never()).onCancelEnrollment(anyInt());
}
@Test
public void fingerprintSfpsEnroll_PlaysAllAnimationsAssetsCorrectly() {
initializeActivityFor(TYPE_POWER_BUTTON);
int totalEnrollSteps = 25;
int initStageSteps = -1, initStageRemaining = 0;
when(mSidecar.getEnrollmentSteps()).thenReturn(initStageSteps);
when(mSidecar.getEnrollmentRemaining()).thenReturn(initStageRemaining);
mActivity.onEnrollmentProgressChange(initStageSteps, initStageRemaining);
when(mSidecar.getEnrollmentSteps()).thenReturn(totalEnrollSteps);
for (int remaining = totalEnrollSteps; remaining > 0; remaining--) {
when(mSidecar.getEnrollmentRemaining()).thenReturn(remaining);
mActivity.onEnrollmentProgressChange(totalEnrollSteps, remaining);
}
List<Integer> expectedLottieAssetOrder = List.of(
R.raw.sfps_lottie_no_animation,
R.raw.sfps_lottie_pad_center,
R.raw.sfps_lottie_tip,
R.raw.sfps_lottie_left_edge,
R.raw.sfps_lottie_right_edge
);
ArgumentCaptor<Integer> lottieAssetCaptor = ArgumentCaptor.forClass(Integer.class);
verify(mIllustrationLottie, times(5)).setAnimation(lottieAssetCaptor.capture());
List<Integer> observedLottieAssetOrder = lottieAssetCaptor.getAllValues();
assertThat(observedLottieAssetOrder).isEqualTo(expectedLottieAssetOrder);
}
// SFPS_STAGE_CENTER is first stage with progress bar colors, starts at steps=25, remaining=25
private void configureSfpsStageColorTest() {
when(mSidecar.getEnrollmentSteps()).thenReturn(25);
when(mSidecar.getEnrollmentRemaining()).thenReturn(25);
mActivity.onEnrollmentProgressChange(25, 25);
}
@Test
public void fingerprintSfpsEnroll_usesCorrectProgressBarFillColor() {
initializeActivityFor(TYPE_POWER_BUTTON);
configureSfpsStageColorTest();
int progress_bar_fill_color = mActivity.getApplicationContext().getColor(
R.color.sfps_enrollment_progress_bar_fill_color
);
RingProgressBar mProgressBar = mActivity.findViewById(R.id.fingerprint_progress_bar);
assertThat(mProgressBar.getProgressTintList()).isEqualTo(
ColorStateList.valueOf(progress_bar_fill_color)
);
}
@Test
public void fingerprintSfpsEnroll_usesCorrectProgressBarHelpColor() {
initializeActivityFor(TYPE_POWER_BUTTON);
configureSfpsStageColorTest();
int progress_bar_error_color = mActivity.getApplicationContext().getColor(
R.color.sfps_enrollment_progress_bar_error_color
);
mActivity.onEnrollmentHelp(
FingerprintManager.FINGERPRINT_ERROR_UNABLE_TO_PROCESS,
"test enrollment help"
);
RingProgressBar mProgressBar = mActivity.findViewById(R.id.fingerprint_progress_bar);
assertThat(mProgressBar.getProgressTintList()).isEqualTo(
ColorStateList.valueOf(progress_bar_error_color)
);
}
@Test
public void fingerprintSfpsEnrollment_loseFocus_shouldNotCancel() {
initializeActivityFor(FingerprintSensorProperties.TYPE_POWER_BUTTON);
mActivity.onEnrollmentProgressChange(1, 1);
mActivity.onWindowFocusChanged(true);
verify(mActivity, never()).onCancelEnrollment(anyInt());
}
@Test
public void fingerprintUdfpsEnroll_activityApplyDarkLightStyle() {
initializeActivityFor(TYPE_UDFPS_OPTICAL);
mActivity.onApplyThemeResource(mTheme, R.style.GlifTheme, true /* first */);
final String appliedThemes = mTheme.toString();
assertThat(appliedThemes.contains("SetupWizardPartnerResource")).isTrue();
}
@Test
public void fingerprintSfpsEnroll_activityApplyDarkLightStyle() {
initializeActivityFor(TYPE_POWER_BUTTON);
mActivity.onApplyThemeResource(mTheme, R.style.GlifTheme, true /* first */);
final String appliedThemes = mTheme.toString();
assertThat(appliedThemes.contains("SetupWizardPartnerResource")).isTrue();
}
private void initializeActivityFor(int sensorType) {
final List<ComponentInfoInternal> componentInfo = new ArrayList<>();
final FingerprintSensorPropertiesInternal prop =
new FingerprintSensorPropertiesInternal(
0 /* sensorId */,
SensorProperties.STRENGTH_STRONG,
1 /* maxEnrollmentsPerUser */,
componentInfo,
sensorType,
true /* resetLockoutRequiresHardwareAuthToken */);
final ArrayList<FingerprintSensorPropertiesInternal> props = new ArrayList<>();
final Bundle savedInstanceState = new Bundle();
savedInstanceState.putInt(KEY_STATE_PREVIOUS_ROTATION, Surface.ROTATION_90);
props.add(prop);
when(mFingerprintManager.getSensorPropertiesInternal()).thenReturn(props);
mContext = spy(RuntimeEnvironment.application);
mActivity = spy(FingerprintEnrollEnrolling.class);
when(mFingerprintManager.getSensorPropertiesInternal()).thenReturn(props);
when(mContext.getDisplay()).thenReturn(mMockDisplay);
when(mMockDisplay.getRotation()).thenReturn(Surface.ROTATION_0);
doReturn(true).when(mActivity).shouldShowLottie();
doReturn(mFingerprintManager).when(mActivity).getSystemService(FingerprintManager.class);
doReturn(mVibrator).when(mActivity).getSystemService(Vibrator.class);
doReturn(mIllustrationLottie).when(mActivity).findViewById(R.id.illustration_lottie);
ReflectionHelpers.setField(mActivity, "mSidecar", mSidecar);
if (sensorType == TYPE_POWER_BUTTON) {
// SFPS_STAGE_NO_ANIMATION = 0, ... , SFPS_STAGE_RIGHT_EDGE = 4
for (int stage = SFPS_STAGE_NO_ANIMATION; stage <= SFPS_STAGE_RIGHT_EDGE; stage++) {
doReturn(mSfpsStageThresholds[stage]).when(mActivity).getStageThresholdSteps(stage);
}
doReturn(true).when(mSidecar).isEnrolling();
}
ActivityController.of(mActivity).create(savedInstanceState);
mTheme = mActivity.getTheme();
}
private EnrollmentCallback verifyAndCaptureEnrollmentCallback() {
ArgumentCaptor<EnrollmentCallback> callbackCaptor =
ArgumentCaptor.forClass(EnrollmentCallback.class);
verify(mFingerprintManager).enroll(
any(byte[].class),
any(CancellationSignal.class),
anyInt(),
callbackCaptor.capture(),
eq(FingerprintManager.ENROLL_ENROLL));
verify(mFingerprintManager)
.enroll(
any(byte[].class),
any(CancellationSignal.class),
anyInt(),
callbackCaptor.capture(),
eq(FingerprintManager.ENROLL_ENROLL));
return callbackCaptor.getValue();
}
}
}

View File

@@ -16,21 +16,41 @@
package com.android.settings.biometrics.fingerprint;
import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_POWER_BUTTON;
import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_REAR;
import static android.hardware.fingerprint.FingerprintSensorProperties.TYPE_UDFPS_OPTICAL;
import static com.android.settings.biometrics.BiometricEnrollBase.RESULT_FINISHED;
import static com.android.settings.biometrics.BiometricEnrollBase.RESULT_SKIP;
import static com.android.settings.biometrics.BiometricEnrollBase.RESULT_TIMEOUT;
import static com.android.settings.biometrics.fingerprint.FingerprintEnrollEnrolling.TAG_SIDECAR;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.verify;
import static org.robolectric.RuntimeEnvironment.application;
import android.annotation.NonNull;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.Resources;
import android.hardware.biometrics.ComponentInfoInternal;
import android.hardware.biometrics.SensorProperties;
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.EnrollmentCallback;
import android.hardware.fingerprint.FingerprintSensorProperties;
import android.hardware.fingerprint.FingerprintSensorPropertiesInternal;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.view.View;
import androidx.fragment.app.Fragment;
import com.android.settings.R;
import com.android.settings.biometrics.BiometricEnrollBase;
@@ -40,6 +60,8 @@ import com.android.settings.testutils.shadow.ShadowUtils;
import com.google.android.setupcompat.PartnerCustomizationLayout;
import com.google.android.setupcompat.template.FooterBarMixin;
import com.google.android.setupcompat.template.FooterButton;
import com.google.android.setupdesign.GlifLayout;
import org.junit.After;
import org.junit.Before;
@@ -51,31 +73,80 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.Shadows;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity;
import org.robolectric.shadows.ShadowActivity.IntentForResult;
import java.util.ArrayList;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowUtils.class)
public class FingerprintEnrollFindSensorTest {
private static final int DEFAULT_ACTIVITY_RESULT = Activity.RESULT_CANCELED;
@Mock
private FingerprintManager mFingerprintManager;
private Resources.Theme mTheme;
private ActivityController<FingerprintEnrollFindSensor> mActivityController;
private FingerprintEnrollFindSensor mActivity;
private void buildActivity() {
mActivityController = Robolectric.buildActivity(
FingerprintEnrollFindSensor.class,
new Intent()
// Set the challenge token so the confirm screen will not be shown
.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE_TOKEN, new byte[0])
);
mActivity = mActivityController.get();
mTheme = mActivity.getTheme();
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ShadowUtils.setFingerprintManager(mFingerprintManager);
FakeFeatureFactory.setupForTest();
buildActivity();
}
mActivity = Robolectric.buildActivity(
FingerprintEnrollFindSensor.class,
new Intent()
// Set the challenge token so the confirm screen will not be shown
.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE_TOKEN, new byte[0]))
.setup().get();
private void setupActivity_onRearDevice() {
final ArrayList<FingerprintSensorPropertiesInternal> props = new ArrayList<>();
props.add(newFingerprintSensorPropertiesInternal(TYPE_REAR));
doReturn(props).when(mFingerprintManager).getSensorPropertiesInternal();
mActivityController.setup();
}
private void setupActivity_onUdfpsDevice() {
final ArrayList<FingerprintSensorPropertiesInternal> props = new ArrayList<>();
props.add(newFingerprintSensorPropertiesInternal(TYPE_UDFPS_OPTICAL));
doReturn(props).when(mFingerprintManager).getSensorPropertiesInternal();
mActivityController.setup();
}
private void setupActivity_onSfpsDevice() {
final ArrayList<FingerprintSensorPropertiesInternal> props = new ArrayList<>();
props.add(newFingerprintSensorPropertiesInternal(TYPE_POWER_BUTTON));
doReturn(props).when(mFingerprintManager).getSensorPropertiesInternal();
mActivityController.setup();
}
private FingerprintSensorPropertiesInternal newFingerprintSensorPropertiesInternal(
@FingerprintSensorProperties.SensorType int sensorType) {
return new FingerprintSensorPropertiesInternal(
0 /* sensorId */,
SensorProperties.STRENGTH_STRONG,
1 /* maxEnrollmentsPerUser */,
new ArrayList<ComponentInfoInternal>(),
sensorType,
true /* resetLockoutRequiresHardwareAuthToken */);
}
@After
@@ -83,13 +154,7 @@ public class FingerprintEnrollFindSensorTest {
ShadowUtils.reset();
}
@Test
public void enrollFingerprint_shouldProceed() {
EnrollmentCallback enrollmentCallback = verifyAndCaptureEnrollmentCallback();
enrollmentCallback.onEnrollmentProgress(123);
enrollmentCallback.onEnrollmentError(FingerprintManager.FINGERPRINT_ERROR_CANCELED, "test");
private void verifyStartEnrollingActivity() {
ShadowActivity shadowActivity = Shadows.shadowOf(mActivity);
IntentForResult startedActivity =
shadowActivity.getNextStartedActivityForResult();
@@ -100,6 +165,7 @@ public class FingerprintEnrollFindSensorTest {
@Test
public void enrollFingerprintTwice_shouldStartOneEnrolling() {
setupActivity_onRearDevice();
EnrollmentCallback enrollmentCallback = verifyAndCaptureEnrollmentCallback();
enrollmentCallback.onEnrollmentProgress(123);
@@ -123,6 +189,8 @@ public class FingerprintEnrollFindSensorTest {
@Config(qualifiers = "mcc999")
@Test
public void layoutWithoutAnimation_shouldNotCrash() {
setupActivity_onRearDevice();
EnrollmentCallback enrollmentCallback = verifyAndCaptureEnrollmentCallback();
enrollmentCallback.onEnrollmentProgress(123);
enrollmentCallback.onEnrollmentError(FingerprintManager.FINGERPRINT_ERROR_CANCELED, "test");
@@ -137,12 +205,14 @@ public class FingerprintEnrollFindSensorTest {
@Test
public void clickSkip_shouldReturnResultSkip() {
setupActivity_onRearDevice();
PartnerCustomizationLayout layout = mActivity.findViewById(R.id.setup_wizard_layout);
layout.getMixin(FooterBarMixin.class).getSecondaryButtonView().performClick();
ShadowActivity shadowActivity = Shadows.shadowOf(mActivity);
assertWithMessage("result code").that(shadowActivity.getResultCode())
.isEqualTo(BiometricEnrollBase.RESULT_SKIP);
.isEqualTo(RESULT_SKIP);
}
private EnrollmentCallback verifyAndCaptureEnrollmentCallback() {
@@ -160,9 +230,415 @@ public class FingerprintEnrollFindSensorTest {
@Test
public void onActivityResult_withNullIntentShouldNotCrash() {
setupActivity_onRearDevice();
// this should not crash
mActivity.onActivityResult(BiometricEnrollBase.CONFIRM_REQUEST, Activity.RESULT_OK,
null);
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(Activity.RESULT_CANCELED);
}
@Test
public void resultFinishShallForward_onRearDevice() {
setupActivity_onRearDevice();
triggerEnrollProgressAndError_onRearDevice();
verifyStartEnrollingActivity();
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_FINISHED);
}
@Test
public void resultFinishShallForward_onRearDevice_recreate() {
setupActivity_onRearDevice();
triggerEnrollProgressAndError_onRearDevice();
verifyStartEnrollingActivity();
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_FINISHED, bundle);
}
@Test
public void resultSkipShallForward_onRearDevice() {
setupActivity_onRearDevice();
verifySidecar_onRearOrSfpsDevice();
triggerEnrollProgressAndError_onRearDevice();
verifyStartEnrollingActivity();
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_SKIP);
}
@Test
public void resultSkipShallForward_onRearDevice_recreate() {
setupActivity_onRearDevice();
verifySidecar_onRearOrSfpsDevice();
triggerEnrollProgressAndError_onRearDevice();
verifyStartEnrollingActivity();
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_SKIP, bundle);
}
@Test
public void resultTimeoutShallForward_onRearDevice() {
setupActivity_onRearDevice();
verifySidecar_onRearOrSfpsDevice();
triggerEnrollProgressAndError_onRearDevice();
verifyStartEnrollingActivity();
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_TIMEOUT);
}
@Test
public void resultTimeoutShallForward_onRearDevice_recreate() {
setupActivity_onRearDevice();
verifySidecar_onRearOrSfpsDevice();
triggerEnrollProgressAndError_onRearDevice();
verifyStartEnrollingActivity();
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_TIMEOUT, bundle);
}
@Test
public void clickLottieResultFinishShallForward_onUdfpsDevice() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickLottieView_onUdfpsDevice();
verifyStartEnrollingActivity();
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_FINISHED);
}
@Test
public void clickLottieResultFinishShallForward_onUdfpsDevice_ifActivityRecycled() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickLottieView_onUdfpsDevice();
verifyStartEnrollingActivity();
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_FINISHED, bundle);
}
@Test
public void clickLottieResultSkipShallForward_onUdfpsDevice() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickLottieView_onUdfpsDevice();
verifyStartEnrollingActivity();
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_SKIP);
}
@Test
public void clickLottieResultSkipShallForward_onUdfpsDevice_ifActivityRecycled() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickLottieView_onUdfpsDevice();
verifyStartEnrollingActivity();
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_SKIP, bundle);
}
@Test
public void clickLottieResultTimeoutShallForward_onUdfpsDevice() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickLottieView_onUdfpsDevice();
verifyStartEnrollingActivity();
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_TIMEOUT);
}
@Test
public void clickLottieResultTimeoutShallForward_onUdfpsDevice_ifActivityRecycled() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickLottieView_onUdfpsDevice();
verifyStartEnrollingActivity();
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_TIMEOUT, bundle);
}
@Test
public void clickPrimiaryButtonResultFinishShallForward_onUdfpsDevice() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickPrimaryButton_onUdfpsDevice();
verifyStartEnrollingActivity();
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_FINISHED);
}
@Test
public void clickPrimiaryButtonResultFinishShallForward_onUdfpsDevice_ifActivityRecycled() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickPrimaryButton_onUdfpsDevice();
verifyStartEnrollingActivity();
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_FINISHED, bundle);
}
@Test
public void clickPrimiaryButtonResultSkipShallForward_onUdfpsDevice() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickPrimaryButton_onUdfpsDevice();
verifyStartEnrollingActivity();
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_SKIP);
}
@Test
public void clickPrimaryButtonResultSkipShallForward_onUdfpsDevice_ifActivityRecycled() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickPrimaryButton_onUdfpsDevice();
verifyStartEnrollingActivity();
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_SKIP, bundle);
}
@Test
public void clickPrimaryButtonResultTimeoutShallForward_onUdfpsDevice() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickPrimaryButton_onUdfpsDevice();
verifyStartEnrollingActivity();
// pause activity
mActivityController.pause().stop();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_resumeActivityAndVerifyResultThenForward(RESULT_TIMEOUT);
}
@Test
public void clickPrimaryButtonResultTimeoutShallForward_onUdfpsDevice_ifActivityRecycled() {
setupActivity_onUdfpsDevice();
verifyNoSidecar();
clickPrimaryButton_onUdfpsDevice();
verifyStartEnrollingActivity();
// recycle activity
final Bundle bundle = new Bundle();
mActivityController.pause().stop().saveInstanceState(bundle).destroy();
// onStop shall not change default activity result
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(DEFAULT_ACTIVITY_RESULT);
gotEnrollingResult_recreateActivityAndVerifyResultThenForward(RESULT_TIMEOUT, bundle);
}
@Test
public void fingerprintEnrollFindSensor_activityApplyDarkLightStyle() {
setupActivity_onSfpsDevice();
verifySidecar_onRearOrSfpsDevice();
mActivity.onApplyThemeResource(mTheme, R.style.GlifTheme, true /* first */);
final String appliedThemes = mTheme.toString();
assertThat(appliedThemes.contains("SetupWizardPartnerResource")).isTrue();
}
private void triggerEnrollProgressAndError_onRearDevice() {
EnrollmentCallback enrollmentCallback = verifyAndCaptureEnrollmentCallback();
enrollmentCallback.onEnrollmentProgress(123);
enrollmentCallback.onEnrollmentError(FingerprintManager.FINGERPRINT_ERROR_CANCELED, "test");
}
private void clickPrimaryButton_onUdfpsDevice() {
final FooterBarMixin footerBarMixin =
((GlifLayout) mActivity.findViewById(R.id.setup_wizard_layout))
.getMixin(FooterBarMixin.class);
final FooterButton primaryButton = footerBarMixin.getPrimaryButton();
assertThat(primaryButton).isNotNull();
assertThat(primaryButton.getVisibility()).isEqualTo(View.VISIBLE);
primaryButton.onClick(null);
}
private void clickLottieView_onUdfpsDevice() {
final View lottieView = mActivity.findViewById(R.id.illustration_lottie);
assertThat(lottieView).isNotNull();
lottieView.performClick();
}
private void gotEnrollingResult_resumeActivityAndVerifyResultThenForward(
int testActivityResult) {
// resume activity
mActivityController.start().resume().visible();
verifyNoSidecar();
// onActivityResult from Enrolling activity shall be forward back
Shadows.shadowOf(mActivity).receiveResult(
new Intent(mActivity, FingerprintEnrollEnrolling.class),
testActivityResult,
null);
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(testActivityResult);
assertThat(mActivity.isFinishing()).isEqualTo(true);
// onStop shall not change last activity result
mActivityController.pause().stop().destroy();
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(testActivityResult);
}
private void gotEnrollingResult_recreateActivityAndVerifyResultThenForward(
int testActivityResult, @NonNull Bundle savedInstance) {
// Rebuild activity and use savedInstance to restore.
buildActivity();
mActivityController.setup(savedInstance);
verifyNoSidecar();
// onActivityResult from Enrolling activity shall be forward back
Shadows.shadowOf(mActivity).receiveResult(
new Intent(mActivity, FingerprintEnrollEnrolling.class),
testActivityResult,
null);
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(testActivityResult);
assertThat(mActivity.isFinishing()).isEqualTo(true);
// onStop shall not change last activity result
mActivityController.pause().stop().destroy();
assertThat(Shadows.shadowOf(mActivity).getResultCode()).isEqualTo(testActivityResult);
}
private void verifySidecar_onRearOrSfpsDevice() {
final Fragment sidecar = mActivity.getSupportFragmentManager().findFragmentByTag(
TAG_SIDECAR);
assertThat(sidecar).isNotNull();
assertThat(sidecar.isAdded()).isTrue();
}
private void verifyNoSidecar() {
final Fragment sidecar = mActivity.getSupportFragmentManager().findFragmentByTag(
TAG_SIDECAR);
if (sidecar != null) {
assertThat(sidecar.isAdded()).isFalse();
}
}
}

View File

@@ -173,4 +173,24 @@ public class FingerprintEnrollIntroductionTest {
assertThat(result).isEqualTo(R.string.fingerprint_intro_error_max);
}
@Test
public void intro_CheckCanEnrollDuringPortal() {
setupFingerprintEnrollIntroWith(
new Intent().putExtra(WizardManagerHelper.EXTRA_IS_PORTAL_SETUP, true));
setFingerprintManagerToHave(2 /* numEnrollments */);
int result = mFingerprintEnrollIntroduction.checkMaxEnrolled();
assertThat(result).isEqualTo(0);
}
@Test
public void intro_CheckMaxEnrolledDuringPortal() {
setupFingerprintEnrollIntroWith(
new Intent().putExtra(WizardManagerHelper.EXTRA_IS_PORTAL_SETUP, true));
setFingerprintManagerToHave(6 /* numEnrollments */);
int result = mFingerprintEnrollIntroduction.checkMaxEnrolled();
assertThat(result).isEqualTo(R.string.fingerprint_intro_error_max);
}
}

View File

@@ -21,8 +21,8 @@ import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.RuntimeEnvironment.application;
import android.content.Intent;
import android.content.res.Resources.Theme;
import android.hardware.fingerprint.FingerprintManager;
import android.widget.Button;
import androidx.appcompat.app.AlertDialog;
@@ -49,14 +49,24 @@ import org.robolectric.annotation.Config;
@Config(shadows = {ShadowUtils.class, ShadowAlertDialogCompat.class})
public class SetupFingerprintEnrollFindSensorTest {
@Mock
private FingerprintManager mFingerprintManager;
@Mock private FingerprintManager mFingerprintManager;
private Theme mTheme;
private SetupFingerprintEnrollFindSensor mActivity;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ShadowUtils.setFingerprintManager(mFingerprintManager);
FakeFeatureFactory.setupForTest();
final Intent intent = new Intent()
// Set the challenge token so the confirm screen will not be shown
.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE_TOKEN, new byte[0]);
mActivity = Robolectric.buildActivity(SetupFingerprintEnrollFindSensor.class,
intent).setup().get();
mTheme = mActivity.getTheme();
}
@After
@@ -66,23 +76,37 @@ public class SetupFingerprintEnrollFindSensorTest {
@Test
public void fingerprintEnroll_showsAlert_whenClickingSkip() {
final Intent intent = new Intent()
// Set the challenge token so the confirm screen will not be shown
.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE_TOKEN, new byte[0]);
final AlertDialog alertDialog = setupAlertDialog();
final ShadowAlertDialogCompat shadowAlertDialog = ShadowAlertDialogCompat.shadowOf(
alertDialog);
final int titleRes = R.string.setup_fingerprint_enroll_skip_title;
final SetupFingerprintEnrollFindSensor activity =
Robolectric.buildActivity(SetupFingerprintEnrollFindSensor.class,
intent).setup().get();
assertThat(application.getString(titleRes)).isEqualTo(shadowAlertDialog.getTitle());
}
PartnerCustomizationLayout layout = activity.findViewById(R.id.setup_wizard_layout);
@Test
public void fingerprintEnroll_activityApplyDarkLightStyle() {
mActivity.onApplyThemeResource(mTheme, R.style.GlifTheme, true /* first */);
final String appliedThemes = mTheme.toString();
assertThat(appliedThemes.contains("SetupWizardPartnerResource")).isTrue();
}
@Test
public void fingerprintEnroll_showsAlert_setAlertDialogTheme() {
final AlertDialog alertDialog = setupAlertDialog();
assertThat(alertDialog.getContext().getThemeResId()).isEqualTo(
R.style.Theme_AlertDialog);
}
private AlertDialog setupAlertDialog() {
PartnerCustomizationLayout layout = mActivity.findViewById(R.id.setup_wizard_layout);
layout.getMixin(FooterBarMixin.class).getSecondaryButtonView().performClick();
final AlertDialog alertDialog = ShadowAlertDialogCompat.getLatestAlertDialog();
assertThat(alertDialog).isNotNull();
final ShadowAlertDialogCompat shadowAlertDialog = ShadowAlertDialogCompat.shadowOf(
alertDialog);
final int titleRes = R.string.setup_fingerprint_enroll_skip_title;
assertThat(application.getString(titleRes)).isEqualTo(shadowAlertDialog.getTitle());
return alertDialog;
}
}

View File

@@ -34,7 +34,6 @@ import android.widget.Button;
import com.android.settings.R;
import com.android.settings.biometrics.BiometricEnrollBase;
import com.android.settings.biometrics.BiometricEnrollIntroduction;
import com.android.settings.password.SetupChooseLockGeneric.SetupChooseLockGenericFragment;
import com.android.settings.password.SetupSkipDialog;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowFingerprintManager;
@@ -160,8 +159,6 @@ public class SetupFingerprintEnrollIntroductionTest {
ShadowActivity shadowActivity = Shadows.shadowOf(activity);
assertThat(shadowActivity.getResultIntent()).isNotNull();
assertThat(shadowActivity.getResultIntent().hasExtra(
SetupChooseLockGenericFragment.EXTRA_PASSWORD_QUALITY)).isTrue();
}
@Test
@@ -191,8 +188,6 @@ public class SetupFingerprintEnrollIntroductionTest {
ShadowActivity shadowActivity = Shadows.shadowOf(activity);
assertThat(shadowActivity.getResultIntent()).isNotNull();
assertThat(shadowActivity.getResultIntent().hasExtra(
SetupChooseLockGenericFragment.EXTRA_PASSWORD_QUALITY)).isTrue();
}
@Test
@@ -218,8 +213,6 @@ public class SetupFingerprintEnrollIntroductionTest {
BiometricEnrollBase.RESULT_FINISHED, null);
ShadowActivity shadowActivity = Shadows.shadowOf(activity);
assertThat(shadowActivity.getResultIntent()).isNotNull();
assertThat(shadowActivity.getResultIntent().hasExtra(
SetupChooseLockGenericFragment.EXTRA_PASSWORD_QUALITY)).isFalse();
}
@Test
@@ -260,8 +253,6 @@ public class SetupFingerprintEnrollIntroductionTest {
ShadowActivity shadowActivity = Shadows.shadowOf(activity);
IntentForResult startedActivity = shadowActivity.getNextStartedActivityForResult();
assertThat(startedActivity).isNotNull();
assertThat(startedActivity.intent.hasExtra(
SetupChooseLockGenericFragment.EXTRA_PASSWORD_QUALITY)).isFalse();
}
private ShadowKeyguardManager getShadowKeyguardManager() {

View File

@@ -109,6 +109,7 @@ public class BluetoothDetailsCompanionAppsControllerTest extends
/* deviceProfile */ "",
/* selfManaged */ false,
/* notifyOnDeviceNearby */ true,
/* revoked */ false,
/* timeApprovedMs */ System.currentTimeMillis(),
/* lastTimeConnected */ Long.MAX_VALUE);

View File

@@ -0,0 +1,147 @@
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.bluetooth;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import com.android.settings.R;
import com.android.settings.applications.SpacePreference;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.HearingAidProfile;
import com.android.settingslib.widget.ButtonPreference;
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;
/** Tests for {@link BluetoothDetailsPairOtherController}. */
@RunWith(RobolectricTestRunner.class)
public class BluetoothDetailsPairOtherControllerTest extends BluetoothDetailsControllerTestBase {
@Rule
public final MockitoRule mockito = MockitoJUnit.rule();
@Mock
private CachedBluetoothDevice mSubCachedDevice;
private BluetoothDetailsPairOtherController mController;
private ButtonPreference mPreference;
private SpacePreference mSpacePreference;
@Override
public void setUp() {
super.setUp();
mController = new BluetoothDetailsPairOtherController(mContext, mFragment, mCachedDevice,
mLifecycle);
mPreference = new ButtonPreference(mContext);
mSpacePreference = new SpacePreference(mContext, null);
mPreference.setKey(mController.getPreferenceKey());
mSpacePreference.setKey(BluetoothDetailsPairOtherController.KEY_SPACE);
mScreen.addPreference(mPreference);
mScreen.addPreference(mSpacePreference);
}
@Test
public void init_leftSideDevice_expectedTitle() {
when(mCachedDevice.getDeviceSide()).thenReturn(HearingAidProfile.DeviceSide.SIDE_LEFT);
mController.init(mScreen);
assertThat(mPreference.getTitle().toString()).isEqualTo(
mContext.getString(R.string.bluetooth_pair_right_ear_button));
}
@Test
public void init_rightSideDevice_expectedTitle() {
when(mCachedDevice.getDeviceSide()).thenReturn(HearingAidProfile.DeviceSide.SIDE_RIGHT);
mController.init(mScreen);
assertThat(mPreference.getTitle().toString()).isEqualTo(
mContext.getString(R.string.bluetooth_pair_left_ear_button));
}
@Test
public void init_isNotConnectedHearingAidDevice_notVisiblePreference() {
when(mCachedDevice.isConnectedHearingAidDevice()).thenReturn(false);
mController.init(mScreen);
assertThat(mPreference.isVisible()).isFalse();
assertThat(mSpacePreference.isVisible()).isFalse();
}
@Test
public void isAvailable_isNotConnectedHearingAidDevice_notAvailable() {
when(mCachedDevice.isConnectedHearingAidDevice()).thenReturn(false);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_notConnectedHearingAidDevice_notAvailable() {
when(mCachedDevice.isConnectedHearingAidDevice()).thenReturn(true);
when(mCachedDevice.getDeviceMode()).thenReturn(HearingAidProfile.DeviceMode.MODE_MONAURAL);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_subDeviceIsConnectedHearingAidDevice_notAvailable() {
when(mCachedDevice.isConnectedHearingAidDevice()).thenReturn(true);
when(mCachedDevice.getDeviceMode()).thenReturn(HearingAidProfile.DeviceMode.MODE_BINAURAL);
when(mSubCachedDevice.isConnectedHearingAidDevice()).thenReturn(true);
when(mCachedDevice.getSubDevice()).thenReturn(mSubCachedDevice);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isAvailable_subDeviceNotConnectedHearingAidDevice_available() {
when(mCachedDevice.isConnectedHearingAidDevice()).thenReturn(true);
when(mCachedDevice.getDeviceMode()).thenReturn(HearingAidProfile.DeviceMode.MODE_BINAURAL);
when(mSubCachedDevice.isConnectedHearingAidDevice()).thenReturn(false);
when(mCachedDevice.getSubDevice()).thenReturn(mSubCachedDevice);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_subDeviceNotExist_available() {
when(mCachedDevice.isConnectedHearingAidDevice()).thenReturn(true);
when(mCachedDevice.getDeviceMode()).thenReturn(HearingAidProfile.DeviceMode.MODE_BINAURAL);
when(mCachedDevice.getSubDevice()).thenReturn(null);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void refresh_isNotConnectedHearingAidDevice_notVisiblePreference() {
when(mCachedDevice.isConnectedHearingAidDevice()).thenReturn(false);
mController.init(mScreen);
mController.refresh();
assertThat(mPreference.isVisible()).isFalse();
assertThat(mSpacePreference.isVisible()).isFalse();
}
}

View File

@@ -22,7 +22,9 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothDevice;
import android.media.AudioDeviceAttributes;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.media.Spatializer;
@@ -57,6 +59,8 @@ public class BluetoothDetailsSpatialAudioControllerTest extends BluetoothDetails
private Lifecycle mSpatialAudioLifecycle;
@Mock
private PreferenceCategory mProfilesContainer;
@Mock
private BluetoothDevice mBluetoothDevice;
private BluetoothDetailsSpatialAudioController mController;
private SwitchPreference mSpatialAudioPref;
@@ -70,6 +74,8 @@ public class BluetoothDetailsSpatialAudioControllerTest extends BluetoothDetails
when(mContext.getSystemService(AudioManager.class)).thenReturn(mAudioManager);
when(mAudioManager.getSpatializer()).thenReturn(mSpatializer);
when(mCachedDevice.getAddress()).thenReturn(MAC_ADDRESS);
when(mCachedDevice.getDevice()).thenReturn(mBluetoothDevice);
when(mBluetoothDevice.getAnonymizedAddress()).thenReturn(MAC_ADDRESS);
mController = new BluetoothDetailsSpatialAudioController(mContext, mFragment,
mCachedDevice, mSpatialAudioLifecycle);
@@ -83,15 +89,85 @@ public class BluetoothDetailsSpatialAudioControllerTest extends BluetoothDetails
}
@Test
public void isAvailable_spatialAudioIsAvailable_returnsTrue() {
when(mSpatializer.isAvailableForDevice(mController.mAudioDevice)).thenReturn(true);
public void isAvailable_spatialAudioSupportA2dpDevice_returnsTrue() {
AudioDeviceAttributes a2dpDevice = new AudioDeviceAttributes(
AudioDeviceAttributes.ROLE_OUTPUT,
AudioDeviceInfo.TYPE_BLUETOOTH_A2DP,
MAC_ADDRESS);
when(mSpatializer.isAvailableForDevice(a2dpDevice)).thenReturn(true);
mController.setAvailableDevice(a2dpDevice);
assertThat(mController.isAvailable()).isTrue();
assertThat(mController.mAudioDevice.getType())
.isEqualTo(AudioDeviceInfo.TYPE_BLUETOOTH_A2DP);
}
@Test
public void isAvailable_spatialAudioIsNotAvailable_returnsFalse() {
when(mSpatializer.isAvailableForDevice(mController.mAudioDevice)).thenReturn(false);
public void isAvailable_spatialAudioSupportBleHeadsetDevice_returnsTrue() {
AudioDeviceAttributes bleHeadsetDevice = new AudioDeviceAttributes(
AudioDeviceAttributes.ROLE_OUTPUT,
AudioDeviceInfo.TYPE_BLE_HEADSET,
MAC_ADDRESS);
when(mSpatializer.isAvailableForDevice(bleHeadsetDevice)).thenReturn(true);
mController.setAvailableDevice(bleHeadsetDevice);
assertThat(mController.isAvailable()).isTrue();
assertThat(mController.mAudioDevice.getType())
.isEqualTo(AudioDeviceInfo.TYPE_BLE_HEADSET);
}
@Test
public void isAvailable_spatialAudioSupportBleSpeakerDevice_returnsTrue() {
AudioDeviceAttributes bleSpeakerDevice = new AudioDeviceAttributes(
AudioDeviceAttributes.ROLE_OUTPUT,
AudioDeviceInfo.TYPE_BLE_SPEAKER,
MAC_ADDRESS);
when(mSpatializer.isAvailableForDevice(bleSpeakerDevice)).thenReturn(true);
mController.setAvailableDevice(bleSpeakerDevice);
assertThat(mController.isAvailable()).isTrue();
assertThat(mController.mAudioDevice.getType())
.isEqualTo(AudioDeviceInfo.TYPE_BLE_SPEAKER);
}
@Test
public void isAvailable_spatialAudioSupportBleBroadcastDevice_returnsTrue() {
AudioDeviceAttributes bleBroadcastDevice = new AudioDeviceAttributes(
AudioDeviceAttributes.ROLE_OUTPUT,
AudioDeviceInfo.TYPE_BLE_BROADCAST,
MAC_ADDRESS);
when(mSpatializer.isAvailableForDevice(bleBroadcastDevice)).thenReturn(true);
mController.setAvailableDevice(bleBroadcastDevice);
assertThat(mController.isAvailable()).isTrue();
assertThat(mController.mAudioDevice.getType())
.isEqualTo(AudioDeviceInfo.TYPE_BLE_BROADCAST);
}
@Test
public void isAvailable_spatialAudioSupportHearingAidDevice_returnsTrue() {
AudioDeviceAttributes hearingAidDevice = new AudioDeviceAttributes(
AudioDeviceAttributes.ROLE_OUTPUT,
AudioDeviceInfo.TYPE_HEARING_AID,
MAC_ADDRESS);
when(mSpatializer.isAvailableForDevice(hearingAidDevice)).thenReturn(true);
mController.setAvailableDevice(hearingAidDevice);
assertThat(mController.isAvailable()).isTrue();
assertThat(mController.mAudioDevice.getType())
.isEqualTo(AudioDeviceInfo.TYPE_HEARING_AID);
}
@Test
public void isAvailable_spatialAudioNotSupported_returnsFalse() {
assertThat(mController.isAvailable()).isFalse();
assertThat(mController.mAudioDevice.getType())
.isEqualTo(AudioDeviceInfo.TYPE_HEARING_AID);
}
@Test

View File

@@ -17,16 +17,28 @@ package com.android.settings.bluetooth;
import static android.bluetooth.BluetoothDevice.PAIRING_VARIANT_CONSENT;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Parcel;
import com.android.settings.core.SettingsUIDeviceConfig;
import com.android.settings.testutils.shadow.ShadowBluetoothAdapter;
import com.android.settings.testutils.shadow.ShadowBluetoothUtils;
import com.android.settings.testutils.shadow.ShadowDeviceConfig;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.bluetooth.CachedBluetoothDeviceManager;
import com.android.settingslib.bluetooth.LocalBluetoothManager;
import com.android.settingslib.bluetooth.LocalBluetoothProfile;
import com.android.settingslib.bluetooth.LocalBluetoothProfileManager;
import org.junit.Before;
import org.junit.Test;
@@ -36,16 +48,36 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
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})
@Config(shadows = {ShadowBluetoothAdapter.class, ShadowBluetoothUtils.class,
ShadowDeviceConfig.class})
public class BluetoothPairingControllerTest {
private final BluetoothClass mBluetoothClass =
createBtClass(BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE);
@Mock
private CachedBluetoothDeviceManager mCachedDeviceManager;
@Mock
private LocalBluetoothManager mLocalBluetoothManager;
@Mock
private LocalBluetoothProfileManager mLocalBluetoothProfileManager;
@Mock
private BluetoothDevice mBluetoothDevice;
@Mock
private CachedBluetoothDevice mCachedDevice;
@Mock
private LocalBluetoothProfile mLocalBluetoothProfile;
@Mock
private LocalBluetoothProfile mPbapLocalBluetoothProfile;
private Context mContext;
private BluetoothPairingController mBluetoothPairingController;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private BluetoothClass createBtClass(int deviceClass) {
Parcel p = Parcel.obtain();
@@ -57,14 +89,32 @@ public class BluetoothPairingControllerTest {
return bluetoothClass;
}
private BluetoothPairingController createBluetoothPairingController() {
final Intent intent = new Intent();
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mBluetoothDevice);
return new BluetoothPairingController(intent, mContext);
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
final Intent intent = new Intent();
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mBluetoothDevice);
mBluetoothPairingController = new BluetoothPairingController(intent, mContext);
mShadowBluetoothAdapter = Shadow.extract(BluetoothAdapter.getDefaultAdapter());
mShadowBluetoothAdapter.setEnabled(true);
ShadowBluetoothUtils.sLocalBluetoothManager = mLocalBluetoothManager;
mLocalBluetoothManager = Utils.getLocalBtManager(mContext);
when(mLocalBluetoothManager.getCachedDeviceManager()).thenReturn(mCachedDeviceManager);
when(mLocalBluetoothManager.getProfileManager()).thenReturn(mLocalBluetoothProfileManager);
when(mCachedDeviceManager.findDevice(mBluetoothDevice)).thenReturn(mCachedDevice);
List<LocalBluetoothProfile> localBluetoothProfiles = new ArrayList<>();
mockIsLeAudio(false);
localBluetoothProfiles.add(mLocalBluetoothProfile);
when(mCachedDevice.getProfiles()).thenReturn(localBluetoothProfiles);
when(mCachedDevice.getDevice()).thenReturn(mBluetoothDevice);
mBluetoothPairingController = createBluetoothPairingController();
mBluetoothPairingController.mockPbapClientProfile(mPbapLocalBluetoothProfile);
}
@Test
@@ -108,4 +158,124 @@ public class BluetoothPairingControllerTest {
verify(mBluetoothDevice).setPhonebookAccessPermission(BluetoothDevice.ACCESS_REJECTED);
}
@Test
public void isLeAudio_noLeProfile_returnsFalse() {
mockIsLeAudio(false);
mBluetoothPairingController = createBluetoothPairingController();
assertThat(mBluetoothPairingController.isLeAudio()).isFalse();
}
@Test
public void isLeAudio_isLeProfile_returnsTrue() {
mockIsLeAudio(true);
mBluetoothPairingController = createBluetoothPairingController();
assertThat(mBluetoothPairingController.isLeAudio()).isTrue();
}
@Test
public void isLeContactSharingEnabled_configIsFalse_returnsFalse() {
mockIsLeContactSharingEnabled(false);
mBluetoothPairingController = createBluetoothPairingController();
assertThat(mBluetoothPairingController.isLeContactSharingEnabled()).isFalse();
}
@Test
public void isLeContactSharingEnabled_configIsTrue_returnsTrue() {
mockIsLeContactSharingEnabled(true);
mBluetoothPairingController = createBluetoothPairingController();
assertThat(mBluetoothPairingController.isLeContactSharingEnabled()).isTrue();
}
@Test
public void isContactSharingVisible_profileIsNotReady_returnsTrue() {
// isProfileReady=false, isLeAudio=false, isLeContactSharingEnabled=true
mockIsProfileReady(false);
mockIsLeAudio(false);
mockIsLeContactSharingEnabled(true);
mBluetoothPairingController = createBluetoothPairingController();
mBluetoothPairingController.mockPbapClientProfile(mPbapLocalBluetoothProfile);
assertThat(mBluetoothPairingController.isContactSharingVisible()).isTrue();
}
@Test
public void isContactSharingVisible_profileIsReady_returnsFalse() {
// isProfileReady=true, isLeAudio=false, isLeContactSharingEnabled=true
mockIsProfileReady(true);
mockIsLeAudio(false);
mockIsLeContactSharingEnabled(true);
mBluetoothPairingController = createBluetoothPairingController();
mBluetoothPairingController.mockPbapClientProfile(mPbapLocalBluetoothProfile);
assertThat(mBluetoothPairingController.isContactSharingVisible()).isFalse();
}
@Test
public void isContactSharingVisible_DeviceIsLeAudioAndProfileIsReady_returnsFalse() {
// isProfileReady=true, isLeAudio=true, isLeContactSharingEnabled=true
mockIsProfileReady(true);
mockIsLeAudio(true);
mockIsLeContactSharingEnabled(true);
mBluetoothPairingController = createBluetoothPairingController();
mBluetoothPairingController.mockPbapClientProfile(mPbapLocalBluetoothProfile);
assertThat(mBluetoothPairingController.isContactSharingVisible()).isFalse();
}
@Test
public void isContactSharingVisible_DeviceIsLeAudioAndProfileIsNotReady_returnsTrue() {
// isProfileReady=false, isLeAudio=true, isLeContactSharingEnabled=true
mockIsProfileReady(false);
mockIsLeAudio(true);
mockIsLeContactSharingEnabled(true);
mBluetoothPairingController = createBluetoothPairingController();
mBluetoothPairingController.mockPbapClientProfile(mPbapLocalBluetoothProfile);
assertThat(mBluetoothPairingController.isContactSharingVisible()).isTrue();
}
@Test
public void isContactSharingVisible_DeviceIsLeAndContactSharingIsNotEnabled_returnsFalse() {
// isProfileReady=false, isLeAudio=true, isLeContactSharingEnabled=false
mockIsProfileReady(false);
mockIsLeAudio(true);
mockIsLeContactSharingEnabled(false);
mBluetoothPairingController = createBluetoothPairingController();
mBluetoothPairingController.mockPbapClientProfile(mPbapLocalBluetoothProfile);
assertThat(mBluetoothPairingController.isContactSharingVisible()).isFalse();
}
private void mockIsProfileReady(boolean mockValue) {
when(mPbapLocalBluetoothProfile.isProfileReady()).thenReturn(mockValue);
}
private void mockIsLeAudio(boolean mockValue) {
int profileId = BluetoothProfile.HEADSET;
if (mockValue) {
profileId = BluetoothProfile.LE_AUDIO;
}
when(mLocalBluetoothProfile.getProfileId()).thenReturn(profileId);
}
private void mockIsLeContactSharingEnabled(boolean mockValue) {
android.provider.DeviceConfig.setProperty(
android.provider.DeviceConfig.NAMESPACE_SETTINGS_UI,
SettingsUIDeviceConfig.BT_LE_AUDIO_CONTACT_SHARING_ENABLED,
/* value= */ mockValue ? "true" : "false", true);
}
}

View File

@@ -274,13 +274,12 @@ public class BluetoothPairingDialogTest {
}
@Test
public void dialogShowsContactSharingCheckboxWhenBluetoothProfileNotReady() {
public void contactSharingCheckbox_conditionIsReady_showsUi() {
// set the dialog variant to confirmation/consent
when(controller.getDialogType()).thenReturn(BluetoothPairingController.CONFIRMATION_DIALOG);
// set a fake device name and pretend the profile has not been set up for it
when(controller.getDeviceName()).thenReturn(FAKE_DEVICE_NAME);
when(controller.isProfileReady()).thenReturn(false);
when(controller.isContactSharingVisible()).thenReturn(true);
// build the fragment
BluetoothPairingDialogFragment frag = makeFragment();
@@ -292,13 +291,12 @@ public class BluetoothPairingDialogTest {
}
@Test
public void dialogHidesContactSharingCheckboxWhenBluetoothProfileIsReady() {
public void contactSharingCheckbox_conditionIsNotReady_doesNotShowUi() {
// set the dialog variant to confirmation/consent
when(controller.getDialogType()).thenReturn(BluetoothPairingController.CONFIRMATION_DIALOG);
// set a fake device name and pretend the profile has been set up for it
when(controller.getDeviceName()).thenReturn(FAKE_DEVICE_NAME);
when(controller.isProfileReady()).thenReturn(true);
when(controller.isContactSharingVisible()).thenReturn(false);
// build the fragment
BluetoothPairingDialogFragment frag = makeFragment();

View File

@@ -297,6 +297,14 @@ public class DashboardFragmentTest {
mTestFragment.updatePreferenceVisibility(prefControllers);
}
@Test
public void forceUpdatePreferences_prefKeyNull_shouldNotCrash() {
mTestFragment.addPreferenceController(new TestPreferenceController(mContext));
// Should not crash
mTestFragment.forceUpdatePreferences();
}
@Test
public void checkUiBlocker_noUiBlocker_controllerIsNull() {
mTestFragment.mBlockerController = null;

View File

@@ -22,9 +22,13 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.time.Capabilities;
import android.app.time.TimeManager;
import android.app.time.TimeZoneCapabilities;
import android.app.time.TimeZoneCapabilitiesAndConfig;
import android.app.time.TimeZoneConfiguration;
import android.content.Context;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.os.UserHandle;
import androidx.preference.Preference;
@@ -32,6 +36,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@@ -46,7 +51,7 @@ public class AutoTimeZonePreferenceControllerTest {
private AutoTimeZonePreferenceController mController;
private Preference mPreference;
@Mock
private TelephonyManager mTelephonyManager;
private TimeManager mTimeManager;
@Before
public void setUp() {
@@ -55,12 +60,15 @@ public class AutoTimeZonePreferenceControllerTest {
mPreference = new Preference(mContext);
when(mContext.getSystemService(TelephonyManager.class)).thenReturn(mTelephonyManager);
when(mTelephonyManager.isDataCapable()).thenReturn(true);
when(mContext.getSystemService(TimeManager.class)).thenReturn(mTimeManager);
}
@Test
public void isFromSUW_notAvailable() {
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */true, /* autoEnabled= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
mController = new AutoTimeZonePreferenceController(
mContext, null /* callback */, true /* isFromSUW */);
@@ -69,6 +77,10 @@ public class AutoTimeZonePreferenceControllerTest {
@Test
public void notFromSUW_isAvailable() {
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */true, /* autoEnabled= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
mController = new AutoTimeZonePreferenceController(
mContext, null /* callback */, false /* isFromSUW */);
@@ -76,8 +88,11 @@ public class AutoTimeZonePreferenceControllerTest {
}
@Test
public void isWifiOnly_notAvailable() {
when(mTelephonyManager.isDataCapable()).thenReturn(false);
public void autoTimeZoneNotSupported_notAvailable() {
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */false, /* autoEnabled= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
mController = new AutoTimeZonePreferenceController(
mContext, null /* callback */, false /* fromSUW */);
@@ -86,54 +101,134 @@ public class AutoTimeZonePreferenceControllerTest {
@Test
public void isFromSUW_notEnable() {
mController =
new AutoTimeZonePreferenceController(mContext, null /* callback */, true /* fromSUW */);
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */false, /* autoEnabled= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
mController = new AutoTimeZonePreferenceController(
mContext, null /* callback */, true /* fromSUW */);
assertThat(mController.isEnabled()).isFalse();
}
@Test
public void isWifiOnly_notEnable() {
when(mTelephonyManager.isDataCapable()).thenReturn(false);
public void isFromSUW_isEnable() {
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */false, /* autoEnabled= */true);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
mController = new AutoTimeZonePreferenceController(
mContext, null /* callback */, false /* fromSUW */);
mContext, null /* callback */, true /* fromSUW */);
assertThat(mController.isEnabled()).isFalse();
}
@Test
public void testIsEnabled_shouldReadFromSettingsProvider() {
mController = new AutoTimeZonePreferenceController(
mContext, null /* callback */, false /* fromSUW */);
// Disabled
Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AUTO_TIME_ZONE, 0);
assertThat(mController.isEnabled()).isFalse();
// Enabled
Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AUTO_TIME_ZONE, 1);
assertThat(mController.isEnabled()).isTrue();
}
@Test
public void autoTimeZoneNotSupported_notEnable() {
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */false, /* autoEnabled= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
mController = new AutoTimeZonePreferenceController(
mContext, null /* callback */, false /* fromSUW */);
assertThat(mController.isEnabled()).isFalse();
}
@Test
public void testIsEnabled_shouldReadFromTimeManagerConfig() {
mController = new AutoTimeZonePreferenceController(
mContext, null /* callback */, false /* fromSUW */);
{
// Disabled
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */true, /* autoEnabled= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
assertThat(mController.isEnabled()).isFalse();
}
{
// Enabled
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */true, /* autoEnabled= */true);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
assertThat(mController.isEnabled()).isTrue();
}
}
@Test
public void updatePreferenceChange_prefIsChecked_shouldUpdatePreferenceAndNotifyCallback() {
mController =
new AutoTimeZonePreferenceController(mContext, mCallback, false /* fromSUW */);
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */true, /* autoEnabled= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
when(mTimeManager.updateTimeZoneConfiguration(Mockito.any())).thenReturn(true);
mController.onPreferenceChange(mPreference, true);
mController = new AutoTimeZonePreferenceController(
mContext, mCallback, false /* fromSUW */);
assertThat(mController.onPreferenceChange(mPreference, true)).isTrue();
verify(mCallback).updateTimeAndDateDisplay(mContext);
// Check the service was asked to change the configuration correctly.
TimeZoneConfiguration timeZoneConfiguration = new TimeZoneConfiguration.Builder()
.setAutoDetectionEnabled(true)
.build();
verify(mTimeManager).updateTimeZoneConfiguration(timeZoneConfiguration);
// Update the mTimeManager mock so that it now returns the expected updated config.
TimeZoneCapabilitiesAndConfig capabilitiesAndConfigAfterUpdate =
createCapabilitiesAndConfig(/* autoSupported= */true, /* autoEnabled= */true);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig())
.thenReturn(capabilitiesAndConfigAfterUpdate);
assertThat(mController.isEnabled()).isTrue();
verify(mCallback).updateTimeAndDateDisplay(mContext);
}
@Test
public void updatePreferenceChange_prefIsUnchecked_shouldUpdatePreferenceAndNotifyCallback() {
mController =
new AutoTimeZonePreferenceController(mContext, mCallback, false /* fromSUW */);
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* autoSupported= */true, /* autoEnabled= */true);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
when(mTimeManager.updateTimeZoneConfiguration(Mockito.any())).thenReturn(true);
mController.onPreferenceChange(mPreference, false);
mController = new AutoTimeZonePreferenceController(
mContext, mCallback, false /* fromSUW */);
assertThat(mController.onPreferenceChange(mPreference, false)).isTrue();
verify(mCallback).updateTimeAndDateDisplay(mContext);
// Check the service was asked to change the configuration correctly.
TimeZoneConfiguration timeZoneConfiguration = new TimeZoneConfiguration.Builder()
.setAutoDetectionEnabled(false)
.build();
verify(mTimeManager).updateTimeZoneConfiguration(timeZoneConfiguration);
// Update the mTimeManager mock so that it now returns the expected updated config.
TimeZoneCapabilitiesAndConfig capabilitiesAndConfigAfterUpdate =
createCapabilitiesAndConfig(/* autoSupported= */true, /* autoEnabled= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig())
.thenReturn(capabilitiesAndConfigAfterUpdate);
assertThat(mController.isEnabled()).isFalse();
verify(mCallback).updateTimeAndDateDisplay(mContext);
}
private static TimeZoneCapabilitiesAndConfig createCapabilitiesAndConfig(
boolean autoSupported, boolean autoEnabled) {
int configureAutoDetectionEnabledCapability =
autoSupported ? Capabilities.CAPABILITY_POSSESSED
: Capabilities.CAPABILITY_NOT_SUPPORTED;
TimeZoneCapabilities capabilities = new TimeZoneCapabilities.Builder(UserHandle.SYSTEM)
.setConfigureAutoDetectionEnabledCapability(configureAutoDetectionEnabledCapability)
.setConfigureGeoDetectionEnabledCapability(Capabilities.CAPABILITY_NOT_SUPPORTED)
.setSuggestManualTimeZoneCapability(Capabilities.CAPABILITY_POSSESSED)
.build();
TimeZoneConfiguration config = new TimeZoneConfiguration.Builder()
.setAutoDetectionEnabled(autoEnabled)
.setGeoDetectionEnabled(false)
.build();
return new TimeZoneCapabilitiesAndConfig(capabilities, config);
}
}

View File

@@ -22,7 +22,13 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.app.time.Capabilities;
import android.app.time.TimeManager;
import android.app.time.TimeZoneCapabilities;
import android.app.time.TimeZoneCapabilitiesAndConfig;
import android.app.time.TimeZoneConfiguration;
import android.content.Context;
import android.os.UserHandle;
import com.android.settingslib.RestrictedPreference;
@@ -38,8 +44,7 @@ import org.robolectric.RuntimeEnvironment;
public class TimeZonePreferenceControllerTest {
@Mock
private AutoTimeZonePreferenceController mAutoTimeZonePreferenceController;
private TimeManager mTimeManager;
private Context mContext;
private TimeZonePreferenceController mController;
private RestrictedPreference mPreference;
@@ -47,10 +52,14 @@ public class TimeZonePreferenceControllerTest {
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mContext = spy(RuntimeEnvironment.application);
doReturn(mTimeManager).when(mContext).getSystemService(TimeManager.class);
mPreference = new RestrictedPreference(mContext);
mController = spy(new TimeZonePreferenceController(mContext,
mAutoTimeZonePreferenceController));
mController = spy(new TimeZonePreferenceController(mContext));
doReturn("test timezone").when(mController).getTimeZoneOffsetAndName();
}
@Test
@@ -59,26 +68,46 @@ public class TimeZonePreferenceControllerTest {
}
@Test
public void updateState_autoTimeZoneEnabled_shouldDisablePref() {
public void updateState_suggestManualNotAllowed_shouldDisablePref() {
// Make sure not disabled by admin.
mPreference.setDisabledByAdmin(null);
doReturn("test timezone").when(mController).getTimeZoneOffsetAndName();
when(mAutoTimeZonePreferenceController.isEnabled()).thenReturn(true);
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* suggestManualAllowed= */false);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
mController.updateState(mPreference);
assertThat(mPreference.isEnabled()).isFalse();
}
@Test
public void updateState_autoTimeZoneDisabled_shouldEnablePref() {
public void updateState_suggestManualAllowed_shouldEnablePref() {
// Make sure not disabled by admin.
mPreference.setDisabledByAdmin(null);
doReturn("test timezone").when(mController).getTimeZoneOffsetAndName();
when(mAutoTimeZonePreferenceController.isEnabled()).thenReturn(false);
TimeZoneCapabilitiesAndConfig capabilitiesAndConfig = createCapabilitiesAndConfig(
/* suggestManualAllowed= */true);
when(mTimeManager.getTimeZoneCapabilitiesAndConfig()).thenReturn(capabilitiesAndConfig);
mController.updateState(mPreference);
assertThat(mPreference.isEnabled()).isTrue();
}
private static TimeZoneCapabilitiesAndConfig createCapabilitiesAndConfig(
boolean suggestManualAllowed) {
int suggestManualCapability = suggestManualAllowed ? Capabilities.CAPABILITY_POSSESSED
: Capabilities.CAPABILITY_NOT_SUPPORTED;
TimeZoneCapabilities capabilities = new TimeZoneCapabilities.Builder(UserHandle.SYSTEM)
.setConfigureAutoDetectionEnabledCapability(Capabilities.CAPABILITY_POSSESSED)
.setConfigureGeoDetectionEnabledCapability(Capabilities.CAPABILITY_NOT_SUPPORTED)
.setSuggestManualTimeZoneCapability(suggestManualCapability)
.build();
TimeZoneConfiguration config = new TimeZoneConfiguration.Builder()
.setAutoDetectionEnabled(!suggestManualAllowed)
.setGeoDetectionEnabled(false)
.build();
return new TimeZoneCapabilitiesAndConfig(capabilities, config);
}
}

View File

@@ -47,6 +47,8 @@ public final class EnableVerboseVendorLoggingPreferenceControllerTest {
private PreferenceScreen mPreferenceScreen;
@Mock
IDumpstateDevice mIDumpstateDevice;
@Mock
android.hardware.dumpstate.IDumpstateDevice mIDumpstateDeviceAidl;
private Context mContext;
private EnableVerboseVendorLoggingPreferenceController mController;
@@ -57,6 +59,7 @@ public final class EnableVerboseVendorLoggingPreferenceControllerTest {
mContext = RuntimeEnvironment.application;
mController = spy(new EnableVerboseVendorLoggingPreferenceController(mContext));
doReturn(mIDumpstateDevice).when(mController).getDumpstateDeviceService();
doReturn(mIDumpstateDeviceAidl).when(mController).getDumpstateDeviceAidlService();
// mock with Dumpstate HAL v1.1
Field f = EnableVerboseVendorLoggingPreferenceController.class
@@ -70,7 +73,9 @@ public final class EnableVerboseVendorLoggingPreferenceControllerTest {
}
@Test
public void onPreferenceChange_settingEnable_enableVendorLoggingShouldBeOn() throws Exception {
public void onPreferenceChange_settingEnableByHidl_enableVendorLoggingShouldBeOn()
throws Exception {
doReturn(null).when(mController).getDumpstateDeviceAidlService();
doReturn(true).when(mIDumpstateDevice).getVerboseLoggingEnabled();
mController.onPreferenceChange(mPreference, true /* new value */);
@@ -80,8 +85,21 @@ public final class EnableVerboseVendorLoggingPreferenceControllerTest {
}
@Test
public void onPreferenceChange_settingDisable_enableVendorLoggingShouldBeOff()
public void onPreferenceChange_settingEnableByAidl_enableVendorLoggingShouldBeOn()
throws Exception {
doReturn(mIDumpstateDeviceAidl).when(mController).getDumpstateDeviceAidlService();
doReturn(true).when(mIDumpstateDeviceAidl).getVerboseLoggingEnabled();
mController.onPreferenceChange(mPreference, true /* new value */);
final boolean enabled = mController.getVerboseLoggingEnabled();
assertTrue(enabled);
}
@Test
public void onPreferenceChange_settingDisableByHidl_enableVendorLoggingShouldBeOff()
throws Exception {
doReturn(null).when(mController).getDumpstateDeviceAidlService();
doReturn(false).when(mIDumpstateDevice).getVerboseLoggingEnabled();
mController.onPreferenceChange(mPreference, false /* new value */);
@@ -91,7 +109,20 @@ public final class EnableVerboseVendorLoggingPreferenceControllerTest {
}
@Test
public void updateState_settingDisabled_preferenceShouldNotBeChecked() throws Exception {
public void onPreferenceChange_settingDisableByAidl_enableVendorLoggingShouldBeOff()
throws Exception {
doReturn(mIDumpstateDeviceAidl).when(mController).getDumpstateDeviceAidlService();
doReturn(false).when(mIDumpstateDeviceAidl).getVerboseLoggingEnabled();
mController.onPreferenceChange(mPreference, false /* new value */);
final boolean enabled = mController.getVerboseLoggingEnabled();
assertFalse(enabled);
}
@Test
public void updateState_settingDisabledByHidl_preferenceShouldNotBeChecked() throws Exception {
doReturn(null).when(mController).getDumpstateDeviceAidlService();
doReturn(false).when(mIDumpstateDevice).getVerboseLoggingEnabled();
mController.setVerboseLoggingEnabled(false);
@@ -101,7 +132,19 @@ public final class EnableVerboseVendorLoggingPreferenceControllerTest {
}
@Test
public void updateState_settingEnabled_preferenceShouldBeChecked() throws Exception {
public void updateState_settingDisabledByAidl_preferenceShouldNotBeChecked() throws Exception {
doReturn(mIDumpstateDeviceAidl).when(mController).getDumpstateDeviceAidlService();
doReturn(false).when(mIDumpstateDeviceAidl).getVerboseLoggingEnabled();
mController.setVerboseLoggingEnabled(false);
mController.updateState(mPreference);
verify(mPreference).setChecked(false);
}
@Test
public void updateState_settingEnabledByHidl_preferenceShouldBeChecked() throws Exception {
doReturn(null).when(mController).getDumpstateDeviceAidlService();
doReturn(true).when(mIDumpstateDevice).getVerboseLoggingEnabled();
mController.setVerboseLoggingEnabled(true);
@@ -111,7 +154,19 @@ public final class EnableVerboseVendorLoggingPreferenceControllerTest {
}
@Test
public void onDeveloperOptionDisabled_shouldDisablePreference() throws Exception {
public void updateState_settingEnabledByAidl_preferenceShouldBeChecked() throws Exception {
doReturn(mIDumpstateDeviceAidl).when(mController).getDumpstateDeviceAidlService();
doReturn(true).when(mIDumpstateDeviceAidl).getVerboseLoggingEnabled();
mController.setVerboseLoggingEnabled(true);
mController.updateState(mPreference);
verify(mPreference).setChecked(true);
}
@Test
public void onDeveloperOptionDisabled_byHidl_shouldDisablePreference() throws Exception {
doReturn(null).when(mController).getDumpstateDeviceAidlService();
doReturn(false).when(mIDumpstateDevice).getVerboseLoggingEnabled();
mController.onDeveloperOptionsSwitchDisabled();
@@ -121,4 +176,17 @@ public final class EnableVerboseVendorLoggingPreferenceControllerTest {
verify(mPreference).setChecked(false);
verify(mPreference).setEnabled(false);
}
@Test
public void onDeveloperOptionDisabled_byAidl_shouldDisablePreference() throws Exception {
doReturn(mIDumpstateDeviceAidl).when(mController).getDumpstateDeviceAidlService();
doReturn(false).when(mIDumpstateDeviceAidl).getVerboseLoggingEnabled();
mController.onDeveloperOptionsSwitchDisabled();
final boolean enabled = mController.getVerboseLoggingEnabled();
assertFalse(enabled);
verify(mPreference).setChecked(false);
verify(mPreference).setEnabled(false);
}
}

View File

@@ -102,7 +102,7 @@ public class NotificationChannelWarningsPreferenceControllerTest {
}
@Test
public void updateState_settingUndefinedDebuggingEnabled_preferenceShouldBeChecked() {
public void updateState_settingUndefinedDebuggingEnabled_preferenceShouldNotBeChecked() {
mController = spy(mController);
doReturn(true).when(mController).isDebuggable();
Settings.Global.putString(mContext.getContentResolver(),
@@ -110,18 +110,6 @@ public class NotificationChannelWarningsPreferenceControllerTest {
mController.updateState(mPreference);
verify(mPreference).setChecked(true);
}
@Test
public void updateState_settingUndefinedDebuggingDisabled_preferenceShouldNotBeChecked() {
mController = spy(mController);
doReturn(false).when(mController).isDebuggable();
Settings.Global.putString(mContext.getContentResolver(),
Settings.Global.SHOW_NOTIFICATION_CHANNEL_WARNINGS, "NotAnInteger");
mController.updateState(mPreference);
verify(mPreference).setChecked(false);
}

View File

@@ -52,6 +52,8 @@ import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class BluetoothCodecDialogPreferenceControllerTest {
private static final int SOURCE_CODEC_TYPE_OPUS = 6; // TODO(b/240635097): remove in U
private static final String DEVICE_ADDRESS = "00:11:22:33:44:55";
@Mock
@@ -72,6 +74,7 @@ public class BluetoothCodecDialogPreferenceControllerTest {
private BluetoothCodecConfig mCodecConfigAPTX;
private BluetoothCodecConfig mCodecConfigAPTXHD;
private BluetoothCodecConfig mCodecConfigLDAC;
private BluetoothCodecConfig mCodecConfigOPUS;
private BluetoothDevice mActiveDevice;
private Context mContext;
private LifecycleOwner mLifecycleOwner;
@@ -119,13 +122,17 @@ public class BluetoothCodecDialogPreferenceControllerTest {
mCodecConfigLDAC = new BluetoothCodecConfig.Builder()
.setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC)
.build();
mCodecConfigOPUS = new BluetoothCodecConfig.Builder()
.setCodecType(SOURCE_CODEC_TYPE_OPUS)
.build();
when(mBluetoothAdapter.getActiveDevices(eq(BluetoothProfile.A2DP)))
.thenReturn(Arrays.asList(mActiveDevice));
}
@Test
public void writeConfigurationValues_selectDefault_setHighest() {
BluetoothCodecConfig[] mCodecConfigs = {mCodecConfigAAC, mCodecConfigSBC};
BluetoothCodecConfig[] mCodecConfigs = {mCodecConfigOPUS, mCodecConfigAAC,
mCodecConfigSBC};
mCodecStatus = new BluetoothCodecStatus.Builder()
.setCodecConfig(mCodecConfigSBC)
.setCodecsSelectableCapabilities(Arrays.asList(mCodecConfigs))
@@ -136,13 +143,14 @@ public class BluetoothCodecDialogPreferenceControllerTest {
mController.onBluetoothServiceConnected(mBluetoothA2dp);
mController.writeConfigurationValues(0);
verify(mBluetoothA2dpConfigStore).setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC);
// TODO(b/240635097): update in U
verify(mBluetoothA2dpConfigStore).setCodecType(SOURCE_CODEC_TYPE_OPUS);
}
@Test
public void writeConfigurationValues_checkCodec() {
BluetoothCodecConfig[] mCodecConfigs = {mCodecConfigAAC, mCodecConfigSBC, mCodecConfigAPTX,
mCodecConfigAPTXHD, mCodecConfigLDAC, mCodecConfigAAC, mCodecConfigSBC};
BluetoothCodecConfig[] mCodecConfigs = {mCodecConfigOPUS, mCodecConfigAAC,
mCodecConfigSBC, mCodecConfigAPTX, mCodecConfigAPTXHD, mCodecConfigLDAC};
mCodecStatus = new BluetoothCodecStatus.Builder()
.setCodecConfig(mCodecConfigSBC)
.setCodecsSelectableCapabilities(Arrays.asList(mCodecConfigs))
@@ -167,12 +175,15 @@ public class BluetoothCodecDialogPreferenceControllerTest {
mController.writeConfigurationValues(5);
verify(mBluetoothA2dpConfigStore).setCodecType(BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC);
mController.writeConfigurationValues(7);
// TODO(b/240635097): update in U
verify(mBluetoothA2dpConfigStore).setCodecType(SOURCE_CODEC_TYPE_OPUS);
}
@Test
public void writeConfigurationValues_resetHighestConfig() {
BluetoothCodecConfig[] mCodecConfigs = {mCodecConfigAAC, mCodecConfigSBC, mCodecConfigAPTX,
mCodecConfigAPTXHD, mCodecConfigLDAC, mCodecConfigAAC, mCodecConfigSBC};
mCodecConfigAPTXHD, mCodecConfigLDAC, mCodecConfigOPUS};
mCodecStatus = new BluetoothCodecStatus.Builder()
.setCodecConfig(mCodecConfigAAC)
.setCodecsSelectableCapabilities(Arrays.asList(mCodecConfigs))
@@ -197,6 +208,14 @@ public class BluetoothCodecDialogPreferenceControllerTest {
mController.convertCfgToBtnIndex(BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC));
}
@Test
public void getCurrentIndexByConfig_verifyOpusIndex() {
assertThat(mController.getCurrentIndexByConfig(mCodecConfigOPUS)).isEqualTo(
mController.convertCfgToBtnIndex(SOURCE_CODEC_TYPE_OPUS));
// TODO(b/240635097): update in U
}
@Test
public void onIndexUpdated_notifyPreference() {
mController.onIndexUpdated(0);
@@ -204,9 +223,29 @@ public class BluetoothCodecDialogPreferenceControllerTest {
verify(mCallback).onBluetoothCodecChanged();
}
@Test
public void onHDAudioEnabled_optionalCodecEnabled_setsCodecTypeAsOpus() {
List<BluetoothCodecConfig> mCodecConfigs = Arrays.asList(mCodecConfigOPUS,
mCodecConfigAAC, mCodecConfigSBC);
mCodecStatus = new BluetoothCodecStatus.Builder()
.setCodecConfig(mCodecConfigOPUS)
.setCodecsSelectableCapabilities(mCodecConfigs)
.build();
when(mBluetoothA2dp.getCodecStatus(mActiveDevice)).thenReturn(mCodecStatus);
when(mBluetoothA2dp.isOptionalCodecsEnabled(mActiveDevice)).thenReturn(
BluetoothA2dp.OPTIONAL_CODECS_PREF_ENABLED);
mController.onBluetoothServiceConnected(mBluetoothA2dp);
mController.onHDAudioEnabled(/* enabled= */ true);
verify(mBluetoothA2dpConfigStore, atLeastOnce()).setCodecType(
eq(SOURCE_CODEC_TYPE_OPUS)); // TODO(b/240635097): update in U
}
@Test
public void onHDAudioEnabled_optionalCodecEnabled_setsCodecTypeAsAAC() {
List<BluetoothCodecConfig> mCodecConfigs = Arrays.asList(mCodecConfigAAC, mCodecConfigSBC);
List<BluetoothCodecConfig> mCodecConfigs = Arrays.asList(mCodecConfigOPUS,
mCodecConfigAAC, mCodecConfigSBC);
mCodecStatus = new BluetoothCodecStatus.Builder()
.setCodecConfig(mCodecConfigAAC)
.setCodecsSelectableCapabilities(mCodecConfigs)
@@ -223,7 +262,8 @@ public class BluetoothCodecDialogPreferenceControllerTest {
}
@Test
public void onHDAudioEnabled_optionalCodecDisabled_setsCodecTypeAsSBC() {
List<BluetoothCodecConfig> mCodecConfigs = Arrays.asList(mCodecConfigAAC, mCodecConfigSBC);
List<BluetoothCodecConfig> mCodecConfigs = Arrays.asList(mCodecConfigOPUS,
mCodecConfigAAC, mCodecConfigSBC);
mCodecStatus = new BluetoothCodecStatus.Builder()
.setCodecConfig(mCodecConfigAAC)
.setCodecsSelectableCapabilities(mCodecConfigs)

View File

@@ -19,7 +19,9 @@ package com.android.settings.development.qstile;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -30,6 +32,7 @@ import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.os.Bundle;
import android.os.RemoteException;
import android.service.quicksettings.TileService;
@@ -50,6 +53,7 @@ import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.shadows.ShadowPackageManager;
import org.robolectric.shadows.ShadowSystemProperties;
import org.robolectric.util.ReflectionHelpers;
import java.util.Arrays;
@@ -88,11 +92,7 @@ public class DevelopmentTilePreferenceControllerTest {
public void display_hasTileService_shouldDisplay() {
final Intent tileProbe = new Intent(TileService.ACTION_QS_TILE)
.setPackage(mContext.getPackageName());
final ResolveInfo info = new ResolveInfo();
info.serviceInfo = new FakeServiceInfo();
info.serviceInfo.name = "abc";
info.serviceInfo.icon = R.drawable.ic_settings_24dp;
info.serviceInfo.packageName = mContext.getPackageName();
final ResolveInfo info = createFakeInfo("abc");
mShadowPackageManager.setResolveInfosForIntent(tileProbe, Arrays.asList(info));
mController.displayPreference(mScreen);
@@ -100,6 +100,36 @@ public class DevelopmentTilePreferenceControllerTest {
verify(mScreen, atLeastOnce()).addPreference(any(Preference.class));
}
@Test
public void display_flagDefinedAndOn_shouldDisplay() {
ShadowSystemProperties.override("tile_flag", "1");
final Intent tileProbe = new Intent(TileService.ACTION_QS_TILE)
.setPackage(mContext.getPackageName());
final ResolveInfo info = createFakeInfo("abc");
info.serviceInfo.metaData = createFlagMetadata("tile_flag");
mShadowPackageManager.setResolveInfosForIntent(tileProbe, Arrays.asList(info));
mController.displayPreference(mScreen);
verify(mScreen, atLeastOnce()).addPreference(argThat(pref -> pref.getKey().equals("abc")));
}
@Test
public void display_flagDefinedAndOff_shouldHide() {
ShadowSystemProperties.override("tile_flag" , "0");
final Intent tileProbe = new Intent(TileService.ACTION_QS_TILE)
.setPackage(mContext.getPackageName());
final ResolveInfo info = createFakeInfo("abc");
info.serviceInfo.metaData = createFlagMetadata("tile_flag");
mShadowPackageManager.setResolveInfosForIntent(tileProbe, Arrays.asList(info));
mController.displayPreference(mScreen);
verify(mScreen, never()).addPreference(argThat(pref -> pref.getKey().equals("abc")));
}
@Test
public void preferenceChecked_shouldAddTile() throws RemoteException {
SwitchPreference preference = createPreference(/* defaultCheckedState = */ false);
@@ -132,6 +162,21 @@ public class DevelopmentTilePreferenceControllerTest {
return preference;
}
private ResolveInfo createFakeInfo(String name) {
final ResolveInfo info = new ResolveInfo();
info.serviceInfo = new FakeServiceInfo();
info.serviceInfo.name = name;
info.serviceInfo.icon = R.drawable.ic_settings_24dp;
info.serviceInfo.packageName = mContext.getPackageName();
return info;
}
private Bundle createFlagMetadata(String flag) {
Bundle metaData = new Bundle();
metaData.putString(DevelopmentTiles.META_DATA_REQUIRES_SYSTEM_PROPERTY, flag);
return metaData;
}
private static class FakeServiceInfo extends ServiceInfo {
public String loadLabel(PackageManager mgr) {

View File

@@ -25,6 +25,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.UserManager;
@@ -33,6 +34,7 @@ import androidx.preference.Preference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
@@ -85,7 +87,13 @@ public class FirmwareVersionDetailPreferenceControllerTest {
mController.handlePreferenceTreeClick(mPreference);
verify(mContext).startActivity(any());
final ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
verify(mContext).startActivity(captor.capture());
assertThat(captor.getValue().getAction()).isEqualTo(Intent.ACTION_MAIN);
assertThat(captor.getValue().getComponent().getPackageName()).isEqualTo("android");
assertThat(captor.getValue().getComponent().getClassName()).isEqualTo(
com.android.internal.app.PlatLogoActivity.class.getName());
assertThat(captor.getValue().getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK).isGreaterThan(0);
}
@Test

View File

@@ -53,6 +53,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
import com.android.settings.fuelgauge.batteryusage.BatteryEntry;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowActivityManager;
import com.android.settings.testutils.shadow.ShadowEntityHeaderController;
@@ -231,7 +232,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testGetPreferenceScreenResId_returnNewLayout() {
public void setPreferenceScreenResId_returnNewLayout() {
assertThat(mFragment.getPreferenceScreenResId()).isEqualTo(R.xml.power_usage_detail);
}
@@ -251,7 +252,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_HasAppEntry_BuildByAppEntry() {
public void initHeader_HasAppEntry_BuildByAppEntry() {
ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
new InstantAppDataProvider() {
@Override
@@ -268,7 +269,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_HasAppEntry_InstantApp() {
public void initHeader_HasAppEntry_InstantApp() {
ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
new InstantAppDataProvider() {
@Override
@@ -285,7 +286,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_noUsageTimeAndGraphDisabled_hasCorrectSummary() {
public void initHeader_noUsageTimeAndGraphDisabled_hasCorrectSummary() {
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mContext))
.thenReturn(false);
@@ -303,7 +304,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_bgTwoMinFgZeroAndGraphDisabled_hasCorrectSummary() {
public void initHeader_bgTwoMinFgZeroAndGraphDisabled_hasCorrectSummary() {
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mContext))
.thenReturn(false);
@@ -323,7 +324,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_bgLessThanAMinFgZeroAndGraphDisabled_hasCorrectSummary() {
public void initHeader_bgLessThanAMinFgZeroAndGraphDisabled_hasCorrectSummary() {
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mContext))
.thenReturn(false);
@@ -344,7 +345,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_totalUsageLessThanAMinAndGraphDisabled_hasCorrectSummary() {
public void initHeader_totalUsageLessThanAMinAndGraphDisabled_hasCorrectSummary() {
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mContext))
.thenReturn(false);
@@ -366,7 +367,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_TotalAMinutesBgLessThanAMinAndGraphDisabled_hasCorrectSummary() {
public void initHeader_TotalAMinutesBgLessThanAMinAndGraphDisabled_hasCorrectSummary() {
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mContext))
.thenReturn(false);
@@ -386,7 +387,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_TotalAMinBackgroundZeroAndGraphDisabled_hasCorrectSummary() {
public void initHeader_TotalAMinBackgroundZeroAndGraphDisabled_hasCorrectSummary() {
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mContext))
.thenReturn(false);
final long backgroundTimeZero = 0;
@@ -405,7 +406,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_fgTwoMinBgFourMinAndGraphDisabled_hasCorrectSummary() {
public void initHeader_fgTwoMinBgFourMinAndGraphDisabled_hasCorrectSummary() {
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mContext))
.thenReturn(false);
final long backgroundTimeFourMinute = 240000;
@@ -423,7 +424,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_noUsageTime_hasCorrectSummary() {
public void initHeader_noUsageTime_hasCorrectSummary() {
Bundle bundle = new Bundle(2);
bundle.putLong(AdvancedPowerUsageDetail.EXTRA_BACKGROUND_TIME, /* value */ 0);
bundle.putLong(AdvancedPowerUsageDetail.EXTRA_FOREGROUND_TIME, /* value */ 0);
@@ -434,11 +435,11 @@ public class AdvancedPowerUsageDetailTest {
ArgumentCaptor<CharSequence> captor = ArgumentCaptor.forClass(CharSequence.class);
verify(mEntityHeaderController).setSummary(captor.capture());
assertThat(captor.getValue().toString())
.isEqualTo("No usage for past 24 hr");
.isEqualTo("No usage from last full charge");
}
@Test
public void testInitHeader_noUsageTimeButConsumedPower_hasEmptySummary() {
public void initHeader_noUsageTimeButConsumedPower_hasEmptySummary() {
Bundle bundle = new Bundle(3);
bundle.putLong(AdvancedPowerUsageDetail.EXTRA_BACKGROUND_TIME, /* value */ 0);
bundle.putLong(AdvancedPowerUsageDetail.EXTRA_FOREGROUND_TIME, /* value */ 0);
@@ -453,7 +454,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_backgroundTwoMinForegroundZero_hasCorrectSummary() {
public void initHeader_backgroundTwoMinForegroundZero_hasCorrectSummary() {
final long backgroundTimeTwoMinutes = 120000;
final long foregroundTimeZero = 0;
Bundle bundle = new Bundle(2);
@@ -466,11 +467,11 @@ public class AdvancedPowerUsageDetailTest {
ArgumentCaptor<CharSequence> captor = ArgumentCaptor.forClass(CharSequence.class);
verify(mEntityHeaderController).setSummary(captor.capture());
assertThat(captor.getValue().toString())
.isEqualTo("2 min background for past 24 hr");
.isEqualTo("2 min background from last full charge");
}
@Test
public void testInitHeader_backgroundLessThanAMinForegroundZero_hasCorrectSummary() {
public void initHeader_backgroundLessThanAMinForegroundZero_hasCorrectSummary() {
final long backgroundTimeLessThanAMinute = 59999;
final long foregroundTimeZero = 0;
Bundle bundle = new Bundle(2);
@@ -484,11 +485,11 @@ public class AdvancedPowerUsageDetailTest {
ArgumentCaptor<CharSequence> captor = ArgumentCaptor.forClass(CharSequence.class);
verify(mEntityHeaderController).setSummary(captor.capture());
assertThat(captor.getValue().toString())
.isEqualTo("Background less than a minute for past 24 hr");
.isEqualTo("Background less than a minute from last full charge");
}
@Test
public void testInitHeader_totalUsageLessThanAMin_hasCorrectSummary() {
public void initHeader_totalUsageLessThanAMin_hasCorrectSummary() {
final long backgroundTimeLessThanHalfMinute = 20000;
final long foregroundTimeLessThanHalfMinute = 20000;
Bundle bundle = new Bundle(2);
@@ -503,11 +504,11 @@ public class AdvancedPowerUsageDetailTest {
ArgumentCaptor<CharSequence> captor = ArgumentCaptor.forClass(CharSequence.class);
verify(mEntityHeaderController).setSummary(captor.capture());
assertThat(captor.getValue().toString())
.isEqualTo("Total less than a minute for past 24 hr");
.isEqualTo("Total less than a minute from last full charge");
}
@Test
public void testInitHeader_TotalAMinutesBackgroundLessThanAMin_hasCorrectSummary() {
public void initHeader_TotalAMinutesBackgroundLessThanAMin_hasCorrectSummary() {
final long backgroundTimeZero = 59999;
final long foregroundTimeTwoMinutes = 1;
Bundle bundle = new Bundle(2);
@@ -520,11 +521,11 @@ public class AdvancedPowerUsageDetailTest {
ArgumentCaptor<CharSequence> captor = ArgumentCaptor.forClass(CharSequence.class);
verify(mEntityHeaderController).setSummary(captor.capture());
assertThat(captor.getValue().toString())
.isEqualTo("1 min total • background less than a minute\nfor past 24 hr");
.isEqualTo("1 min total • background less than a minute\nfrom last full charge");
}
@Test
public void testInitHeader_TotalAMinBackgroundZero_hasCorrectSummary() {
public void initHeader_TotalAMinBackgroundZero_hasCorrectSummary() {
final long backgroundTimeZero = 0;
final long foregroundTimeAMinutes = 60000;
Bundle bundle = new Bundle(2);
@@ -537,11 +538,11 @@ public class AdvancedPowerUsageDetailTest {
ArgumentCaptor<CharSequence> captor = ArgumentCaptor.forClass(CharSequence.class);
verify(mEntityHeaderController).setSummary(captor.capture());
assertThat(captor.getValue().toString())
.isEqualTo("1 min total for past 24 hr");
.isEqualTo("1 min total from last full charge");
}
@Test
public void testInitHeader_foregroundTwoMinBackgroundFourMin_hasCorrectSummary() {
public void initHeader_foregroundTwoMinBackgroundFourMin_hasCorrectSummary() {
final long backgroundTimeFourMinute = 240000;
final long foregroundTimeTwoMinutes = 120000;
Bundle bundle = new Bundle(2);
@@ -554,11 +555,11 @@ public class AdvancedPowerUsageDetailTest {
ArgumentCaptor<CharSequence> captor = ArgumentCaptor.forClass(CharSequence.class);
verify(mEntityHeaderController).setSummary(captor.capture());
assertThat(captor.getValue().toString())
.isEqualTo("6 min total • 4 min background\nfor past 24 hr");
.isEqualTo("6 min total • 4 min background\nfrom last full charge");
}
@Test
public void testInitHeader_totalUsageLessThanAMinWithSlotTime_hasCorrectSummary() {
public void initHeader_totalUsageLessThanAMinWithSlotTime_hasCorrectSummary() {
final long backgroundTimeLessThanHalfMinute = 20000;
final long foregroundTimeLessThanHalfMinute = 20000;
Bundle bundle = new Bundle(3);
@@ -578,7 +579,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_TotalAMinBackgroundLessThanAMinWithSlotTime_hasCorrectSummary() {
public void initHeader_TotalAMinBackgroundLessThanAMinWithSlotTime_hasCorrectSummary() {
final long backgroundTimeZero = 59999;
final long foregroundTimeTwoMinutes = 1;
Bundle bundle = new Bundle(3);
@@ -596,7 +597,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_TotalAMinBackgroundZeroWithSlotTime_hasCorrectSummary() {
public void initHeader_TotalAMinBackgroundZeroWithSlotTime_hasCorrectSummary() {
final long backgroundTimeZero = 0;
final long foregroundTimeAMinutes = 60000;
Bundle bundle = new Bundle(3);
@@ -614,7 +615,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_foregroundTwoMinBackgroundFourMinWithSlotTime_hasCorrectSummary() {
public void initHeader_foregroundTwoMinBackgroundFourMinWithSlotTime_hasCorrectSummary() {
final long backgroundTimeFourMinute = 240000;
final long foregroundTimeTwoMinutes = 120000;
Bundle bundle = new Bundle(3);
@@ -632,7 +633,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_systemUidWithChartIsDisabled_nullSummary() {
public void initHeader_systemUidWithChartIsDisabled_nullSummary() {
Bundle bundle = new Bundle(3);
bundle.putLong(AdvancedPowerUsageDetail.EXTRA_BACKGROUND_TIME, 240000);
bundle.putLong(AdvancedPowerUsageDetail.EXTRA_FOREGROUND_TIME, 120000);
@@ -649,7 +650,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitHeader_systemUidWithChartIsEnabled_notNullSummary() {
public void initHeader_systemUidWithChartIsEnabled_notNullSummary() {
Bundle bundle = new Bundle(3);
bundle.putLong(AdvancedPowerUsageDetail.EXTRA_BACKGROUND_TIME, 240000);
bundle.putLong(AdvancedPowerUsageDetail.EXTRA_FOREGROUND_TIME, 120000);
@@ -664,21 +665,21 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testStartBatteryDetailPage_hasBasicData() {
public void startBatteryDetailPage_hasBasicData() {
AdvancedPowerUsageDetail.startBatteryDetailPage(mActivity, mFragment,
mBatteryEntry, USAGE_PERCENT, /*isValidToShowSummary=*/ true);
assertThat(mBundle.getInt(AdvancedPowerUsageDetail.EXTRA_UID)).isEqualTo(UID);
assertThat(mBundle.getLong(AdvancedPowerUsageDetail.EXTRA_BACKGROUND_TIME))
.isEqualTo(BACKGROUND_TIME_MS);
.isEqualTo(BACKGROUND_TIME_MS);
assertThat(mBundle.getLong(AdvancedPowerUsageDetail.EXTRA_FOREGROUND_TIME))
.isEqualTo(FOREGROUND_TIME_MS);
.isEqualTo(FOREGROUND_TIME_MS);
assertThat(mBundle.getString(AdvancedPowerUsageDetail.EXTRA_POWER_USAGE_PERCENT))
.isEqualTo(USAGE_PERCENT);
.isEqualTo(USAGE_PERCENT);
}
@Test
public void testStartBatteryDetailPage_invalidToShowSummary_noFGBDData() {
public void startBatteryDetailPage_invalidToShowSummary_noFGBDData() {
AdvancedPowerUsageDetail.startBatteryDetailPage(mActivity, mFragment,
mBatteryEntry, USAGE_PERCENT, /*isValidToShowSummary=*/ false);
@@ -692,7 +693,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testStartBatteryDetailPage_NormalApp() {
public void startBatteryDetailPage_NormalApp() {
when(mBatteryEntry.getDefaultPackageName()).thenReturn(PACKAGE_NAME[0]);
AdvancedPowerUsageDetail.startBatteryDetailPage(mActivity, mFragment,
@@ -703,7 +704,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testStartBatteryDetailPage_SystemApp() {
public void startBatteryDetailPage_SystemApp() {
when(mBatteryEntry.getDefaultPackageName()).thenReturn(null);
AdvancedPowerUsageDetail.startBatteryDetailPage(mActivity, mFragment,
@@ -715,7 +716,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testStartBatteryDetailPage_WorkApp() {
public void startBatteryDetailPage_WorkApp() {
final int appUid = 1010019;
doReturn(appUid).when(mBatteryEntry).getUid();
@@ -726,7 +727,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testStartBatteryDetailPage_typeUser_startByCurrentUser() {
public void startBatteryDetailPage_typeUser_startByCurrentUser() {
when(mBatteryEntry.isUserEntry()).thenReturn(true);
final int currentUser = 20;
@@ -738,7 +739,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testStartBatteryDetailPage_noBatteryUsage_hasBasicData() {
public void startBatteryDetailPage_noBatteryUsage_hasBasicData() {
final ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
AdvancedPowerUsageDetail.startBatteryDetailPage(mActivity, mFragment, PACKAGE_NAME[0]);
@@ -746,16 +747,16 @@ public class AdvancedPowerUsageDetailTest {
verify(mActivity).startActivity(captor.capture());
assertThat(captor.getValue().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS)
.getString(AdvancedPowerUsageDetail.EXTRA_PACKAGE_NAME))
.isEqualTo(PACKAGE_NAME[0]);
.getString(AdvancedPowerUsageDetail.EXTRA_PACKAGE_NAME))
.isEqualTo(PACKAGE_NAME[0]);
assertThat(captor.getValue().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS)
.getString(AdvancedPowerUsageDetail.EXTRA_POWER_USAGE_PERCENT))
.isEqualTo("0%");
.getString(AdvancedPowerUsageDetail.EXTRA_POWER_USAGE_PERCENT))
.isEqualTo("0%");
}
@Test
public void testStartBatteryDetailPage_batteryEntryNotExisted_extractUidFromPackageName() throws
public void startBatteryDetailPage_batteryEntryNotExisted_extractUidFromPackageName() throws
PackageManager.NameNotFoundException {
doReturn(UID).when(mPackageManager).getPackageUid(PACKAGE_NAME[0], 0 /* no flag */);
@@ -795,7 +796,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitPreferenceForTriState_isSystemOrDefaultApp_hasCorrectString() {
public void initPreferenceForTriState_isSystemOrDefaultApp_hasCorrectString() {
when(mBatteryOptimizeUtils.isValidPackageName()).thenReturn(true);
when(mBatteryOptimizeUtils.isSystemOrDefaultApp()).thenReturn(true);
@@ -806,7 +807,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testInitPreferenceForTriState_hasCorrectString() {
public void initPreferenceForTriState_hasCorrectString() {
when(mBatteryOptimizeUtils.isValidPackageName()).thenReturn(true);
when(mBatteryOptimizeUtils.isSystemOrDefaultApp()).thenReturn(false);
@@ -817,7 +818,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testOnRadioButtonClicked_clickOptimizePref_optimizePreferenceChecked() {
public void onRadioButtonClicked_clickOptimizePref_optimizePreferenceChecked() {
mOptimizePreference.setKey(KEY_PREF_OPTIMIZED);
mRestrictedPreference.setKey(KEY_PREF_RESTRICTED);
mUnrestrictedPreference.setKey(KEY_PREF_UNRESTRICTED);
@@ -829,7 +830,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testOnPause_optimizationModeChanged_logPreference() {
public void onPause_optimizationModeChanged_logPreference() {
final int mode = BatteryOptimizeUtils.MODE_RESTRICTED;
mFragment.mOptimizationMode = mode;
when(mBatteryOptimizeUtils.getAppOptimizationMode()).thenReturn(mode);
@@ -848,7 +849,7 @@ public class AdvancedPowerUsageDetailTest {
}
@Test
public void testOnPause_optimizationModeIsNotChanged_notInvokeLogging() {
public void onPause_optimizationModeIsNotChanged_notInvokeLogging() {
final int mode = BatteryOptimizeUtils.MODE_OPTIMIZED;
mFragment.mOptimizationMode = mode;
when(mBatteryOptimizeUtils.getAppOptimizationMode()).thenReturn(mode);

View File

@@ -25,6 +25,7 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
@@ -48,6 +49,7 @@ import android.os.IDeviceIdleController;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.ArraySet;
import com.android.settingslib.fuelgauge.PowerAllowlistBackend;
@@ -68,6 +70,7 @@ import org.robolectric.annotation.Resetter;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@RunWith(RobolectricTestRunner.class)
@@ -193,7 +196,7 @@ public final class BatteryBackupHelperTest {
doReturn(Arrays.asList(userInfo)).when(mUserManager).getProfiles(anyInt());
doThrow(new RuntimeException())
.when(mIPackageManager)
.getInstalledApplications(anyInt(), anyInt());
.getInstalledApplications(anyLong(), anyInt());
mBatteryBackupHelper.backupOptimizationMode(mBackupDataOutput, null);
@@ -341,9 +344,17 @@ public final class BatteryBackupHelperTest {
private void verifyBackupData(String expectedResult) throws Exception {
final byte[] expectedBytes = expectedResult.getBytes();
final ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class);
final Set<String> expectedResultSet =
Set.of(expectedResult.split(BatteryBackupHelper.DELIMITER));
verify(mBackupDataOutput).writeEntityHeader(
BatteryBackupHelper.KEY_OPTIMIZATION_LIST, expectedBytes.length);
verify(mBackupDataOutput).writeEntityData(expectedBytes, expectedBytes.length);
verify(mBackupDataOutput).writeEntityData(captor.capture(), eq(expectedBytes.length));
final String actualResult = new String(captor.getValue());
final Set<String> actualResultSet =
Set.of(actualResult.split(BatteryBackupHelper.DELIMITER));
assertThat(actualResultSet).isEqualTo(expectedResultSet);
}
private void createTestingData(
@@ -369,7 +380,7 @@ public final class BatteryBackupHelperTest {
doReturn(new ParceledListSlice<ApplicationInfo>(
Arrays.asList(applicationInfo1, applicationInfo2, applicationInfo3)))
.when(mIPackageManager)
.getInstalledApplications(anyInt(), anyInt());
.getInstalledApplications(anyLong(), anyInt());
// Sets the AppOpsManager for checkOpNoThrow() method.
doReturn(AppOpsManager.MODE_ALLOWED)
.when(mAppOpsManager)
@@ -384,7 +395,7 @@ public final class BatteryBackupHelperTest {
applicationInfo2.uid,
applicationInfo2.packageName);
mBatteryBackupHelper.mTestApplicationInfoList =
Arrays.asList(applicationInfo1, applicationInfo2, applicationInfo3);
new ArraySet<>(Arrays.asList(applicationInfo1, applicationInfo2, applicationInfo3));
}
@Implements(UserHandle.class)

View File

@@ -1,697 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import android.app.settings.SettingsEnums;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.LocaleList;
import android.text.format.DateUtils;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceGroup;
import com.android.settings.SettingsActivity;
import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@RunWith(RobolectricTestRunner.class)
public final class BatteryChartPreferenceControllerTest {
private static final String PREF_KEY = "pref_key";
private static final String PREF_SUMMARY = "fake preference summary";
private static final int DESIRED_HISTORY_SIZE =
BatteryChartPreferenceController.DESIRED_HISTORY_SIZE;
@Mock private InstrumentedPreferenceFragment mFragment;
@Mock private SettingsActivity mSettingsActivity;
@Mock private PreferenceGroup mAppListGroup;
@Mock private PackageManager mPackageManager;
@Mock private Drawable mDrawable;
@Mock private BatteryHistEntry mBatteryHistEntry;
@Mock private BatteryChartView mBatteryChartView;
@Mock private PowerGaugePreference mPowerGaugePreference;
@Mock private ExpandDividerPreference mExpandDividerPreference;
@Mock private BatteryUtils mBatteryUtils;
@Mock private Configuration mConfiguration;
@Mock private Resources mResources;
private Context mContext;
private FakeFeatureFactory mFeatureFactory;
private BatteryDiffEntry mBatteryDiffEntry;
private MetricsFeatureProvider mMetricsFeatureProvider;
private BatteryChartPreferenceController mBatteryChartPreferenceController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Locale.setDefault(new Locale("en_US"));
org.robolectric.shadows.ShadowSettings.set24HourTimeFormat(false);
mFeatureFactory = FakeFeatureFactory.setupForTest();
mMetricsFeatureProvider = mFeatureFactory.metricsFeatureProvider;
mContext = spy(RuntimeEnvironment.application);
final Resources resources = spy(mContext.getResources());
resources.getConfiguration().setLocales(new LocaleList(new Locale("en_US")));
doReturn(resources).when(mContext).getResources();
doReturn(new String[] {"com.android.googlequicksearchbox"})
.when(mFeatureFactory.powerUsageFeatureProvider)
.getHideApplicationSummary(mContext);
doReturn(new String[] {"com.android.gms.persistent"})
.when(mFeatureFactory.powerUsageFeatureProvider)
.getHideApplicationEntries(mContext);
mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mPrefContext = mContext;
mBatteryChartPreferenceController.mAppListPrefGroup = mAppListGroup;
mBatteryChartPreferenceController.mBatteryChartView = mBatteryChartView;
mBatteryDiffEntry = new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 1,
/*backgroundUsageTimeInMs=*/ 2,
/*consumePower=*/ 3,
mBatteryHistEntry);
mBatteryDiffEntry = spy(mBatteryDiffEntry);
// Adds fake testing data.
BatteryDiffEntry.sResourceCache.put(
"fakeBatteryDiffEntryKey",
new BatteryEntry.NameAndIcon("fakeName", /*icon=*/ null, /*iconId=*/ 1));
mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap());
}
@Test
public void testOnDestroy_activityIsChanging_clearBatteryEntryCache() {
doReturn(true).when(mSettingsActivity).isChangingConfigurations();
// Ensures the testing environment is correct.
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
mBatteryChartPreferenceController.onDestroy();
assertThat(BatteryDiffEntry.sResourceCache).isEmpty();
}
@Test
public void testOnDestroy_activityIsNotChanging_notClearBatteryEntryCache() {
doReturn(false).when(mSettingsActivity).isChangingConfigurations();
// Ensures the testing environment is correct.
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
mBatteryChartPreferenceController.onDestroy();
assertThat(BatteryDiffEntry.sResourceCache).isNotEmpty();
}
@Test
public void testOnDestroy_clearPreferenceCache() {
// Ensures the testing environment is correct.
mBatteryChartPreferenceController.mPreferenceCache.put(
PREF_KEY, mPowerGaugePreference);
assertThat(mBatteryChartPreferenceController.mPreferenceCache).hasSize(1);
mBatteryChartPreferenceController.onDestroy();
// Verifies the result after onDestroy.
assertThat(mBatteryChartPreferenceController.mPreferenceCache).isEmpty();
}
@Test
public void testOnDestroy_removeAllPreferenceFromPreferenceGroup() {
mBatteryChartPreferenceController.onDestroy();
verify(mAppListGroup).removeAll();
}
@Test
public void testSetBatteryHistoryMap_createExpectedKeysAndLevels() {
mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap());
// Verifies the created battery keys array.
for (int index = 0; index < DESIRED_HISTORY_SIZE; index++) {
assertThat(mBatteryChartPreferenceController.mBatteryHistoryKeys[index])
// These values is are calculated by hand from createBatteryHistoryMap().
.isEqualTo(index + 1);
}
// Verifies the created battery levels array.
for (int index = 0; index < 13; index++) {
assertThat(mBatteryChartPreferenceController.mBatteryHistoryLevels[index])
// These values is are calculated by hand from createBatteryHistoryMap().
.isEqualTo(100 - index * 2);
}
assertThat(mBatteryChartPreferenceController.mBatteryIndexedMap).hasSize(13);
}
@Test
public void testSetBatteryHistoryMap_largeSize_createExpectedKeysAndLevels() {
mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap());
// Verifies the created battery keys array.
for (int index = 0; index < DESIRED_HISTORY_SIZE; index++) {
assertThat(mBatteryChartPreferenceController.mBatteryHistoryKeys[index])
// These values is are calculated by hand from createBatteryHistoryMap().
.isEqualTo(index + 1);
}
// Verifies the created battery levels array.
for (int index = 0; index < 13; index++) {
assertThat(mBatteryChartPreferenceController.mBatteryHistoryLevels[index])
// These values is are calculated by hand from createBatteryHistoryMap().
.isEqualTo(100 - index * 2);
}
assertThat(mBatteryChartPreferenceController.mBatteryIndexedMap).hasSize(13);
}
@Test
public void testRefreshUi_batteryIndexedMapIsNull_ignoreRefresh() {
mBatteryChartPreferenceController.setBatteryHistoryMap(null);
assertThat(mBatteryChartPreferenceController.refreshUi(
/*trapezoidIndex=*/ 1, /*isForce=*/ false)).isFalse();
}
@Test
public void testRefreshUi_batteryChartViewIsNull_ignoreRefresh() {
mBatteryChartPreferenceController.mBatteryChartView = null;
assertThat(mBatteryChartPreferenceController.refreshUi(
/*trapezoidIndex=*/ 1, /*isForce=*/ false)).isFalse();
}
@Test
public void testRefreshUi_trapezoidIndexIsNotChanged_ignoreRefresh() {
final int trapezoidIndex = 1;
mBatteryChartPreferenceController.mTrapezoidIndex = trapezoidIndex;
assertThat(mBatteryChartPreferenceController.refreshUi(
trapezoidIndex, /*isForce=*/ false)).isFalse();
}
@Test
public void testRefreshUi_forceUpdate_refreshUi() {
final int trapezoidIndex = 1;
mBatteryChartPreferenceController.mTrapezoidIndex = trapezoidIndex;
assertThat(mBatteryChartPreferenceController.refreshUi(
trapezoidIndex, /*isForce=*/ true)).isTrue();
}
@Test
public void testForceRefreshUi_updateTrapezoidIndexIntoSelectAll() {
mBatteryChartPreferenceController.mTrapezoidIndex =
BatteryChartView.SELECTED_INDEX_INVALID;
mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap());
assertThat(mBatteryChartPreferenceController.mTrapezoidIndex)
.isEqualTo(BatteryChartView.SELECTED_INDEX_ALL);
}
@Test
public void testRemoveAndCacheAllPrefs_emptyContent_ignoreRemoveAll() {
final int trapezoidIndex = 1;
doReturn(0).when(mAppListGroup).getPreferenceCount();
mBatteryChartPreferenceController.refreshUi(
trapezoidIndex, /*isForce=*/ true);
verify(mAppListGroup, never()).removeAll();
}
@Test
public void testRemoveAndCacheAllPrefs_buildCacheAndRemoveAllPreference() {
final int trapezoidIndex = 1;
doReturn(1).when(mAppListGroup).getPreferenceCount();
doReturn(mPowerGaugePreference).when(mAppListGroup).getPreference(0);
doReturn(PREF_KEY).when(mPowerGaugePreference).getKey();
// Ensures the testing data is correct.
assertThat(mBatteryChartPreferenceController.mPreferenceCache).isEmpty();
mBatteryChartPreferenceController.refreshUi(
trapezoidIndex, /*isForce=*/ true);
assertThat(mBatteryChartPreferenceController.mPreferenceCache.get(PREF_KEY))
.isEqualTo(mPowerGaugePreference);
verify(mAppListGroup).removeAll();
}
@Test
public void testAddPreferenceToScreen_emptyContent_ignoreAddPreference() {
mBatteryChartPreferenceController.addPreferenceToScreen(
new ArrayList<BatteryDiffEntry>());
verify(mAppListGroup, never()).addPreference(any());
}
@Test
public void testAddPreferenceToScreen_addPreferenceIntoScreen() {
final String appLabel = "fake app label";
doReturn(1).when(mAppListGroup).getPreferenceCount();
doReturn(mDrawable).when(mBatteryDiffEntry).getAppIcon();
doReturn(appLabel).when(mBatteryDiffEntry).getAppLabel();
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
doReturn(null).when(mAppListGroup).findPreference(PREF_KEY);
doReturn(false).when(mBatteryDiffEntry).validForRestriction();
mBatteryChartPreferenceController.addPreferenceToScreen(
Arrays.asList(mBatteryDiffEntry));
// Verifies the preference cache.
final PowerGaugePreference pref =
(PowerGaugePreference) mBatteryChartPreferenceController.mPreferenceCache
.get(PREF_KEY);
assertThat(pref).isNotNull();
// Verifies the added preference configuration.
verify(mAppListGroup).addPreference(pref);
assertThat(pref.getKey()).isEqualTo(PREF_KEY);
assertThat(pref.getTitle()).isEqualTo(appLabel);
assertThat(pref.getIcon()).isEqualTo(mDrawable);
assertThat(pref.getOrder()).isEqualTo(1);
assertThat(pref.getBatteryDiffEntry()).isSameInstanceAs(mBatteryDiffEntry);
assertThat(pref.isSingleLineTitle()).isTrue();
assertThat(pref.isEnabled()).isFalse();
}
@Test
public void testAddPreferenceToScreen_alreadyInScreen_notAddPreferenceAgain() {
final String appLabel = "fake app label";
doReturn(1).when(mAppListGroup).getPreferenceCount();
doReturn(mDrawable).when(mBatteryDiffEntry).getAppIcon();
doReturn(appLabel).when(mBatteryDiffEntry).getAppLabel();
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
doReturn(mPowerGaugePreference).when(mAppListGroup).findPreference(PREF_KEY);
mBatteryChartPreferenceController.addPreferenceToScreen(
Arrays.asList(mBatteryDiffEntry));
verify(mAppListGroup, never()).addPreference(any());
}
@Test
public void testHandlePreferenceTreeiClick_notPowerGaugePreference_returnFalse() {
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(mAppListGroup))
.isFalse();
verify(mMetricsFeatureProvider, never())
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_APP_ITEM);
verify(mMetricsFeatureProvider, never())
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_SYSTEM_ITEM);
}
@Test
public void testHandlePreferenceTreeClick_forAppEntry_returnTrue() {
doReturn(false).when(mBatteryHistEntry).isAppEntry();
doReturn(mBatteryDiffEntry).when(mPowerGaugePreference).getBatteryDiffEntry();
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(
mPowerGaugePreference)).isTrue();
verify(mMetricsFeatureProvider)
.action(
SettingsEnums.OPEN_BATTERY_USAGE,
SettingsEnums.ACTION_BATTERY_USAGE_SYSTEM_ITEM,
SettingsEnums.OPEN_BATTERY_USAGE,
/* package name */ "none",
/* percentage of total */ 0);
}
@Test
public void testHandlePreferenceTreeClick_forSystemEntry_returnTrue() {
mBatteryChartPreferenceController.mBatteryUtils = mBatteryUtils;
doReturn(true).when(mBatteryHistEntry).isAppEntry();
doReturn(mBatteryDiffEntry).when(mPowerGaugePreference).getBatteryDiffEntry();
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(
mPowerGaugePreference)).isTrue();
verify(mMetricsFeatureProvider)
.action(
SettingsEnums.OPEN_BATTERY_USAGE,
SettingsEnums.ACTION_BATTERY_USAGE_APP_ITEM,
SettingsEnums.OPEN_BATTERY_USAGE,
/* package name */ "none",
/* percentage of total */ 0);
}
@Test
public void testSetPreferenceSummary_setNullContentIfTotalUsageTimeIsZero() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0));
assertThat(pref.getSummary()).isNull();
}
@Test
public void testSetPreferenceSummary_setBackgroundUsageTimeOnly() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
assertThat(pref.getSummary()).isEqualTo("Background: 1 min");
}
@Test
public void testSetPreferenceSummary_setTotalUsageTimeLessThanAMinute() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 100,
/*backgroundUsageTimeInMs=*/ 200));
assertThat(pref.getSummary()).isEqualTo("Total: less than a min");
}
@Test
public void testSetPreferenceSummary_setTotalTimeIfBackgroundTimeLessThanAMinute() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ 200));
assertThat(pref.getSummary())
.isEqualTo("Total: 1 min\nBackground: less than a min");
}
@Test
public void testSetPreferenceSummary_setTotalAndBackgroundUsageTime() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
assertThat(pref.getSummary()).isEqualTo("Total: 2 min\nBackground: 1 min");
}
@Test
public void testSetPreferenceSummary_notAllowShownPackage_setSummayAsNull() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
final BatteryDiffEntry batteryDiffEntry =
spy(createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
doReturn("com.android.googlequicksearchbox").when(batteryDiffEntry)
.getPackageName();
mBatteryChartPreferenceController.setPreferenceSummary(pref, batteryDiffEntry);
assertThat(pref.getSummary()).isNull();
}
@Test
public void testValidateUsageTime_returnTrueIfBatteryDiffEntryIsValid() {
assertThat(BatteryChartPreferenceController.validateUsageTime(
createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS)))
.isTrue();
}
@Test
public void testValidateUsageTime_foregroundTimeExceedThreshold_returnFalse() {
assertThat(BatteryChartPreferenceController.validateUsageTime(
createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.HOUR_IN_MILLIS * 3,
/*backgroundUsageTimeInMs=*/ 0)))
.isFalse();
}
@Test
public void testValidateUsageTime_backgroundTimeExceedThreshold_returnFalse() {
assertThat(BatteryChartPreferenceController.validateUsageTime(
createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ DateUtils.HOUR_IN_MILLIS * 3)))
.isFalse();
}
@Test
public void testOnExpand_expandedIsTrue_addSystemEntriesToPreferenceGroup() {
doReturn(1).when(mAppListGroup).getPreferenceCount();
mBatteryChartPreferenceController.mSystemEntries.add(mBatteryDiffEntry);
doReturn("label").when(mBatteryDiffEntry).getAppLabel();
doReturn(mDrawable).when(mBatteryDiffEntry).getAppIcon();
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
mBatteryChartPreferenceController.onExpand(/*isExpanded=*/ true);
final ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
verify(mAppListGroup).addPreference(captor.capture());
// Verifies the added preference.
assertThat(captor.getValue().getKey()).isEqualTo(PREF_KEY);
verify(mMetricsFeatureProvider)
.action(
mContext,
SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM,
true /*isExpanded*/);
}
@Test
public void testOnExpand_expandedIsFalse_removeSystemEntriesFromPreferenceGroup() {
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
doReturn(mPowerGaugePreference).when(mAppListGroup).findPreference(PREF_KEY);
mBatteryChartPreferenceController.mSystemEntries.add(mBatteryDiffEntry);
// Verifies the cache is empty first.
assertThat(mBatteryChartPreferenceController.mPreferenceCache).isEmpty();
mBatteryChartPreferenceController.onExpand(/*isExpanded=*/ false);
verify(mAppListGroup).findPreference(PREF_KEY);
verify(mAppListGroup).removePreference(mPowerGaugePreference);
assertThat(mBatteryChartPreferenceController.mPreferenceCache).hasSize(1);
verify(mMetricsFeatureProvider)
.action(
mContext,
SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM,
false /*isExpanded*/);
}
@Test
public void testOnSelect_selectSpecificTimeSlot_logMetric() {
mBatteryChartPreferenceController.onSelect(1 /*slot index*/);
verify(mMetricsFeatureProvider)
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_TIME_SLOT);
}
@Test
public void testOnSelect_selectAll_logMetric() {
mBatteryChartPreferenceController.onSelect(
BatteryChartView.SELECTED_INDEX_ALL /*slot index*/);
verify(mMetricsFeatureProvider)
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_SHOW_ALL);
}
@Test
public void testRefreshCategoryTitle_setHourIntoBothTitleTextView() {
mBatteryChartPreferenceController = createController();
setUpBatteryHistoryKeys();
mBatteryChartPreferenceController.mAppListPrefGroup =
spy(new PreferenceCategory(mContext));
mBatteryChartPreferenceController.mExpandDividerPreference =
spy(new ExpandDividerPreference(mContext));
// Simulates select the first slot.
mBatteryChartPreferenceController.mTrapezoidIndex = 0;
mBatteryChartPreferenceController.refreshCategoryTitle();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// Verifies the title in the preference group.
verify(mBatteryChartPreferenceController.mAppListPrefGroup)
.setTitle(captor.capture());
assertThat(captor.getValue()).isNotEqualTo("App usage for past 24 hr");
// Verifies the title in the expandable divider.
captor = ArgumentCaptor.forClass(String.class);
verify(mBatteryChartPreferenceController.mExpandDividerPreference)
.setTitle(captor.capture());
assertThat(captor.getValue()).isNotEqualTo("System usage for past 24 hr");
}
@Test
public void testRefreshCategoryTitle_setLast24HrIntoBothTitleTextView() {
mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mAppListPrefGroup =
spy(new PreferenceCategory(mContext));
mBatteryChartPreferenceController.mExpandDividerPreference =
spy(new ExpandDividerPreference(mContext));
// Simulates select all condition.
mBatteryChartPreferenceController.mTrapezoidIndex =
BatteryChartView.SELECTED_INDEX_ALL;
mBatteryChartPreferenceController.refreshCategoryTitle();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// Verifies the title in the preference group.
verify(mBatteryChartPreferenceController.mAppListPrefGroup)
.setTitle(captor.capture());
assertThat(captor.getValue())
.isEqualTo("App usage for past 24 hr");
// Verifies the title in the expandable divider.
captor = ArgumentCaptor.forClass(String.class);
verify(mBatteryChartPreferenceController.mExpandDividerPreference)
.setTitle(captor.capture());
assertThat(captor.getValue())
.isEqualTo("System usage for past 24 hr");
}
@Test
public void testSetTimestampLabel_nullBatteryHistoryKeys_ignore() {
mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mBatteryHistoryKeys = null;
mBatteryChartPreferenceController.mBatteryChartView =
spy(new BatteryChartView(mContext));
mBatteryChartPreferenceController.setTimestampLabel();
verify(mBatteryChartPreferenceController.mBatteryChartView, never())
.setLatestTimestamp(anyLong());
}
@Test
public void testSetTimestampLabel_setExpectedTimestampData() {
mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mBatteryChartView =
spy(new BatteryChartView(mContext));
setUpBatteryHistoryKeys();
mBatteryChartPreferenceController.setTimestampLabel();
verify(mBatteryChartPreferenceController.mBatteryChartView)
.setLatestTimestamp(1619247636826L);
}
@Test
public void testSetTimestampLabel_withoutValidTimestamp_setExpectedTimestampData() {
mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mBatteryChartView =
spy(new BatteryChartView(mContext));
mBatteryChartPreferenceController.mBatteryHistoryKeys = new long[] {0L};
mBatteryChartPreferenceController.setTimestampLabel();
verify(mBatteryChartPreferenceController.mBatteryChartView)
.setLatestTimestamp(anyLong());
}
@Test
public void testOnSaveInstanceState_restoreSelectedIndexAndExpandState() {
final int expectedIndex = 1;
final boolean isExpanded = true;
final Bundle bundle = new Bundle();
mBatteryChartPreferenceController.mTrapezoidIndex = expectedIndex;
mBatteryChartPreferenceController.mIsExpanded = isExpanded;
mBatteryChartPreferenceController.onSaveInstanceState(bundle);
// Replaces the original controller with other values.
mBatteryChartPreferenceController.mTrapezoidIndex = -1;
mBatteryChartPreferenceController.mIsExpanded = false;
mBatteryChartPreferenceController.onCreate(bundle);
mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap());
assertThat(mBatteryChartPreferenceController.mTrapezoidIndex)
.isEqualTo(expectedIndex);
assertThat(mBatteryChartPreferenceController.mIsExpanded).isTrue();
}
@Test
public void testIsValidToShowSummary_returnExpectedResult() {
assertThat(mBatteryChartPreferenceController
.isValidToShowSummary("com.google.android.apps.scone"))
.isTrue();
// Verifies the item which is defined in the array list.
assertThat(mBatteryChartPreferenceController
.isValidToShowSummary("com.android.googlequicksearchbox"))
.isFalse();
}
@Test
public void testIsValidToShowEntry_returnExpectedResult() {
assertThat(mBatteryChartPreferenceController
.isValidToShowEntry("com.google.android.apps.scone"))
.isTrue();
// Verifies the items which are defined in the array list.
assertThat(mBatteryChartPreferenceController
.isValidToShowEntry("com.android.gms.persistent"))
.isFalse();
}
private static Map<Long, Map<String, BatteryHistEntry>> createBatteryHistoryMap() {
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = new HashMap<>();
for (int index = 0; index < DESIRED_HISTORY_SIZE; index++) {
final ContentValues values = new ContentValues();
values.put("batteryLevel", Integer.valueOf(100 - index));
final BatteryHistEntry entry = new BatteryHistEntry(values);
final Map<String, BatteryHistEntry> entryMap = new HashMap<>();
entryMap.put("fake_entry_key" + index, entry);
batteryHistoryMap.put(Long.valueOf(index + 1), entryMap);
}
return batteryHistoryMap;
}
private BatteryDiffEntry createBatteryDiffEntry(
long foregroundUsageTimeInMs, long backgroundUsageTimeInMs) {
return new BatteryDiffEntry(
mContext, foregroundUsageTimeInMs, backgroundUsageTimeInMs,
/*consumePower=*/ 0, mBatteryHistEntry);
}
private void setUpBatteryHistoryKeys() {
mBatteryChartPreferenceController.mBatteryHistoryKeys =
new long[] {1619196786769L, 0L, 1619247636826L};
ConvertUtils.utcToLocalTimeHour(
mContext, /*timestamp=*/ 0, /*is24HourFormat=*/ false);
}
private BatteryChartPreferenceController createController() {
final BatteryChartPreferenceController controller =
new BatteryChartPreferenceController(
mContext, "app_list", /*lifecycle=*/ null,
mSettingsActivity, mFragment);
controller.mPrefContext = mContext;
return controller;
}
}

View File

@@ -1,234 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.android.settings.fuelgauge;
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.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Context;
import android.os.LocaleList;
import android.view.accessibility.AccessibilityManager;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Locale;
@RunWith(RobolectricTestRunner.class)
public final class BatteryChartViewTest {
private Context mContext;
private BatteryChartView mBatteryChartView;
private FakeFeatureFactory mFeatureFactory;
private PowerUsageFeatureProvider mPowerUsageFeatureProvider;
@Mock private AccessibilityServiceInfo mockAccessibilityServiceInfo;
@Mock private AccessibilityManager mockAccessibilityManager;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mFeatureFactory = FakeFeatureFactory.setupForTest();
mPowerUsageFeatureProvider = mFeatureFactory.powerUsageFeatureProvider;
mContext = spy(RuntimeEnvironment.application);
mContext.getResources().getConfiguration().setLocales(
new LocaleList(new Locale("en_US")));
mBatteryChartView = new BatteryChartView(mContext);
doReturn(mockAccessibilityManager).when(mContext)
.getSystemService(AccessibilityManager.class);
doReturn("TalkBackService").when(mockAccessibilityServiceInfo).getId();
doReturn(Arrays.asList(mockAccessibilityServiceInfo))
.when(mockAccessibilityManager)
.getEnabledAccessibilityServiceList(anyInt());
}
@Test
public void testIsAccessibilityEnabled_disable_returnFalse() {
doReturn(false).when(mockAccessibilityManager).isEnabled();
assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isFalse();
}
@Test
public void testIsAccessibilityEnabled_emptyInfo_returnFalse() {
doReturn(true).when(mockAccessibilityManager).isEnabled();
doReturn(new ArrayList<AccessibilityServiceInfo>())
.when(mockAccessibilityManager)
.getEnabledAccessibilityServiceList(anyInt());
assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isFalse();
}
@Test
public void testIsAccessibilityEnabled_validServiceId_returnTrue() {
doReturn(true).when(mockAccessibilityManager).isEnabled();
assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isTrue();
}
@Test
public void testSetSelectedIndex_invokesCallback() {
final int selectedIndex[] = new int[1];
final int expectedIndex = 2;
mBatteryChartView.mSelectedIndex = 1;
mBatteryChartView.setOnSelectListener(
trapezoidIndex -> {
selectedIndex[0] = trapezoidIndex;
});
mBatteryChartView.setSelectedIndex(expectedIndex);
assertThat(mBatteryChartView.mSelectedIndex)
.isEqualTo(expectedIndex);
assertThat(selectedIndex[0]).isEqualTo(expectedIndex);
}
@Test
public void testSetSelectedIndex_sameIndex_notInvokesCallback() {
final int selectedIndex[] = new int[1];
final int expectedIndex = 1;
mBatteryChartView.mSelectedIndex = expectedIndex;
mBatteryChartView.setOnSelectListener(
trapezoidIndex -> {
selectedIndex[0] = trapezoidIndex;
});
mBatteryChartView.setSelectedIndex(expectedIndex);
assertThat(selectedIndex[0]).isNotEqualTo(expectedIndex);
}
@Test
public void testClickable_isChartGraphSlotsEnabledIsFalse_notClickable() {
mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(false);
mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isFalse();
assertThat(mBatteryChartView.mTrapezoidCurvePaint).isNotNull();
}
@Test
public void testClickable_accessibilityIsDisabled_clickable() {
mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(true);
doReturn(false).when(mockAccessibilityManager).isEnabled();
mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isTrue();
assertThat(mBatteryChartView.mTrapezoidCurvePaint).isNull();
}
@Test
public void testClickable_accessibilityIsEnabledWithoutValidId_clickable() {
mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(true);
doReturn(true).when(mockAccessibilityManager).isEnabled();
doReturn(new ArrayList<AccessibilityServiceInfo>())
.when(mockAccessibilityManager)
.getEnabledAccessibilityServiceList(anyInt());
mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isTrue();
assertThat(mBatteryChartView.mTrapezoidCurvePaint).isNull();
}
@Test
public void testClickable_accessibilityIsEnabledWithValidId_notClickable() {
mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(true);
doReturn(true).when(mockAccessibilityManager).isEnabled();
mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isFalse();
assertThat(mBatteryChartView.mTrapezoidCurvePaint).isNotNull();
}
@Test
public void testClickable_restoreFromNonClickableState() {
final int[] levels = new int[13];
for (int index = 0; index < levels.length; index++) {
levels[index] = index + 1;
}
mBatteryChartView.setTrapezoidCount(12);
mBatteryChartView.setLevels(levels);
mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(true);
doReturn(true).when(mockAccessibilityManager).isEnabled();
mBatteryChartView.onAttachedToWindow();
// Ensures the testing environment is correct.
assertThat(mBatteryChartView.isClickable()).isFalse();
// Turns off accessibility service.
doReturn(false).when(mockAccessibilityManager).isEnabled();
mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isTrue();
}
@Test
public void testOnAttachedToWindow_addAccessibilityStateChangeListener() {
mBatteryChartView.onAttachedToWindow();
verify(mockAccessibilityManager)
.addAccessibilityStateChangeListener(mBatteryChartView);
}
@Test
public void testOnDetachedFromWindow_removeAccessibilityStateChangeListener() {
mBatteryChartView.onAttachedToWindow();
mBatteryChartView.mHandler.postDelayed(
mBatteryChartView.mUpdateClickableStateRun, 1000);
mBatteryChartView.onDetachedFromWindow();
verify(mockAccessibilityManager)
.removeAccessibilityStateChangeListener(mBatteryChartView);
assertThat(mBatteryChartView.mHandler.hasCallbacks(
mBatteryChartView.mUpdateClickableStateRun))
.isFalse();
}
@Test
public void testOnAccessibilityStateChanged_postUpdateStateRunnable() {
mBatteryChartView.mHandler = spy(mBatteryChartView.mHandler);
mBatteryChartView.onAccessibilityStateChanged(/*enabled=*/ true);
verify(mBatteryChartView.mHandler)
.removeCallbacks(mBatteryChartView.mUpdateClickableStateRun);
verify(mBatteryChartView.mHandler)
.postDelayed(mBatteryChartView.mUpdateClickableStateRun, 500L);
}
}

View File

@@ -249,6 +249,8 @@ public class BatteryInfoTest {
@Test
public void testGetBatteryInfo_chargingWithOverheated_updateChargeLabel() {
final String expectedString =
mContext.getString(R.string.battery_tip_limited_temporarily_title);
doReturn(TEST_CHARGE_TIME_REMAINING)
.when(mBatteryUsageStats)
.getChargeTimeRemainingMs();
@@ -260,7 +262,7 @@ public class BatteryInfoTest {
false /* shortString */);
assertThat(info.isOverheated).isTrue();
assertThat(info.chargeLabel).isEqualTo("50% - Charging temporarily limited");
assertThat(info.chargeLabel.toString()).contains(expectedString);
}
// Make our battery stats return a sequence of battery events.

View File

@@ -22,26 +22,43 @@ import static com.android.settings.fuelgauge.BatteryOptimizeUtils.MODE_UNRESTRIC
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.content.pm.ParceledListSlice;
import android.content.pm.UserInfo;
import android.os.UserManager;
import android.util.ArraySet;
import com.android.settingslib.fuelgauge.PowerAllowlistBackend;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
@RunWith(RobolectricTestRunner.class)
@@ -50,9 +67,11 @@ public class BatteryOptimizeUtilsTest {
private static final int UID = 12345;
private static final String PACKAGE_NAME = "com.android.app";
@Mock BatteryUtils mMockBatteryUtils;
@Mock AppOpsManager mMockAppOpsManager;
@Mock PowerAllowlistBackend mMockBackend;
@Mock private BatteryUtils mMockBatteryUtils;
@Mock private AppOpsManager mMockAppOpsManager;
@Mock private PowerAllowlistBackend mMockBackend;
@Mock private IPackageManager mMockIPackageManager;
@Mock private UserManager mMockUserManager;
private Context mContext;
private BatteryOptimizeUtils mBatteryOptimizeUtils;
@@ -68,6 +87,7 @@ public class BatteryOptimizeUtilsTest {
// Sets the default mode as MODE_RESTRICTED.
mBatteryOptimizeUtils.mMode = AppOpsManager.MODE_IGNORED;
mBatteryOptimizeUtils.mAllowListed = false;
doReturn(mMockUserManager).when(mContext).getSystemService(UserManager.class);
}
@Test
@@ -135,9 +155,7 @@ public class BatteryOptimizeUtilsTest {
mBatteryOptimizeUtils.setAppUsageState(MODE_RESTRICTED);
TimeUnit.SECONDS.sleep(1);
verify(mMockBatteryUtils).setForceAppStandby(UID,
PACKAGE_NAME, AppOpsManager.MODE_IGNORED);
verify(mMockBackend).removeApp(PACKAGE_NAME);
verifySetAppOptimizationMode(AppOpsManager.MODE_IGNORED, /* allowListed */ false);
}
@Test
@@ -145,9 +163,7 @@ public class BatteryOptimizeUtilsTest {
mBatteryOptimizeUtils.setAppUsageState(MODE_UNRESTRICTED);
TimeUnit.SECONDS.sleep(1);
verify(mMockBatteryUtils).setForceAppStandby(UID,
PACKAGE_NAME, AppOpsManager.MODE_ALLOWED);
verify(mMockBackend).addApp(PACKAGE_NAME);
verifySetAppOptimizationMode(AppOpsManager.MODE_ALLOWED, /* allowListed */ true);
}
@Test
@@ -155,9 +171,7 @@ public class BatteryOptimizeUtilsTest {
mBatteryOptimizeUtils.setAppUsageState(MODE_OPTIMIZED);
TimeUnit.SECONDS.sleep(1);
verify(mMockBatteryUtils).setForceAppStandby(UID,
PACKAGE_NAME, AppOpsManager.MODE_ALLOWED);
verify(mMockBackend).removeApp(PACKAGE_NAME);
verifySetAppOptimizationMode(AppOpsManager.MODE_ALLOWED, /* allowListed */ false);
}
@Test
@@ -172,4 +186,148 @@ public class BatteryOptimizeUtilsTest {
verifyNoInteractions(mMockBackend);
verifyNoInteractions(mMockBatteryUtils);
}
@Test
public void testGetInstalledApplications_returnEmptyArray() {
assertTrue(BatteryOptimizeUtils.getInstalledApplications(mContext, mMockIPackageManager)
.isEmpty());
}
@Test
public void testGetInstalledApplications_returnNull() throws Exception {
final UserInfo userInfo =
new UserInfo(/*userId=*/ 0, /*userName=*/ "google", /*flag=*/ 0);
doReturn(Arrays.asList(userInfo)).when(mMockUserManager).getProfiles(anyInt());
doThrow(new RuntimeException())
.when(mMockIPackageManager)
.getInstalledApplications(anyLong(), anyInt());
assertNull(BatteryOptimizeUtils.getInstalledApplications(mContext, mMockIPackageManager));
}
@Test
public void testGetInstalledApplications_returnInstalledApps() throws Exception {
final UserInfo userInfo =
new UserInfo(/*userId=*/ 0, /*userName=*/ "google", /*flag=*/ 0);
doReturn(Arrays.asList(userInfo)).when(mMockUserManager).getProfiles(anyInt());
final ApplicationInfo applicationInfo1 = new ApplicationInfo();
applicationInfo1.enabled = true;
applicationInfo1.uid = 1;
final ApplicationInfo applicationInfo2 = new ApplicationInfo();
applicationInfo2.enabled = false;
applicationInfo2.uid = 2;
applicationInfo2.enabledSetting = PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
final ApplicationInfo applicationInfo3 = new ApplicationInfo();
applicationInfo3.enabled = false;
applicationInfo3.uid = 3;
applicationInfo3.enabledSetting = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
final ApplicationInfo applicationInfo4 = new ApplicationInfo();
applicationInfo4.enabled = true;
applicationInfo4.uid = 4;
applicationInfo4.enabledSetting = PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
doReturn(new ParceledListSlice<ApplicationInfo>(
Arrays.asList(applicationInfo1, applicationInfo2, applicationInfo3, applicationInfo4)))
.when(mMockIPackageManager)
.getInstalledApplications(anyLong(), anyInt());
final ArraySet<ApplicationInfo> applications =
BatteryOptimizeUtils.getInstalledApplications(mContext, mMockIPackageManager);
assertThat(applications.size()).isEqualTo(3);
// applicationInfo3 should be filtered.
assertTrue(applications.contains(applicationInfo1));
assertTrue(applications.contains(applicationInfo2));
assertFalse(applications.contains(applicationInfo3));
assertTrue(applications.contains(applicationInfo4));
}
@Test
public void testResetAppOptimizationMode_Optimized_verifyAction() throws Exception {
runTestForResetWithMode(
AppOpsManager.MODE_ALLOWED, /* allowListed */ false,
/* isSystemOrDefaultApp */ false);
verifyNoInteractions(mMockBatteryUtils);
final InOrder inOrder = inOrder(mMockBackend);
inOrder.verify(mMockBackend).refreshList();
inOrder.verify(mMockBackend).isAllowlisted(PACKAGE_NAME);
verifyNoMoreInteractions(mMockBackend);
}
@Test
public void testResetAppOptimizationMode_SystemOrDefault_verifyAction() throws Exception {
runTestForResetWithMode(
AppOpsManager.MODE_ALLOWED, /* allowListed */ true,
/* isSystemOrDefaultApp */ true);
verifyNoInteractions(mMockBatteryUtils);
final InOrder inOrder = inOrder(mMockBackend);
inOrder.verify(mMockBackend).refreshList();
inOrder.verify(mMockBackend).isAllowlisted(PACKAGE_NAME);
inOrder.verify(mMockBackend).isSysAllowlisted(PACKAGE_NAME);
verifyNoMoreInteractions(mMockBackend);
}
@Test
public void testResetAppOptimizationMode_Restricted_verifyAction() throws Exception {
runTestForResetWithMode(
AppOpsManager.MODE_IGNORED, /* allowListed */ false,
/* isSystemOrDefaultApp */ false);
verifySetAppOptimizationMode(AppOpsManager.MODE_ALLOWED, /* allowListed */ false);
}
@Test
public void testResetAppOptimizationMode_Unrestricted_verifyAction() throws Exception {
runTestForResetWithMode(
AppOpsManager.MODE_ALLOWED, /* allowListed */ true,
/* isSystemOrDefaultApp */ false);
verifySetAppOptimizationMode(AppOpsManager.MODE_ALLOWED, /* allowListed */ false);
}
private void runTestForResetWithMode(
int appStandbyMode, boolean allowListed, boolean isSystemOrDefaultApp)
throws Exception {
final UserInfo userInfo =
new UserInfo(/*userId=*/ 0, /*userName=*/ "google", /*flag=*/ 0);
doReturn(Arrays.asList(userInfo)).when(mMockUserManager).getProfiles(anyInt());
final ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.uid = UID;
applicationInfo.packageName = PACKAGE_NAME;
applicationInfo.enabled = true;
doReturn(new ParceledListSlice<ApplicationInfo>(
Arrays.asList(applicationInfo)))
.when(mMockIPackageManager)
.getInstalledApplications(anyLong(), anyInt());
doReturn(appStandbyMode)
.when(mMockAppOpsManager)
.checkOpNoThrow(anyInt(), anyInt(), anyString());
doReturn(allowListed)
.when(mMockBackend)
.isAllowlisted(anyString());
doReturn(isSystemOrDefaultApp)
.when(mMockBackend)
.isSysAllowlisted(anyString());
doReturn(isSystemOrDefaultApp)
.when(mMockBackend)
.isDefaultActiveApp(anyString());
BatteryOptimizeUtils.resetAppOptimizationMode(
mContext, mMockIPackageManager, mMockAppOpsManager, mMockBackend,
mMockBatteryUtils);
TimeUnit.SECONDS.sleep(1);
}
private void verifySetAppOptimizationMode(int appStandbyMode, boolean allowListed) {
verify(mMockBatteryUtils).setForceAppStandby(UID, PACKAGE_NAME, appStandbyMode);
if (allowListed) {
verify(mMockBackend).addApp(PACKAGE_NAME);
} else {
verify(mMockBackend).removeApp(PACKAGE_NAME);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2017 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -23,7 +23,6 @@ import static org.mockito.Mockito.when;
import com.android.settings.SettingsActivity;
import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.fuelgauge.batterytip.actions.BatteryDefenderAction;
import com.android.settings.fuelgauge.batterytip.actions.OpenBatterySaverAction;
import com.android.settings.fuelgauge.batterytip.actions.OpenRestrictAppFragmentAction;
import com.android.settings.fuelgauge.batterytip.actions.RestrictAppAction;
@@ -105,10 +104,10 @@ public class BatteryTipUtilsTest {
@Test
public void
testGetActionForBatteryTip_typeBatteryDefenderStateNew_returnActionBatteryDefender() {
testGetActionForBatteryTip_typeBatteryDefenderStateNew_returnNullAction() {
when(mBatteryDefenderTip.getState()).thenReturn(BatteryTip.StateType.NEW);
assertThat(BatteryTipUtils.getActionForBatteryTip(mBatteryDefenderTip, mSettingsActivity,
mFragment)).isInstanceOf(BatteryDefenderAction.class);
mFragment)).isNull();
}
}

View File

@@ -18,6 +18,8 @@ package com.android.settings.fuelgauge.batterytip.detectors;
import static com.google.common.truth.Truth.assertThat;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.fuelgauge.BatteryInfo;
import com.android.settings.fuelgauge.batterytip.tips.BatteryTip;
@@ -41,7 +43,8 @@ public class BatteryDefenderDetectorTest {
mBatteryInfo.discharging = false;
mBatteryDefenderDetector = new BatteryDefenderDetector(mBatteryInfo);
mBatteryDefenderDetector = new BatteryDefenderDetector(
mBatteryInfo, ApplicationProvider.getApplicationContext());
}
@Test

View File

@@ -17,13 +17,25 @@ package com.android.settings.fuelgauge.batterytip.tips;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.settings.SettingsEnums;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;
import androidx.preference.Preference;
import com.android.settings.R;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.widget.CardPreference;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import org.junit.Before;
@@ -33,6 +45,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowLog;
@RunWith(RobolectricTestRunner.class)
public class BatteryDefenderTipTest {
@@ -43,6 +56,8 @@ public class BatteryDefenderTipTest {
private MetricsFeatureProvider mMetricsFeatureProvider;
@Mock private BatteryTip mBatteryTip;
@Mock private Preference mPreference;
@Mock private CardPreference mCardPreference;
@Before
public void setUp() {
@@ -52,6 +67,9 @@ public class BatteryDefenderTipTest {
mMetricsFeatureProvider = mFeatureFactory.metricsFeatureProvider;
mContext = RuntimeEnvironment.application;
mBatteryDefenderTip = new BatteryDefenderTip(BatteryTip.StateType.NEW);
when(mPreference.getContext()).thenReturn(mContext);
when(mCardPreference.getContext()).thenReturn(mContext);
}
@Test
@@ -61,11 +79,19 @@ public class BatteryDefenderTipTest {
}
@Test
public void getSummary_showSummary() {
public void getSummary_notExtraDefended_showNonExtraDefendedSummary() {
assertThat(mBatteryDefenderTip.getSummary(mContext))
.isEqualTo(mContext.getString(R.string.battery_tip_limited_temporarily_summary));
}
@Test
public void getSummary_extraDefended_showExtraDefendedSummary() {
BatteryDefenderTip defenderTip = new BatteryDefenderTip(
BatteryTip.StateType.NEW, /* extraDefended= */ true);
assertThat(defenderTip.getSummary(mContext).toString()).isEqualTo("12%");
}
@Test
public void getIcon_showIcon() {
assertThat(mBatteryDefenderTip.getIconId())
@@ -80,4 +106,94 @@ public class BatteryDefenderTipTest {
verify(mMetricsFeatureProvider).action(mContext,
SettingsEnums.ACTION_BATTERY_DEFENDER_TIP, mBatteryTip.mState);
}
@Test
public void updatePreference_castFail_logErrorMessage() {
mBatteryDefenderTip.updatePreference(mPreference);
assertThat(getLastErrorLog()).isEqualTo("cast Preference to CardPreference failed");
}
@Test
public void updatePreference_shouldSetPrimaryButtonText() {
String expectedText = mContext.getString(R.string.battery_tip_charge_to_full_button);
mBatteryDefenderTip.updatePreference(mCardPreference);
verify(mCardPreference).setPrimaryButtonText(expectedText);
}
@Test
public void updatePreference_shouldSetSecondaryButtonText() {
String expected = mContext.getString(R.string.learn_more);
mBatteryDefenderTip.updatePreference(mCardPreference);
verify(mCardPreference).setSecondaryButtonText(expected);
}
@Test
public void updatePreference_shouldSetSecondaryButtonVisible() {
mBatteryDefenderTip.updatePreference(mCardPreference);
verify(mCardPreference).setSecondaryButtonVisible(true);
}
@Test
public void updatePreference_whenCharging_setPrimaryButtonVisibleToBeTrue() {
fakeDeviceIsCharging(true);
mBatteryDefenderTip.updatePreference(mCardPreference);
verify(mCardPreference).setPrimaryButtonVisible(true);
}
@Test
public void updatePreference_whenNotCharging_setPrimaryButtonVisibleToBeFalse() {
fakeDeviceIsCharging(false);
mBatteryDefenderTip.updatePreference(mCardPreference);
verify(mCardPreference).setPrimaryButtonVisible(false);
}
@Test
public void updatePreference_whenGetChargingStatusFailed_setPrimaryButtonVisibleToBeFalse() {
fakeGetChargingStatusFailed();
mBatteryDefenderTip.updatePreference(mCardPreference);
verify(mCardPreference).setPrimaryButtonVisible(false);
}
private void fakeDeviceIsCharging(boolean charging) {
int charged = charging ? 1 : 0; // 1 means charging, 0:not charging
Intent batteryChangedIntent = new Intent(Intent.ACTION_BATTERY_CHANGED);
batteryChangedIntent.putExtra(BatteryManager.EXTRA_PLUGGED, charged);
Context mockContext = mock(Context.class);
when(mockContext.getString(anyInt())).thenReturn("fake_string");
when(mCardPreference.getContext()).thenReturn(mockContext);
when(mockContext.registerReceiver(eq(null), any(IntentFilter.class)))
.thenReturn(batteryChangedIntent);
}
private void fakeGetChargingStatusFailed() {
Context mockContext = mock(Context.class);
when(mockContext.getString(anyInt())).thenReturn("fake_string");
when(mCardPreference.getContext()).thenReturn(mockContext);
when(mockContext.registerReceiver(eq(null), any(IntentFilter.class))).thenReturn(null);
}
private String getLastErrorLog() {
return ShadowLog.getLogsForTag(BatteryDefenderTip.class.getSimpleName()).stream()
.filter(log -> log.type == Log.ERROR)
.reduce((first, second) -> second)
.orElse(createErrorLog("No Error Log"))
.msg;
}
private ShadowLog.LogItem createErrorLog(String msg) {
return new ShadowLog.LogItem(Log.ERROR, "tag", msg, null);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2017 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
@@ -35,6 +35,7 @@ import androidx.preference.PreferenceGroup;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
@@ -81,9 +82,9 @@ public class BatteryAppListPreferenceControllerTest {
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mContext.getApplicationContext()).thenReturn(mContext);
when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mUserManager.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {});
when(mUserManager.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[]{});
when(mFeatureFactory.powerUsageFeatureProvider.getHideApplicationSummary(mContext))
.thenReturn(new String[] {"com.android.googlequicksearchbox"});
.thenReturn(new String[]{"com.android.googlequicksearchbox"});
mPreference = new PowerGaugePreference(mContext);

View File

@@ -0,0 +1,737 @@
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import android.app.settings.SettingsEnums;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.LocaleList;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.LinearLayout;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceGroup;
import com.android.settings.SettingsActivity;
import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
@RunWith(RobolectricTestRunner.class)
public final class BatteryChartPreferenceControllerTest {
private static final String PREF_KEY = "pref_key";
private static final String PREF_SUMMARY = "fake preference summary";
@Mock
private InstrumentedPreferenceFragment mFragment;
@Mock
private SettingsActivity mSettingsActivity;
@Mock
private PreferenceGroup mAppListGroup;
@Mock
private Drawable mDrawable;
@Mock
private BatteryHistEntry mBatteryHistEntry;
@Mock
private BatteryChartView mDailyChartView;
@Mock
private BatteryChartView mHourlyChartView;
@Mock
private PowerGaugePreference mPowerGaugePreference;
@Mock
private BatteryUtils mBatteryUtils;
@Mock
private LinearLayout.LayoutParams mLayoutParams;
private Context mContext;
private FakeFeatureFactory mFeatureFactory;
private BatteryDiffEntry mBatteryDiffEntry;
private MetricsFeatureProvider mMetricsFeatureProvider;
private BatteryChartPreferenceController mBatteryChartPreferenceController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Locale.setDefault(new Locale("en_US"));
org.robolectric.shadows.ShadowSettings.set24HourTimeFormat(false);
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
mFeatureFactory = FakeFeatureFactory.setupForTest();
mMetricsFeatureProvider = mFeatureFactory.metricsFeatureProvider;
mContext = spy(RuntimeEnvironment.application);
final Resources resources = spy(mContext.getResources());
resources.getConfiguration().setLocales(new LocaleList(new Locale("en_US")));
doReturn(resources).when(mContext).getResources();
doReturn(new String[]{"com.android.googlequicksearchbox"})
.when(mFeatureFactory.powerUsageFeatureProvider)
.getHideApplicationSummary(mContext);
doReturn(new String[]{"com.android.gms.persistent"})
.when(mFeatureFactory.powerUsageFeatureProvider)
.getHideApplicationEntries(mContext);
doReturn(mLayoutParams).when(mDailyChartView).getLayoutParams();
mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mPrefContext = mContext;
mBatteryChartPreferenceController.mAppListPrefGroup = mAppListGroup;
mBatteryChartPreferenceController.mDailyChartView = mDailyChartView;
mBatteryChartPreferenceController.mHourlyChartView = mHourlyChartView;
mBatteryDiffEntry = new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 1,
/*backgroundUsageTimeInMs=*/ 2,
/*consumePower=*/ 3,
mBatteryHistEntry);
mBatteryDiffEntry = spy(mBatteryDiffEntry);
// Adds fake testing data.
BatteryDiffEntry.sResourceCache.put(
"fakeBatteryDiffEntryKey",
new BatteryEntry.NameAndIcon("fakeName", /*icon=*/ null, /*iconId=*/ 1));
}
@Test
public void onDestroy_activityIsChanging_clearBatteryEntryCache() {
doReturn(true).when(mSettingsActivity).isChangingConfigurations();
// Ensures the testing environment is correct.
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
mBatteryChartPreferenceController.onDestroy();
assertThat(BatteryDiffEntry.sResourceCache).isEmpty();
}
@Test
public void onDestroy_activityIsNotChanging_notClearBatteryEntryCache() {
doReturn(false).when(mSettingsActivity).isChangingConfigurations();
// Ensures the testing environment is correct.
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
mBatteryChartPreferenceController.onDestroy();
assertThat(BatteryDiffEntry.sResourceCache).isNotEmpty();
}
@Test
public void onDestroy_clearPreferenceCache() {
// Ensures the testing environment is correct.
mBatteryChartPreferenceController.mPreferenceCache.put(
PREF_KEY, mPowerGaugePreference);
assertThat(mBatteryChartPreferenceController.mPreferenceCache).hasSize(1);
mBatteryChartPreferenceController.onDestroy();
// Verifies the result after onDestroy.
assertThat(mBatteryChartPreferenceController.mPreferenceCache).isEmpty();
}
@Test
public void onDestroy_removeAllPreferenceFromPreferenceGroup() {
mBatteryChartPreferenceController.onDestroy();
verify(mAppListGroup).removeAll();
}
@Test
public void setBatteryChartViewModel_6Hours() {
reset(mHourlyChartView);
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(6));
verify(mDailyChartView, atLeastOnce()).setVisibility(View.GONE);
verify(mHourlyChartView, atLeastOnce()).setVisibility(View.VISIBLE);
// Ignore fast refresh ui from the data processor callback.
verify(mHourlyChartView, atLeast(0)).setViewModel(null);
verify(mHourlyChartView, atLeastOnce()).setViewModel(new BatteryChartViewModel(
List.of(100, 97, 95),
List.of(1619251200000L /* 8 AM */,
1619258400000L /* 10 AM */,
1619265600000L /* 12 PM */),
BatteryChartViewModel.AxisLabelPosition.BETWEEN_TRAPEZOIDS,
mBatteryChartPreferenceController.mHourlyChartLabelTextGenerator));
}
@Test
public void setBatteryChartViewModel_60Hours() {
BatteryChartViewModel expectedDailyViewModel = new BatteryChartViewModel(
List.of(100, 83, 59, 41),
// "Sat", "Sun", "Mon", "Mon"
List.of(1619251200000L /* Sat */,
1619308800000L /* Sun */,
1619395200000L /* Mon */,
1619460000000L /* Mon */),
BatteryChartViewModel.AxisLabelPosition.CENTER_OF_TRAPEZOIDS,
mBatteryChartPreferenceController.mDailyChartLabelTextGenerator);
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(60));
verify(mDailyChartView, atLeastOnce()).setVisibility(View.VISIBLE);
verify(mHourlyChartView, atLeastOnce()).setVisibility(View.GONE);
verify(mDailyChartView).setViewModel(expectedDailyViewModel);
reset(mDailyChartView);
reset(mHourlyChartView);
doReturn(mLayoutParams).when(mDailyChartView).getLayoutParams();
mBatteryChartPreferenceController.mDailyChartIndex = 0;
mBatteryChartPreferenceController.refreshUi();
verify(mDailyChartView).setVisibility(View.VISIBLE);
verify(mHourlyChartView).setVisibility(View.VISIBLE);
expectedDailyViewModel.setSelectedIndex(0);
verify(mDailyChartView).setViewModel(expectedDailyViewModel);
verify(mHourlyChartView).setViewModel(new BatteryChartViewModel(
List.of(100, 97, 95, 93, 91, 89, 87, 85, 83),
List.of(1619251200000L /* 8 AM */,
1619258400000L /* 10 AM */,
1619265600000L /* 12 PM */,
1619272800000L /* 2 PM */,
1619280000000L /* 4 PM */,
1619287200000L /* 6 PM */,
1619294400000L /* 8 PM */,
1619301600000L /* 10 PM */,
1619308800000L /* 12 AM */),
BatteryChartViewModel.AxisLabelPosition.BETWEEN_TRAPEZOIDS,
mBatteryChartPreferenceController.mHourlyChartLabelTextGenerator));
reset(mDailyChartView);
reset(mHourlyChartView);
doReturn(mLayoutParams).when(mDailyChartView).getLayoutParams();
mBatteryChartPreferenceController.mDailyChartIndex = 1;
mBatteryChartPreferenceController.mHourlyChartIndex = 6;
mBatteryChartPreferenceController.refreshUi();
verify(mDailyChartView).setVisibility(View.VISIBLE);
verify(mHourlyChartView).setVisibility(View.VISIBLE);
expectedDailyViewModel.setSelectedIndex(1);
verify(mDailyChartView).setViewModel(expectedDailyViewModel);
BatteryChartViewModel expectedHourlyViewModel = new BatteryChartViewModel(
List.of(83, 81, 79, 77, 75, 73, 71, 69, 67, 65, 63, 61, 59),
List.of(1619308800000L /* 12 AM */,
1619316000000L /* 2 AM */,
1619323200000L /* 4 AM */,
1619330400000L /* 6 AM */,
1619337600000L /* 8 AM */,
1619344800000L /* 10 AM */,
1619352000000L /* 12 PM */,
1619359200000L /* 2 PM */,
1619366400000L /* 4 PM */,
1619373600000L /* 6 PM */,
1619380800000L /* 8 PM */,
1619388000000L /* 10 PM */,
1619395200000L /* 12 AM */),
BatteryChartViewModel.AxisLabelPosition.BETWEEN_TRAPEZOIDS,
mBatteryChartPreferenceController.mHourlyChartLabelTextGenerator);
expectedHourlyViewModel.setSelectedIndex(6);
verify(mHourlyChartView).setViewModel(expectedHourlyViewModel);
reset(mDailyChartView);
reset(mHourlyChartView);
doReturn(mLayoutParams).when(mDailyChartView).getLayoutParams();
mBatteryChartPreferenceController.mDailyChartIndex = 2;
mBatteryChartPreferenceController.mHourlyChartIndex =
BatteryChartViewModel.SELECTED_INDEX_ALL;
mBatteryChartPreferenceController.refreshUi();
verify(mDailyChartView).setVisibility(View.VISIBLE);
verify(mHourlyChartView).setVisibility(View.VISIBLE);
expectedDailyViewModel.setSelectedIndex(2);
verify(mDailyChartView).setViewModel(expectedDailyViewModel);
verify(mHourlyChartView).setViewModel(new BatteryChartViewModel(
List.of(59, 57, 55, 53, 51, 49, 47, 45, 43, 41),
List.of(1619395200000L /* 12 AM */,
1619402400000L /* 2 AM */,
1619409600000L /* 4 AM */,
1619416800000L /* 6 AM */,
1619424000000L /* 8 AM */,
1619431200000L /* 10 AM */,
1619438400000L /* 12 PM */,
1619445600000L /* 2 PM */,
1619452800000L /* 4 PM */,
1619460000000L /* 6 PM */),
BatteryChartViewModel.AxisLabelPosition.BETWEEN_TRAPEZOIDS,
mBatteryChartPreferenceController.mHourlyChartLabelTextGenerator));
}
@Test
public void refreshUi_normalCase_returnTrue() {
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(6));
assertThat(mBatteryChartPreferenceController.refreshUi()).isTrue();
}
@Test
public void refreshUi_batteryIndexedMapIsNull_ignoreRefresh() {
mBatteryChartPreferenceController.setBatteryHistoryMap(null);
assertThat(mBatteryChartPreferenceController.refreshUi()).isFalse();
}
@Test
public void refreshUi_dailyChartViewIsNull_ignoreRefresh() {
mBatteryChartPreferenceController.mDailyChartView = null;
assertThat(mBatteryChartPreferenceController.refreshUi()).isFalse();
}
@Test
public void refreshUi_hourlyChartViewIsNull_ignoreRefresh() {
mBatteryChartPreferenceController.mHourlyChartView = null;
assertThat(mBatteryChartPreferenceController.refreshUi()).isFalse();
}
@Test
public void removeAndCacheAllPrefs_emptyContent_ignoreRemoveAll() {
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(6));
mBatteryChartPreferenceController.mBatteryUsageMap = createBatteryUsageMap();
doReturn(0).when(mAppListGroup).getPreferenceCount();
mBatteryChartPreferenceController.refreshUi();
verify(mAppListGroup, never()).removeAll();
}
@Test
public void removeAndCacheAllPrefs_buildCacheAndRemoveAllPreference() {
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(6));
mBatteryChartPreferenceController.mBatteryUsageMap = createBatteryUsageMap();
doReturn(1).when(mAppListGroup).getPreferenceCount();
doReturn(mPowerGaugePreference).when(mAppListGroup).getPreference(0);
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
doReturn(PREF_KEY).when(mPowerGaugePreference).getKey();
doReturn(mPowerGaugePreference).when(mAppListGroup).findPreference(PREF_KEY);
// Ensures the testing data is correct.
assertThat(mBatteryChartPreferenceController.mPreferenceCache).isEmpty();
mBatteryChartPreferenceController.refreshUi();
assertThat(mBatteryChartPreferenceController.mPreferenceCache.get(PREF_KEY))
.isEqualTo(mPowerGaugePreference);
verify(mAppListGroup).removeAll();
}
@Test
public void addPreferenceToScreen_emptyContent_ignoreAddPreference() {
mBatteryChartPreferenceController.addPreferenceToScreen(
new ArrayList<BatteryDiffEntry>());
verify(mAppListGroup, never()).addPreference(any());
}
@Test
public void addPreferenceToScreen_addPreferenceIntoScreen() {
final String appLabel = "fake app label";
doReturn(1).when(mAppListGroup).getPreferenceCount();
doReturn(mDrawable).when(mBatteryDiffEntry).getAppIcon();
doReturn(appLabel).when(mBatteryDiffEntry).getAppLabel();
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
doReturn(null).when(mAppListGroup).findPreference(PREF_KEY);
doReturn(false).when(mBatteryDiffEntry).validForRestriction();
mBatteryChartPreferenceController.addPreferenceToScreen(
Arrays.asList(mBatteryDiffEntry));
// Verifies the preference cache.
final PowerGaugePreference pref =
(PowerGaugePreference) mBatteryChartPreferenceController.mPreferenceCache
.get(PREF_KEY);
assertThat(pref).isNotNull();
// Verifies the added preference configuration.
verify(mAppListGroup).addPreference(pref);
assertThat(pref.getKey()).isEqualTo(PREF_KEY);
assertThat(pref.getTitle()).isEqualTo(appLabel);
assertThat(pref.getIcon()).isEqualTo(mDrawable);
assertThat(pref.getOrder()).isEqualTo(1);
assertThat(pref.getBatteryDiffEntry()).isSameInstanceAs(mBatteryDiffEntry);
assertThat(pref.isSingleLineTitle()).isTrue();
assertThat(pref.isEnabled()).isFalse();
}
@Test
public void addPreferenceToScreen_alreadyInScreen_notAddPreferenceAgain() {
final String appLabel = "fake app label";
doReturn(1).when(mAppListGroup).getPreferenceCount();
doReturn(mDrawable).when(mBatteryDiffEntry).getAppIcon();
doReturn(appLabel).when(mBatteryDiffEntry).getAppLabel();
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
doReturn(mPowerGaugePreference).when(mAppListGroup).findPreference(PREF_KEY);
mBatteryChartPreferenceController.addPreferenceToScreen(
Arrays.asList(mBatteryDiffEntry));
verify(mAppListGroup, never()).addPreference(any());
}
@Test
public void handlePreferenceTreeClick_notPowerGaugePreference_returnFalse() {
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(mAppListGroup))
.isFalse();
verify(mMetricsFeatureProvider, never())
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_APP_ITEM);
verify(mMetricsFeatureProvider, never())
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_SYSTEM_ITEM);
}
@Test
public void handlePreferenceTreeClick_forAppEntry_returnTrue() {
doReturn(false).when(mBatteryHistEntry).isAppEntry();
doReturn(mBatteryDiffEntry).when(mPowerGaugePreference).getBatteryDiffEntry();
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(
mPowerGaugePreference)).isTrue();
verify(mMetricsFeatureProvider)
.action(
SettingsEnums.OPEN_BATTERY_USAGE,
SettingsEnums.ACTION_BATTERY_USAGE_SYSTEM_ITEM,
SettingsEnums.OPEN_BATTERY_USAGE,
/* package name */ "none",
/* percentage of total */ 0);
}
@Test
public void handlePreferenceTreeClick_forSystemEntry_returnTrue() {
mBatteryChartPreferenceController.mBatteryUtils = mBatteryUtils;
doReturn(true).when(mBatteryHistEntry).isAppEntry();
doReturn(mBatteryDiffEntry).when(mPowerGaugePreference).getBatteryDiffEntry();
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(
mPowerGaugePreference)).isTrue();
verify(mMetricsFeatureProvider)
.action(
SettingsEnums.OPEN_BATTERY_USAGE,
SettingsEnums.ACTION_BATTERY_USAGE_APP_ITEM,
SettingsEnums.OPEN_BATTERY_USAGE,
/* package name */ "none",
/* percentage of total */ 0);
}
@Test
public void setPreferenceSummary_setNullContentIfTotalUsageTimeIsZero() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0));
assertThat(pref.getSummary()).isNull();
}
@Test
public void setPreferenceSummary_setBackgroundUsageTimeOnly() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
assertThat(pref.getSummary()).isEqualTo("Background: 1 min");
}
@Test
public void setPreferenceSummary_setTotalUsageTimeLessThanAMinute() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 100,
/*backgroundUsageTimeInMs=*/ 200));
assertThat(pref.getSummary()).isEqualTo("Total: less than a min");
}
@Test
public void setPreferenceSummary_setTotalTimeIfBackgroundTimeLessThanAMinute() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ 200));
assertThat(pref.getSummary())
.isEqualTo("Total: 1 min\nBackground: less than a min");
}
@Test
public void setPreferenceSummary_setTotalAndBackgroundUsageTime() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
assertThat(pref.getSummary()).isEqualTo("Total: 2 min\nBackground: 1 min");
}
@Test
public void setPreferenceSummary_notAllowShownPackage_setSummayAsNull() {
final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY);
final BatteryDiffEntry batteryDiffEntry =
spy(createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
doReturn("com.android.googlequicksearchbox").when(batteryDiffEntry)
.getPackageName();
mBatteryChartPreferenceController.setPreferenceSummary(pref, batteryDiffEntry);
assertThat(pref.getSummary()).isNull();
}
@Test
public void onExpand_expandedIsTrue_addSystemEntriesToPreferenceGroup() {
doReturn(1).when(mAppListGroup).getPreferenceCount();
mBatteryChartPreferenceController.mBatteryUsageMap = createBatteryUsageMap();
doReturn("label").when(mBatteryDiffEntry).getAppLabel();
doReturn(mDrawable).when(mBatteryDiffEntry).getAppIcon();
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
mBatteryChartPreferenceController.onExpand(/*isExpanded=*/ true);
final ArgumentCaptor<Preference> captor = ArgumentCaptor.forClass(Preference.class);
verify(mAppListGroup).addPreference(captor.capture());
// Verifies the added preference.
assertThat(captor.getValue().getKey()).isEqualTo(PREF_KEY);
verify(mMetricsFeatureProvider)
.action(
mContext,
SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM,
true /*isExpanded*/);
}
@Test
public void onExpand_expandedIsFalse_removeSystemEntriesFromPreferenceGroup() {
doReturn(PREF_KEY).when(mBatteryHistEntry).getKey();
doReturn(mPowerGaugePreference).when(mAppListGroup).findPreference(PREF_KEY);
mBatteryChartPreferenceController.mBatteryUsageMap = createBatteryUsageMap();
// Verifies the cache is empty first.
assertThat(mBatteryChartPreferenceController.mPreferenceCache).isEmpty();
mBatteryChartPreferenceController.onExpand(/*isExpanded=*/ false);
verify(mAppListGroup).findPreference(PREF_KEY);
verify(mAppListGroup).removePreference(mPowerGaugePreference);
assertThat(mBatteryChartPreferenceController.mPreferenceCache).hasSize(1);
verify(mMetricsFeatureProvider)
.action(
mContext,
SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM,
false /*isExpanded*/);
}
@Test
public void refreshCategoryTitle_setLastFullChargeIntoBothTitleTextView() {
mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mAppListPrefGroup =
spy(new PreferenceCategory(mContext));
mBatteryChartPreferenceController.mExpandDividerPreference =
spy(new ExpandDividerPreference(mContext));
// Simulates select all condition.
mBatteryChartPreferenceController.mDailyChartIndex =
BatteryChartViewModel.SELECTED_INDEX_ALL;
mBatteryChartPreferenceController.mHourlyChartIndex =
BatteryChartViewModel.SELECTED_INDEX_ALL;
mBatteryChartPreferenceController.refreshCategoryTitle();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// Verifies the title in the preference group.
verify(mBatteryChartPreferenceController.mAppListPrefGroup)
.setTitle(captor.capture());
assertThat(captor.getValue())
.isEqualTo("App usage since last full charge");
// Verifies the title in the expandable divider.
captor = ArgumentCaptor.forClass(String.class);
verify(mBatteryChartPreferenceController.mExpandDividerPreference)
.setTitle(captor.capture());
assertThat(captor.getValue())
.isEqualTo("System usage since last full charge");
}
@Test
public void selectedSlotText_selectAllDaysAllHours_returnNull() {
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(60));
mBatteryChartPreferenceController.mDailyChartIndex =
BatteryChartViewModel.SELECTED_INDEX_ALL;
mBatteryChartPreferenceController.mHourlyChartIndex =
BatteryChartViewModel.SELECTED_INDEX_ALL;
assertThat(mBatteryChartPreferenceController.getSlotInformation()).isEqualTo(null);
}
@Test
public void selectedSlotText_onlyOneDayDataSelectAllHours_returnNull() {
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(6));
mBatteryChartPreferenceController.mDailyChartIndex = 0;
mBatteryChartPreferenceController.mHourlyChartIndex =
BatteryChartViewModel.SELECTED_INDEX_ALL;
assertThat(mBatteryChartPreferenceController.getSlotInformation()).isEqualTo(null);
}
@Test
public void selectedSlotText_selectADayAllHours_onlyDayText() {
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(60));
mBatteryChartPreferenceController.mDailyChartIndex = 1;
mBatteryChartPreferenceController.mHourlyChartIndex =
BatteryChartViewModel.SELECTED_INDEX_ALL;
assertThat(mBatteryChartPreferenceController.getSlotInformation()).isEqualTo("Sunday");
}
@Test
public void selectedSlotText_onlyOneDayDataSelectAnHour_onlyHourText() {
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(6));
mBatteryChartPreferenceController.mDailyChartIndex = 0;
mBatteryChartPreferenceController.mHourlyChartIndex = 1;
assertThat(mBatteryChartPreferenceController.getSlotInformation()).isEqualTo(
"10 AM - 12 PM");
}
@Test
public void selectedSlotText_SelectADayAnHour_dayAndHourText() {
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(60));
mBatteryChartPreferenceController.mDailyChartIndex = 1;
mBatteryChartPreferenceController.mHourlyChartIndex = 8;
assertThat(mBatteryChartPreferenceController.getSlotInformation()).isEqualTo(
"Sunday 4 PM - 6 PM");
}
@Test
public void onSaveInstanceState_restoreSelectedIndexAndExpandState() {
final int expectedDailyIndex = 1;
final int expectedHourlyIndex = 2;
final boolean isExpanded = true;
final Bundle bundle = new Bundle();
mBatteryChartPreferenceController.mDailyChartIndex = expectedDailyIndex;
mBatteryChartPreferenceController.mHourlyChartIndex = expectedHourlyIndex;
mBatteryChartPreferenceController.mIsExpanded = isExpanded;
mBatteryChartPreferenceController.onSaveInstanceState(bundle);
// Replaces the original controller with other values.
mBatteryChartPreferenceController.mDailyChartIndex = -1;
mBatteryChartPreferenceController.mHourlyChartIndex = -1;
mBatteryChartPreferenceController.mIsExpanded = false;
mBatteryChartPreferenceController.onCreate(bundle);
mBatteryChartPreferenceController.setBatteryHistoryMap(createBatteryHistoryMap(25));
assertThat(mBatteryChartPreferenceController.mDailyChartIndex)
.isEqualTo(expectedDailyIndex);
assertThat(mBatteryChartPreferenceController.mHourlyChartIndex)
.isEqualTo(expectedHourlyIndex);
assertThat(mBatteryChartPreferenceController.mIsExpanded).isTrue();
}
@Test
public void isValidToShowSummary_returnExpectedResult() {
assertThat(mBatteryChartPreferenceController
.isValidToShowSummary("com.google.android.apps.scone"))
.isTrue();
// Verifies the item which is defined in the array list.
assertThat(mBatteryChartPreferenceController
.isValidToShowSummary("com.android.googlequicksearchbox"))
.isFalse();
}
@Test
public void getTotalHours_getExpectedResult() {
Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = createBatteryHistoryMap(60);
BatteryLevelData batteryLevelData = DataProcessor.getBatteryLevelData(mContext, null,
batteryHistoryMap, null);
final int totalHour = BatteryChartPreferenceController.getTotalHours(batteryLevelData);
// Only calculate the even hours.
assertThat(totalHour).isEqualTo(58);
}
private static Long generateTimestamp(int index) {
// "2021-04-23 07:00:00 UTC" + index hours
return 1619247600000L + index * DateUtils.HOUR_IN_MILLIS;
}
private static Map<Long, Map<String, BatteryHistEntry>> createBatteryHistoryMap(
int numOfHours) {
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = new HashMap<>();
for (int index = 0; index < numOfHours; index++) {
final ContentValues values = new ContentValues();
values.put("batteryLevel", Integer.valueOf(100 - index));
values.put("consumePower", Integer.valueOf(100 - index));
final BatteryHistEntry entry = new BatteryHistEntry(values);
final Map<String, BatteryHistEntry> entryMap = new HashMap<>();
entryMap.put("fake_entry_key" + index, entry);
batteryHistoryMap.put(generateTimestamp(index), entryMap);
}
return batteryHistoryMap;
}
private Map<Integer, Map<Integer, BatteryDiffData>> createBatteryUsageMap() {
final int selectedAll = BatteryChartViewModel.SELECTED_INDEX_ALL;
return Map.of(
selectedAll, Map.of(
selectedAll, new BatteryDiffData(
Arrays.asList(mBatteryDiffEntry),
Arrays.asList(mBatteryDiffEntry))),
0, Map.of(
selectedAll, new BatteryDiffData(
Arrays.asList(mBatteryDiffEntry),
Arrays.asList(mBatteryDiffEntry)),
0, new BatteryDiffData(
Arrays.asList(mBatteryDiffEntry),
Arrays.asList(mBatteryDiffEntry))));
}
private BatteryDiffEntry createBatteryDiffEntry(
long foregroundUsageTimeInMs, long backgroundUsageTimeInMs) {
return new BatteryDiffEntry(
mContext, foregroundUsageTimeInMs, backgroundUsageTimeInMs,
/*consumePower=*/ 0, mBatteryHistEntry);
}
private BatteryChartPreferenceController createController() {
final BatteryChartPreferenceController controller =
new BatteryChartPreferenceController(
mContext, "app_list", /*lifecycle=*/ null,
mSettingsActivity, mFragment);
controller.mPrefContext = mContext;
return controller;
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
import android.content.Context;
import android.os.LocaleList;
import android.view.View;
import com.android.settings.fuelgauge.PowerUsageFeatureProvider;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.List;
import java.util.Locale;
@RunWith(RobolectricTestRunner.class)
public final class BatteryChartViewTest {
private Context mContext;
private BatteryChartView mBatteryChartView;
private FakeFeatureFactory mFeatureFactory;
private PowerUsageFeatureProvider mPowerUsageFeatureProvider;
@Mock
private View mMockView;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mFeatureFactory = FakeFeatureFactory.setupForTest();
mPowerUsageFeatureProvider = mFeatureFactory.powerUsageFeatureProvider;
mContext = spy(RuntimeEnvironment.application);
mContext.getResources().getConfiguration().setLocales(
new LocaleList(new Locale("en_US")));
mBatteryChartView = new BatteryChartView(mContext);
}
@Test
public void onClick_invokesCallback() {
final int originalSelectedIndex = 2;
BatteryChartViewModel batteryChartViewModel = new BatteryChartViewModel(
List.of(90, 80, 70, 60), List.of(0L, 0L, 0L, 0L),
BatteryChartViewModel.AxisLabelPosition.BETWEEN_TRAPEZOIDS, null);
batteryChartViewModel.setSelectedIndex(originalSelectedIndex);
mBatteryChartView.setViewModel(batteryChartViewModel);
for (int i = 0; i < mBatteryChartView.mTrapezoidSlots.length; i++) {
mBatteryChartView.mTrapezoidSlots[i] = new BatteryChartView.TrapezoidSlot();
mBatteryChartView.mTrapezoidSlots[i].mLeft = i;
mBatteryChartView.mTrapezoidSlots[i].mRight = i + 0.5f;
}
final int[] selectedIndex = new int[1];
mBatteryChartView.setOnSelectListener(
trapezoidIndex -> {
selectedIndex[0] = trapezoidIndex;
});
// Verify onClick() a different index 1.
mBatteryChartView.mTouchUpEventX = 1;
selectedIndex[0] = Integer.MIN_VALUE;
mBatteryChartView.onClick(mMockView);
assertThat(selectedIndex[0]).isEqualTo(1);
// Verify onClick() the same index 2.
mBatteryChartView.mTouchUpEventX = 2;
selectedIndex[0] = Integer.MIN_VALUE;
mBatteryChartView.onClick(mMockView);
assertThat(selectedIndex[0]).isEqualTo(BatteryChartViewModel.SELECTED_INDEX_ALL);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.spy;
import android.content.ContentValues;
@@ -35,6 +35,7 @@ import android.os.UserHandle;
import android.os.UserManager;
import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryUtils;
import org.junit.Before;
import org.junit.Test;
@@ -59,15 +60,24 @@ public final class BatteryDiffEntryTest {
private Context mContext;
@Mock private ApplicationInfo mockAppInfo;
@Mock private PackageManager mockPackageManager;
@Mock private UserManager mockUserManager;
@Mock private Drawable mockDrawable;
@Mock private Drawable mockDrawable2;
@Mock private Drawable mockBadgedDrawable;
@Mock private BatteryHistEntry mBatteryHistEntry;
@Mock private PackageInfo mockPackageInfo;
@Mock private ConstantState mockConstantState;
@Mock
private ApplicationInfo mMockAppInfo;
@Mock
private PackageManager mMockPackageManager;
@Mock
private UserManager mMockUserManager;
@Mock
private Drawable mMockDrawable;
@Mock
private Drawable mMockDrawable2;
@Mock
private Drawable mMockBadgedDrawable;
@Mock
private BatteryHistEntry mBatteryHistEntry;
@Mock
private PackageInfo mMockPackageInfo;
@Mock
private ConstantState mMockConstantState;
@Before
public void setUp() {
@@ -75,20 +85,20 @@ public final class BatteryDiffEntryTest {
ShadowUserHandle.reset();
mContext = spy(RuntimeEnvironment.application);
doReturn(mContext).when(mContext).getApplicationContext();
doReturn(mockUserManager).when(mContext).getSystemService(UserManager.class);
doReturn(mockPackageManager).when(mContext).getPackageManager();
doReturn(mMockUserManager).when(mContext).getSystemService(UserManager.class);
doReturn(mMockPackageManager).when(mContext).getPackageManager();
BatteryDiffEntry.clearCache();
}
@Test
public void testSetTotalConsumePower_returnExpectedResult() {
final BatteryDiffEntry entry =
new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 10001L,
/*backgroundUsageTimeInMs=*/ 20002L,
/*consumePower=*/ 22.0,
/*batteryHistEntry=*/ null);
new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 10001L,
/*backgroundUsageTimeInMs=*/ 20002L,
/*consumePower=*/ 22.0,
/*batteryHistEntry=*/ null);
entry.setTotalConsumePower(100.0);
assertThat(entry.getPercentOfTotal()).isEqualTo(22.0);
@@ -97,12 +107,12 @@ public final class BatteryDiffEntryTest {
@Test
public void testSetTotalConsumePower_setZeroValue_returnsZeroValue() {
final BatteryDiffEntry entry =
new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 10001L,
/*backgroundUsageTimeInMs=*/ 20002L,
/*consumePower=*/ 22.0,
/*batteryHistEntry=*/ null);
new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 10001L,
/*backgroundUsageTimeInMs=*/ 20002L,
/*consumePower=*/ 22.0,
/*batteryHistEntry=*/ null);
entry.setTotalConsumePower(0);
assertThat(entry.getPercentOfTotal()).isEqualTo(0);
@@ -127,9 +137,9 @@ public final class BatteryDiffEntryTest {
final String expectedName = "Ambient display";
// Generates fake testing data.
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
values.put("drainType",
Integer.valueOf(BatteryConsumer.POWER_COMPONENT_AMBIENT_DISPLAY));
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
values.put(BatteryHistEntry.KEY_DRAIN_TYPE,
Integer.valueOf(BatteryConsumer.POWER_COMPONENT_AMBIENT_DISPLAY));
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
@@ -139,7 +149,7 @@ public final class BatteryDiffEntryTest {
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey());
BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mName).isEqualTo(expectedName);
assertThat(nameAndIcon.mIconId).isEqualTo(R.drawable.ic_settings_aod);
// Verifies the restrictable flag in the cache.
@@ -150,11 +160,11 @@ public final class BatteryDiffEntryTest {
@Test
public void testLoadLabelAndIcon_forUserBattery_returnExpectedResult() {
final String expectedName = "Removed user";
doReturn(null).when(mockUserManager).getUserInfo(1001);
doReturn(null).when(mMockUserManager).getUserInfo(1001);
// Generates fake testing data.
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_USER_BATTERY);
values.put("userId", Integer.valueOf(1001));
ConvertUtils.CONSUMER_TYPE_USER_BATTERY);
values.put(BatteryHistEntry.KEY_USER_ID, Integer.valueOf(1001));
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
@@ -165,7 +175,7 @@ public final class BatteryDiffEntryTest {
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey());
BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mName).isEqualTo(expectedName);
assertThat(nameAndIcon.mIconId).isEqualTo(0);
// Verifies the restrictable flag in the cache.
@@ -178,13 +188,13 @@ public final class BatteryDiffEntryTest {
final String expectedAppLabel = "fake app label";
final String fakePackageName = "com.fake.google.com";
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("uid", /*invalid uid*/ 10001);
values.put("packageName", fakePackageName);
doReturn(mockAppInfo).when(mockPackageManager)
.getApplicationInfo(fakePackageName, 0);
doReturn(expectedAppLabel).when(mockPackageManager)
.getApplicationLabel(mockAppInfo);
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(BatteryHistEntry.KEY_UID, /*invalid uid*/ 10001);
values.put(BatteryHistEntry.KEY_PACKAGE_NAME, fakePackageName);
doReturn(mMockAppInfo).when(mMockPackageManager)
.getApplicationInfo(fakePackageName, 0);
doReturn(expectedAppLabel).when(mMockPackageManager)
.getApplicationLabel(mMockAppInfo);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
@@ -194,7 +204,7 @@ public final class BatteryDiffEntryTest {
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey());
BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mName).isEqualTo(expectedAppLabel);
// Verifies the restrictable flag in the cache.
assertThat(entry.mValidForRestriction).isFalse();
@@ -205,7 +215,7 @@ public final class BatteryDiffEntryTest {
public void testGetAppLabel_loadDataFromPreDefinedNameAndUid() {
final String expectedAppLabel = "Android OS";
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
@@ -214,7 +224,7 @@ public final class BatteryDiffEntryTest {
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey());
BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mName).isEqualTo(expectedAppLabel);
}
@@ -222,8 +232,8 @@ public final class BatteryDiffEntryTest {
public void testGetAppLabel_nullAppLabel_returnAppLabelInBatteryHistEntry() {
final String expectedAppLabel = "fake app label";
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("appLabel", expectedAppLabel);
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(BatteryHistEntry.KEY_APP_LABEL, expectedAppLabel);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
@@ -236,15 +246,15 @@ public final class BatteryDiffEntryTest {
@Test
public void testGetAppIcon_nonUidConsumer_returnAppIconInBatteryDiffEntry() {
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
mockConstantState(mockDrawable);
mockConstantState(mMockDrawable);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
entry.mIsLoaded = true;
entry.mAppIcon = mockDrawable;
assertThat(entry.getAppIcon()).isEqualTo(mockDrawable);
entry.mAppIcon = mMockDrawable;
assertThat(entry.getAppIcon()).isEqualTo(mMockDrawable);
assertThat(BatteryDiffEntry.sResourceCache).isEmpty();
}
@@ -252,38 +262,38 @@ public final class BatteryDiffEntryTest {
public void testGetAppIcon_uidConsumerForNonOwner_returnDefaultActivityIconWithBadge()
throws Exception {
ShadowUserHandle.setUid(10);
final BatteryDiffEntry entry = createBatteryDiffEntry(mockDrawable);
mockConstantState(mockDrawable);
mockConstantState(mockBadgedDrawable);
doReturn(mockBadgedDrawable).when(mockUserManager)
.getBadgedIconForUser(eq(mockDrawable), any());
final BatteryDiffEntry entry = createBatteryDiffEntry(mMockDrawable);
mockConstantState(mMockDrawable);
mockConstantState(mMockBadgedDrawable);
doReturn(mMockBadgedDrawable).when(mMockUserManager)
.getBadgedIconForUser(eq(mMockDrawable), any());
entry.mAppIcon = null;
assertThat(entry.getAppIcon()).isEqualTo(mockBadgedDrawable);
assertThat(entry.getAppIcon()).isEqualTo(mMockBadgedDrawable);
}
@Test
public void testGetAppIcon_uidConsumerWithNullIcon_returnDefaultActivityIcon()
throws Exception {
final BatteryDiffEntry entry = createBatteryDiffEntry(mockDrawable);
mockConstantState(mockDrawable);
final BatteryDiffEntry entry = createBatteryDiffEntry(mMockDrawable);
mockConstantState(mMockDrawable);
entry.mAppIcon = null;
assertThat(entry.getAppIcon()).isEqualTo(mockDrawable);
assertThat(entry.getAppIcon()).isEqualTo(mMockDrawable);
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mIcon).isEqualTo(mockDrawable);
BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mIcon).isEqualTo(mMockDrawable);
}
@Test
public void testClearCache_clearDataForResourcesAndFlags() {
BatteryDiffEntry.sResourceCache.put(
"fake application key",
new BatteryEntry.NameAndIcon("app label", null, /*iconId=*/ 0));
"fake application key",
new BatteryEntry.NameAndIcon("app label", null, /*iconId=*/ 0));
BatteryDiffEntry.sValidForRestriction.put(
"fake application key", Boolean.valueOf(false));
"fake application key", Boolean.valueOf(false));
BatteryDiffEntry.clearCache();
@@ -295,83 +305,83 @@ public final class BatteryDiffEntryTest {
public void testClearCache_switchLocale_clearCacheIconAndLabel() throws Exception {
final int userId = UserHandle.getUserId(1001);
Locale.setDefault(new Locale("en_US"));
final BatteryDiffEntry entry1 = createBatteryDiffEntry(mockDrawable);
mockConstantState(mockDrawable);
assertThat(entry1.getAppIcon()).isEqualTo(mockDrawable);
final BatteryDiffEntry entry1 = createBatteryDiffEntry(mMockDrawable);
mockConstantState(mMockDrawable);
assertThat(entry1.getAppIcon()).isEqualTo(mMockDrawable);
// Switch the locale into another one.
Locale.setDefault(new Locale("zh_TW"));
final BatteryDiffEntry entry2 = createBatteryDiffEntry(mockDrawable2);
final BatteryDiffEntry entry2 = createBatteryDiffEntry(mMockDrawable2);
// We should get new drawable without caching.
mockConstantState(mockDrawable2);
assertThat(entry2.getAppIcon()).isEqualTo(mockDrawable2);
mockConstantState(mMockDrawable2);
assertThat(entry2.getAppIcon()).isEqualTo(mMockDrawable2);
// Verifies the cache is updated into the new drawable.
final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry2.getKey());
assertThat(nameAndIcon.mIcon).isEqualTo(mockDrawable2);
BatteryDiffEntry.sResourceCache.get(entry2.getKey());
assertThat(nameAndIcon.mIcon).isEqualTo(mMockDrawable2);
}
@Test
public void testIsSystemEntry_userBattery_returnTrue() {
final BatteryDiffEntry entry =
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_USER_BATTERY,
/*uid=*/ 0, /*isHidden=*/ false);
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_USER_BATTERY,
/*uid=*/ 0, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isTrue();
}
@Test
public void testIsSystemEntry_systemBattery_returnTrue() {
final BatteryDiffEntry entry =
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY,
/*uid=*/ 0, /*isHidden=*/ false);
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY,
/*uid=*/ 0, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isTrue();
}
@Test
public void testIsSystemEntry_uidBattery_returnFalse() {
final BatteryDiffEntry entry =
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 123, /*isHidden=*/ false);
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 123, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isFalse();
}
@Test
public void testIsSystemEntry_uidBatteryWithHiddenState_returnTrue() {
final BatteryDiffEntry entry =
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 123, /*isHidden=*/ true);
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 123, /*isHidden=*/ true);
assertThat(entry.isSystemEntry()).isTrue();
}
@Test
public void testIsSystemEntry_uidBatteryWithSystemProcess_returnFalse() {
final BatteryDiffEntry entry =
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 1230, /*isHidden=*/ false);
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 1230, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isFalse();
}
@Test
public void testIsSystemEntry_uidBatteryWithTetheringProcess_returnTrue() {
final BatteryDiffEntry entry =
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ BatteryUtils.UID_TETHERING, /*isHidden=*/ false);
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ BatteryUtils.UID_TETHERING, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isTrue();
}
@Test
public void testIsSystemEntry_uidBatteryWithRemovedAppsProcess_returnTrue() {
final BatteryDiffEntry entry =
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ BatteryUtils.UID_REMOVED_APPS, /*isHidden=*/ false);
createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ BatteryUtils.UID_REMOVED_APPS, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isTrue();
}
@@ -380,30 +390,30 @@ public final class BatteryDiffEntryTest {
final String expectedAppLabel = "fake app label";
final String fakePackageName = "com.fake.google.com";
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("uid", /*invalid uid*/ 10001);
values.put("packageName", fakePackageName);
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(BatteryHistEntry.KEY_UID, /*invalid uid*/ 10001);
values.put(BatteryHistEntry.KEY_PACKAGE_NAME, fakePackageName);
final BatteryDiffEntry entry =
createBatteryDiffEntry(10, new BatteryHistEntry(values));
createBatteryDiffEntry(10, new BatteryHistEntry(values));
entry.updateRestrictionFlagState();
// Sets false if the app entry cannot be found.
assertThat(entry.mValidForRestriction).isFalse();
doReturn(BatteryUtils.UID_NULL).when(mockPackageManager).getPackageUid(
entry.getPackageName(), PackageManager.GET_META_DATA);
doReturn(BatteryUtils.UID_NULL).when(mMockPackageManager).getPackageUid(
entry.getPackageName(), PackageManager.GET_META_DATA);
entry.updateRestrictionFlagState();
// Sets false if the app is invalid package name.
assertThat(entry.mValidForRestriction).isFalse();
doReturn(1000).when(mockPackageManager).getPackageUid(
entry.getPackageName(), PackageManager.GET_META_DATA);
doReturn(1000).when(mMockPackageManager).getPackageUid(
entry.getPackageName(), PackageManager.GET_META_DATA);
entry.updateRestrictionFlagState();
// Sets false if the app PackageInfo cannot be found.
assertThat(entry.mValidForRestriction).isFalse();
doReturn(mockPackageInfo).when(mockPackageManager).getPackageInfo(
eq(entry.getPackageName()), anyInt());
doReturn(mMockPackageInfo).when(mMockPackageManager).getPackageInfo(
eq(entry.getPackageName()), anyInt());
entry.updateRestrictionFlagState();
// Sets true if package is valid and PackageInfo can be found.
assertThat(entry.mValidForRestriction).isTrue();
@@ -413,10 +423,10 @@ public final class BatteryDiffEntryTest {
public void testGetPackageName_returnExpectedResult() {
final String expectedPackageName = "com.fake.google.com";
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("packageName", expectedPackageName);
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(BatteryHistEntry.KEY_PACKAGE_NAME, expectedPackageName);
final BatteryDiffEntry entry =
createBatteryDiffEntry(10, new BatteryHistEntry(values));
createBatteryDiffEntry(10, new BatteryHistEntry(values));
assertThat(entry.getPackageName()).isEqualTo(expectedPackageName);
}
@@ -425,63 +435,76 @@ public final class BatteryDiffEntryTest {
public void testGetPackageName_withProcessName_returnExpectedResult() {
final String expectedPackageName = "com.fake.google.com";
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(
"packageName",
expectedPackageName + ":privileged_process0");
BatteryHistEntry.KEY_PACKAGE_NAME,
expectedPackageName + ":privileged_process0");
final BatteryDiffEntry entry =
createBatteryDiffEntry(10, new BatteryHistEntry(values));
createBatteryDiffEntry(10, new BatteryHistEntry(values));
assertThat(entry.getPackageName()).isEqualTo(expectedPackageName);
}
@Test
public void getAppLabel_withOtherUsersUid_returnExpectedLabel() {
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(BatteryHistEntry.KEY_UID, BatteryUtils.UID_OTHER_USERS);
final BatteryDiffEntry batteryDiffEntry = createBatteryDiffEntry(
/*consumePower=*/ 0, new BatteryHistEntry(values));
assertThat(batteryDiffEntry.getAppLabel())
.isEqualTo(mContext.getString(R.string.battery_usage_other_users));
}
private BatteryDiffEntry createBatteryDiffEntry(
int consumerType, long uid, boolean isHidden) {
final ContentValues values = getContentValuesWithType(consumerType);
values.put("isHidden", isHidden);
values.put("uid", uid);
values.put(BatteryHistEntry.KEY_IS_HIDDEN, isHidden);
values.put(BatteryHistEntry.KEY_UID, uid);
return new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0,
/*consumePower=*/ 0,
new BatteryHistEntry(values));
mContext,
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0,
/*consumePower=*/ 0,
new BatteryHistEntry(values));
}
private BatteryDiffEntry createBatteryDiffEntry(
double consumePower, BatteryHistEntry batteryHistEntry) {
double consumePower, BatteryHistEntry batteryHistEntry) {
final BatteryDiffEntry entry = new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0,
consumePower,
batteryHistEntry);
mContext,
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0,
consumePower,
batteryHistEntry);
entry.setTotalConsumePower(100.0);
return entry;
}
private static ContentValues getContentValuesWithType(int consumerType) {
final ContentValues values = new ContentValues();
values.put("consumerType", Integer.valueOf(consumerType));
values.put(BatteryHistEntry.KEY_CONSUMER_TYPE, Integer.valueOf(consumerType));
return values;
}
private BatteryDiffEntry createBatteryDiffEntry(Drawable drawable) throws Exception {
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("uid", 1001);
values.put("packageName", "com.a.b.c");
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(BatteryHistEntry.KEY_UID, 1001);
values.put(BatteryHistEntry.KEY_PACKAGE_NAME, "com.a.b.c");
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
doReturn(drawable).when(mockPackageManager).getDefaultActivityIcon();
doReturn(null).when(mockPackageManager).getApplicationInfo("com.a.b.c", 0);
doReturn(new String[] {"com.a.b.c"}).when(mockPackageManager)
.getPackagesForUid(1001);
doReturn(drawable).when(mMockPackageManager).getDefaultActivityIcon();
doReturn(null).when(mMockPackageManager).getApplicationInfo("com.a.b.c", 0);
doReturn(new String[]{"com.a.b.c"}).when(mMockPackageManager)
.getPackagesForUid(1001);
return createBatteryDiffEntry(10, batteryHistEntry);
}
private void mockConstantState(Drawable drawable) {
doReturn(mockConstantState).when(drawable).getConstantState();
doReturn(drawable).when(mockConstantState).newDrawable();
doReturn(mMockConstantState).when(drawable).getConstantState();
doReturn(drawable).when(mMockConstantState).newDrawable();
}
@Implements(UserHandle.class)

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2016 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
@@ -37,7 +37,8 @@ import android.os.UserBatteryConsumer;
import android.os.UserManager;
import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryEntry.NameAndIcon;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.batteryusage.BatteryEntry.NameAndIcon;
import org.junit.Before;
import org.junit.Rule;
@@ -62,31 +63,36 @@ public class BatteryEntryTest {
private static final String HIGH_DRAIN_PACKAGE = "com.android.test.screen";
private static final String ANDROID_PACKAGE = "android";
@Rule public MockitoRule mocks = MockitoJUnit.rule();
@Rule
public MockitoRule mocks = MockitoJUnit.rule();
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mMockContext;
private Context mContext;
@Mock private Handler mockHandler;
@Mock private PackageManager mockPackageManager;
@Mock private UserManager mockUserManager;
@Mock private UidBatteryConsumer mUidBatteryConsumer;
@Mock
private Handler mMockHandler;
@Mock
private PackageManager mMockPackageManager;
@Mock
private UserManager mMockUserManager;
@Mock
private UidBatteryConsumer mUidBatteryConsumer;
@Before
public void stubContextToReturnMockPackageManager() {
mContext = spy(RuntimeEnvironment.application);
when(mMockContext.getPackageManager()).thenReturn(mockPackageManager);
when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
}
@Before
public void stubPackageManagerToReturnAppPackageAndName() throws NameNotFoundException {
when(mockPackageManager.getApplicationInfo(anyString(), eq(0) /* no flags */))
when(mMockPackageManager.getApplicationInfo(anyString(), eq(0) /* no flags */))
.thenAnswer(invocation -> {
ApplicationInfo info = new ApplicationInfo();
info.packageName = invocation.getArgument(0);
return info;
});
when(mockPackageManager.getApplicationLabel(any(ApplicationInfo.class)))
when(mMockPackageManager.getApplicationLabel(any(ApplicationInfo.class)))
.thenAnswer(invocation -> LABEL_PREFIX
+ ((ApplicationInfo) invocation.getArgument(0)).packageName);
}
@@ -96,7 +102,7 @@ public class BatteryEntryTest {
UidBatteryConsumer consumer = mock(UidBatteryConsumer.class);
when(consumer.getUid()).thenReturn(APP_UID);
when(consumer.getPackageWithHighestDrain()).thenReturn(highDrainPackage);
return new BatteryEntry(mMockContext, mockHandler, mockUserManager,
return new BatteryEntry(mMockContext, mMockHandler, mMockUserManager,
consumer, false, APP_UID, packages, packageName);
}
@@ -111,7 +117,7 @@ public class BatteryEntryTest {
private BatteryEntry createUserBatteryConsumer(int userId) {
UserBatteryConsumer consumer = mock(UserBatteryConsumer.class);
when(consumer.getUserId()).thenReturn(userId);
return new BatteryEntry(mMockContext, mockHandler, mockUserManager,
return new BatteryEntry(mMockContext, mMockHandler, mMockUserManager,
consumer, false, 0, null, null);
}
@@ -127,7 +133,7 @@ public class BatteryEntryTest {
@Test
public void batteryEntryForApp_shouldSetLabelAsPackageName_whenPackageCannotBeFound()
throws Exception {
when(mockPackageManager.getApplicationInfo(APP_DEFAULT_PACKAGE_NAME, 0 /* no flags */))
when(mMockPackageManager.getApplicationInfo(APP_DEFAULT_PACKAGE_NAME, 0 /* no flags */))
.thenThrow(new NameNotFoundException());
BatteryEntry entry = createBatteryEntryForApp(null, APP_DEFAULT_PACKAGE_NAME, null);
@@ -137,7 +143,7 @@ public class BatteryEntryTest {
@Test
public void batteryEntryForApp_shouldSetHighestDrainPackage_whenPackagesCannotBeFoundForUid() {
when(mockPackageManager.getPackagesForUid(APP_UID)).thenReturn(null);
when(mMockPackageManager.getPackagesForUid(APP_UID)).thenReturn(null);
BatteryEntry entry = createBatteryEntryForApp(null, null, HIGH_DRAIN_PACKAGE);
@@ -147,7 +153,7 @@ public class BatteryEntryTest {
@Test
public void batteryEntryForApp_shouldSetHighestDrainPackage_whenMultiplePackagesFoundForUid() {
BatteryEntry entry = createBatteryEntryForApp(
new String[] {APP_DEFAULT_PACKAGE_NAME, "package2", "package3"}, null,
new String[]{APP_DEFAULT_PACKAGE_NAME, "package2", "package3"}, null,
HIGH_DRAIN_PACKAGE);
assertThat(entry.getLabel()).isEqualTo(LABEL_PREFIX + HIGH_DRAIN_PACKAGE);
@@ -176,8 +182,8 @@ public class BatteryEntryTest {
when(mUidBatteryConsumer.getTimeInStateMs(UidBatteryConsumer.STATE_FOREGROUND))
.thenReturn(100L);
final BatteryEntry entry = new BatteryEntry(RuntimeEnvironment.application, mockHandler,
mockUserManager, mUidBatteryConsumer, false, 0, null, null);
final BatteryEntry entry = new BatteryEntry(RuntimeEnvironment.application, mMockHandler,
mMockUserManager, mUidBatteryConsumer, false, 0, null, null);
assertThat(entry.getTimeInForegroundMs()).isEqualTo(100L);
}
@@ -195,8 +201,8 @@ public class BatteryEntryTest {
when(mUidBatteryConsumer.getTimeInStateMs(UidBatteryConsumer.STATE_BACKGROUND))
.thenReturn(100L);
final BatteryEntry entry = new BatteryEntry(RuntimeEnvironment.application, mockHandler,
mockUserManager, mUidBatteryConsumer, false, 0, null, null);
final BatteryEntry entry = new BatteryEntry(RuntimeEnvironment.application, mMockHandler,
mMockUserManager, mUidBatteryConsumer, false, 0, null, null);
assertThat(entry.getTimeInBackgroundMs()).isEqualTo(100L);
}
@@ -247,7 +253,7 @@ public class BatteryEntryTest {
@Test
public void getKey_UserBatteryConsumer_returnUserId() {
doReturn(mockUserManager).when(mMockContext).getSystemService(UserManager.class);
doReturn(mMockUserManager).when(mMockContext).getSystemService(UserManager.class);
final BatteryEntry entry = createUserBatteryConsumer(2);
final String key = entry.getKey();
assertThat(key).isEqualTo("U|2");
@@ -256,8 +262,8 @@ public class BatteryEntryTest {
@Test
public void getNameAndIconFromUserId_nullUserInfo_returnDefaultNameAndIcon() {
final int userId = 1001;
doReturn(mockUserManager).when(mContext).getSystemService(UserManager.class);
doReturn(null).when(mockUserManager).getUserInfo(userId);
doReturn(mMockUserManager).when(mContext).getSystemService(UserManager.class);
doReturn(null).when(mMockUserManager).getUserInfo(userId);
final NameAndIcon nameAndIcon = BatteryEntry.getNameAndIconFromUserId(
mContext, userId);
@@ -301,7 +307,7 @@ public class BatteryEntryTest {
R.drawable.ic_settings_aod);
assertNameAndIcon(BatteryConsumer.POWER_COMPONENT_BLUETOOTH,
R.string.power_bluetooth,
com.android.internal.R.drawable.ic_settings_bluetooth);
R.drawable.ic_settings_bluetooth);
assertNameAndIcon(BatteryConsumer.POWER_COMPONENT_CAMERA,
R.string.power_camera,
R.drawable.ic_settings_camera);
@@ -319,7 +325,7 @@ public class BatteryEntryTest {
R.drawable.ic_settings_display);
assertNameAndIcon(BatteryConsumer.POWER_COMPONENT_WIFI,
R.string.power_wifi,
R.drawable.ic_settings_wireless);
R.drawable.ic_settings_wireless_no_theme);
assertNameAndIcon(BatteryConsumer.POWER_COMPONENT_IDLE,
R.string.power_idle,
R.drawable.ic_settings_phone_idle);

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
@@ -38,7 +38,7 @@ import java.util.TimeZone;
public final class BatteryHistEntryTest {
@Mock
private BatteryEntry mockBatteryEntry;
private BatteryEntry mMockBatteryEntry;
@Mock
private BatteryUsageStats mBatteryUsageStats;
@@ -50,33 +50,33 @@ public final class BatteryHistEntryTest {
@Test
public void testConstructor_contentValues_returnsExpectedResult() {
final int expectedType = 3;
when(mockBatteryEntry.getUid()).thenReturn(1001);
when(mockBatteryEntry.getLabel()).thenReturn("Settings");
when(mockBatteryEntry.getDefaultPackageName())
.thenReturn("com.google.android.settings.battery");
when(mockBatteryEntry.isHidden()).thenReturn(true);
when(mMockBatteryEntry.getUid()).thenReturn(1001);
when(mMockBatteryEntry.getLabel()).thenReturn("Settings");
when(mMockBatteryEntry.getDefaultPackageName())
.thenReturn("com.google.android.settings.battery");
when(mMockBatteryEntry.isHidden()).thenReturn(true);
when(mBatteryUsageStats.getConsumedPower()).thenReturn(5.1);
when(mockBatteryEntry.getConsumedPower()).thenReturn(1.1);
mockBatteryEntry.mPercent = 0.3;
when(mockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L);
when(mockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L);
when(mockBatteryEntry.getPowerComponentId()).thenReturn(expectedType);
when(mockBatteryEntry.getConsumerType())
.thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
when(mMockBatteryEntry.getConsumedPower()).thenReturn(1.1);
mMockBatteryEntry.mPercent = 0.3;
when(mMockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L);
when(mMockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L);
when(mMockBatteryEntry.getPowerComponentId()).thenReturn(expectedType);
when(mMockBatteryEntry.getConsumerType())
.thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
final ContentValues values =
ConvertUtils.convert(
mockBatteryEntry,
mBatteryUsageStats,
/*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L);
ConvertUtils.convertToContentValues(
mMockBatteryEntry,
mBatteryUsageStats,
/*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L);
assertBatteryHistEntry(
new BatteryHistEntry(values),
/*drainType=*/ expectedType,
/*percentOfTotal=*/ mockBatteryEntry.mPercent);
new BatteryHistEntry(values),
/*drainType=*/ expectedType,
/*percentOfTotal=*/ mMockBatteryEntry.mPercent);
}
@Test
@@ -88,22 +88,22 @@ public final class BatteryHistEntryTest {
@Test
public void testConstructor_cursor_returnsExpectedResult() {
assertBatteryHistEntry(
createBatteryHistEntry(
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L,
/*totalPower=*/ 5.1,
/*consumePower=*/ 1.1,
/*foregroundUsageTimeInMs=*/ 1234L,
/*backgroundUsageTimeInMs=*/ 5689L,
/*batteryLevel=*/ 12),
/*drainType=*/ 3,
/*percentOfTotal=*/ 0.3);
createBatteryHistEntry(
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L,
/*totalPower=*/ 5.1,
/*consumePower=*/ 1.1,
/*foregroundUsageTimeInMs=*/ 1234L,
/*backgroundUsageTimeInMs=*/ 5689L,
/*batteryLevel=*/ 12),
/*drainType=*/ 3,
/*percentOfTotal=*/ 0.3);
}
@Test
public void testGetKey_consumerUidType_returnExpectedString() {
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(BatteryHistEntry.KEY_UID, 3);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
@@ -113,7 +113,7 @@ public final class BatteryHistEntryTest {
@Test
public void testGetKey_consumerUserType_returnExpectedString() {
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_USER_BATTERY);
ConvertUtils.CONSUMER_TYPE_USER_BATTERY);
values.put(BatteryHistEntry.KEY_USER_ID, 2);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
@@ -123,7 +123,7 @@ public final class BatteryHistEntryTest {
@Test
public void testGetKey_consumerSystemType_returnExpectedString() {
final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
values.put(BatteryHistEntry.KEY_DRAIN_TYPE, 1);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
@@ -133,31 +133,31 @@ public final class BatteryHistEntryTest {
@Test
public void testIsAppEntry_returnExpectedResult() {
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isAppEntry())
.isFalse();
.isFalse();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isAppEntry())
.isFalse();
.isFalse();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isAppEntry())
.isTrue();
.isTrue();
}
@Test
public void testIsUserEntry_returnExpectedResult() {
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isUserEntry())
.isFalse();
.isFalse();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isUserEntry())
.isTrue();
.isTrue();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isUserEntry())
.isFalse();
.isFalse();
}
@Test
public void testIsSystemEntry_returnExpectedResult() {
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isSystemEntry())
.isTrue();
.isTrue();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isSystemEntry())
.isFalse();
.isFalse();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isSystemEntry())
.isFalse();
.isFalse();
}
@Test
@@ -167,39 +167,39 @@ public final class BatteryHistEntryTest {
final long lowerTimestamp = 100L;
final double ratio = 0.5;
final BatteryHistEntry lowerHistEntry = createBatteryHistEntry(
/*bootTimestamp=*/ 1000L,
lowerTimestamp,
/*totalPower=*/ 50,
/*consumePower=*/ 10,
/*foregroundUsageTimeInMs=*/ 100,
/*backgroundUsageTimeInMs=*/ 200,
/*batteryLevel=*/ 90);
/*bootTimestamp=*/ 1000L,
lowerTimestamp,
/*totalPower=*/ 50,
/*consumePower=*/ 10,
/*foregroundUsageTimeInMs=*/ 100,
/*backgroundUsageTimeInMs=*/ 200,
/*batteryLevel=*/ 90);
final BatteryHistEntry upperHistEntry = createBatteryHistEntry(
/*bootTimestamp=*/ 1200L,
upperTimestamp,
/*totalPower=*/ 80,
/*consumePower=*/ 20,
/*foregroundUsageTimeInMs=*/ 200,
/*backgroundUsageTimeInMs=*/ 300,
/*batteryLevel=*/ 80);
/*bootTimestamp=*/ 1200L,
upperTimestamp,
/*totalPower=*/ 80,
/*consumePower=*/ 20,
/*foregroundUsageTimeInMs=*/ 200,
/*backgroundUsageTimeInMs=*/ 300,
/*batteryLevel=*/ 80);
final BatteryHistEntry newEntry =
BatteryHistEntry.interpolate(
slotTimestamp,
upperTimestamp,
ratio,
lowerHistEntry,
upperHistEntry);
BatteryHistEntry.interpolate(
slotTimestamp,
upperTimestamp,
ratio,
lowerHistEntry,
upperHistEntry);
assertBatteryHistEntry(
newEntry, 3, upperHistEntry.mPercentOfTotal,
/*bootTimestamp=*/ 1200 - 100,
/*timestamp=*/ slotTimestamp,
/*totalPower=*/ 50 + 0.5 * (80 - 50),
/*consumePower=*/ 10 + 0.5 * (20 - 10),
/*foregroundUsageTimeInMs=*/ Math.round(100 + 0.5 * (200 - 100)),
/*backgroundUsageTimeInMs=*/ Math.round(200 + 0.5 * (300 - 200)),
/*batteryLevel=*/ (int) Math.round(90 + 0.5 * (80 - 90)));
newEntry, 3, upperHistEntry.mPercentOfTotal,
/*bootTimestamp=*/ 1200 - 100,
/*timestamp=*/ slotTimestamp,
/*totalPower=*/ 50 + 0.5 * (80 - 50),
/*consumePower=*/ 10 + 0.5 * (20 - 10),
/*foregroundUsageTimeInMs=*/ Math.round(100 + 0.5 * (200 - 100)),
/*backgroundUsageTimeInMs=*/ Math.round(200 + 0.5 * (300 - 200)),
/*batteryLevel=*/ (int) Math.round(90 + 0.5 * (80 - 90)));
}
@Test
@@ -209,31 +209,31 @@ public final class BatteryHistEntryTest {
final long lowerTimestamp = 100L;
final double ratio = 0.5;
final BatteryHistEntry upperHistEntry = createBatteryHistEntry(
/*bootTimestamp=*/ 1200L,
upperTimestamp,
/*totalPower=*/ 80,
/*consumePower=*/ 20,
/*foregroundUsageTimeInMs=*/ 200,
/*backgroundUsageTimeInMs=*/ 300,
/*batteryLevel=*/ 80);
/*bootTimestamp=*/ 1200L,
upperTimestamp,
/*totalPower=*/ 80,
/*consumePower=*/ 20,
/*foregroundUsageTimeInMs=*/ 200,
/*backgroundUsageTimeInMs=*/ 300,
/*batteryLevel=*/ 80);
final BatteryHistEntry newEntry =
BatteryHistEntry.interpolate(
slotTimestamp,
upperTimestamp,
ratio,
/*lowerHistEntry=*/ null,
upperHistEntry);
BatteryHistEntry.interpolate(
slotTimestamp,
upperTimestamp,
ratio,
/*lowerHistEntry=*/ null,
upperHistEntry);
assertBatteryHistEntry(
newEntry, 3, upperHistEntry.mPercentOfTotal,
/*bootTimestamp=*/ 1200 - 100,
/*timestamp=*/ slotTimestamp,
/*totalPower=*/ 0.5 * 80,
/*consumePower=*/ 0.5 * 20,
/*foregroundUsageTimeInMs=*/ Math.round(0.5 * 200),
/*backgroundUsageTimeInMs=*/ Math.round(0.5 * 300),
/*batteryLevel=*/ upperHistEntry.mBatteryLevel);
newEntry, 3, upperHistEntry.mPercentOfTotal,
/*bootTimestamp=*/ 1200 - 100,
/*timestamp=*/ slotTimestamp,
/*totalPower=*/ 0.5 * 80,
/*consumePower=*/ 0.5 * 20,
/*foregroundUsageTimeInMs=*/ Math.round(0.5 * 200),
/*backgroundUsageTimeInMs=*/ Math.round(0.5 * 300),
/*batteryLevel=*/ upperHistEntry.mBatteryLevel);
}
private static BatteryHistEntry createEntry(int consumerType) {
@@ -243,21 +243,21 @@ public final class BatteryHistEntryTest {
private static ContentValues getContentValuesWithType(int consumerType) {
final ContentValues values = new ContentValues();
values.put(BatteryHistEntry.KEY_CONSUMER_TYPE,
Integer.valueOf(consumerType));
Integer.valueOf(consumerType));
return values;
}
private void assertBatteryHistEntry(
BatteryHistEntry entry, int drainType, double percentOfTotal) {
assertBatteryHistEntry(
entry, drainType, percentOfTotal,
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L,
/*totalPower=*/ 5.1,
/*consumePower=*/ 1.1,
/*foregroundUsageTimeInMs=*/ 1234L,
/*backgroundUsageTimeInMs=*/ 5689L,
/*batteryLevel=*/ 12);
entry, drainType, percentOfTotal,
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L,
/*totalPower=*/ 5.1,
/*consumePower=*/ 1.1,
/*foregroundUsageTimeInMs=*/ 1234L,
/*backgroundUsageTimeInMs=*/ 5689L,
/*batteryLevel=*/ 12);
}
private void assertBatteryHistEntry(
@@ -276,7 +276,7 @@ public final class BatteryHistEntryTest {
assertThat(entry.mUserId).isEqualTo(UserHandle.getUserId(1001));
assertThat(entry.mAppLabel).isEqualTo("Settings");
assertThat(entry.mPackageName)
.isEqualTo("com.google.android.settings.battery");
.isEqualTo("com.google.android.settings.battery");
assertThat(entry.mIsHidden).isTrue();
assertThat(entry.mBootTimestamp).isEqualTo(bootTimestamp);
assertThat(entry.mTimestamp).isEqualTo(timestamp);
@@ -288,12 +288,12 @@ public final class BatteryHistEntryTest {
assertThat(entry.mBackgroundUsageTimeInMs).isEqualTo(backgroundUsageTimeInMs);
assertThat(entry.mDrainType).isEqualTo(drainType);
assertThat(entry.mConsumerType)
.isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
.isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
assertThat(entry.mBatteryLevel).isEqualTo(batteryLevel);
assertThat(entry.mBatteryStatus)
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
assertThat(entry.mBatteryHealth)
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
}
private BatteryHistEntry createBatteryHistEntry(
@@ -305,7 +305,7 @@ public final class BatteryHistEntryTest {
long backgroundUsageTimeInMs,
int batteryLevel) {
final MatrixCursor cursor = new MatrixCursor(
new String[] {
new String[]{
BatteryHistEntry.KEY_UID,
BatteryHistEntry.KEY_USER_ID,
BatteryHistEntry.KEY_APP_LABEL,
@@ -325,7 +325,7 @@ public final class BatteryHistEntryTest {
BatteryHistEntry.KEY_BATTERY_STATUS,
BatteryHistEntry.KEY_BATTERY_HEALTH});
cursor.addRow(
new Object[] {
new Object[]{
Long.valueOf(1001),
Long.valueOf(UserHandle.getUserId(1001)),
"Settings",

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,18 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import android.content.Context;
import com.android.settings.testutils.FakeFeatureFactory;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -32,6 +30,9 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.util.HashMap;
import java.util.Map;
@RunWith(RobolectricTestRunner.class)
public final class BatteryHistoryLoaderTest {
@@ -52,7 +53,7 @@ public final class BatteryHistoryLoaderTest {
public void testLoadIBackground_returnsMapFromPowerFeatureProvider() {
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = new HashMap<>();
doReturn(batteryHistoryMap).when(mFeatureFactory.powerUsageFeatureProvider)
.getBatteryHistory(mContext);
.getBatteryHistorySinceLastFullCharge(mContext);
assertThat(mBatteryHistoryLoader.loadInBackground())
.isSameInstanceAs(batteryHistoryMap);

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
@@ -31,6 +31,7 @@ import android.widget.TextView;
import androidx.preference.PreferenceViewHolder;
import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryInfo;
import com.android.settings.widget.UsageView;
import org.junit.Before;

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2017 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
@@ -26,7 +26,10 @@ import android.os.BatteryManager;
import android.os.BatteryUsageStats;
import android.os.LocaleList;
import android.os.UserHandle;
import android.text.format.DateUtils;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.PowerUsageFeatureProvider;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
@@ -54,7 +57,7 @@ public final class ConvertUtilsTest {
@Mock
private BatteryUsageStats mBatteryUsageStats;
@Mock
private BatteryEntry mockBatteryEntry;
private BatteryEntry mMockBatteryEntry;
private FakeFeatureFactory mFeatureFactory;
private PowerUsageFeatureProvider mPowerUsageFeatureProvider;
@@ -68,117 +71,189 @@ public final class ConvertUtilsTest {
}
@Test
public void convert_returnsExpectedContentValues() {
public void convertToContentValues_returnsExpectedContentValues() {
final int expectedType = 3;
when(mockBatteryEntry.getUid()).thenReturn(1001);
when(mockBatteryEntry.getLabel()).thenReturn("Settings");
when(mockBatteryEntry.getDefaultPackageName())
.thenReturn("com.google.android.settings.battery");
when(mockBatteryEntry.isHidden()).thenReturn(true);
when(mMockBatteryEntry.getUid()).thenReturn(1001);
when(mMockBatteryEntry.getLabel()).thenReturn("Settings");
when(mMockBatteryEntry.getDefaultPackageName())
.thenReturn("com.google.android.settings.battery");
when(mMockBatteryEntry.isHidden()).thenReturn(true);
when(mBatteryUsageStats.getConsumedPower()).thenReturn(5.1);
when(mockBatteryEntry.getConsumedPower()).thenReturn(1.1);
mockBatteryEntry.mPercent = 0.3;
when(mockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L);
when(mockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L);
when(mockBatteryEntry.getPowerComponentId()).thenReturn(expectedType);
when(mockBatteryEntry.getConsumerType())
.thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
when(mMockBatteryEntry.getConsumedPower()).thenReturn(1.1);
mMockBatteryEntry.mPercent = 0.3;
when(mMockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L);
when(mMockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L);
when(mMockBatteryEntry.getPowerComponentId()).thenReturn(expectedType);
when(mMockBatteryEntry.getConsumerType())
.thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
final ContentValues values =
ConvertUtils.convert(
mockBatteryEntry,
mBatteryUsageStats,
/*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L);
ConvertUtils.convertToContentValues(
mMockBatteryEntry,
mBatteryUsageStats,
/*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_UID)).isEqualTo(1001L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_USER_ID))
.isEqualTo(UserHandle.getUserId(1001));
.isEqualTo(UserHandle.getUserId(1001));
assertThat(values.getAsString(BatteryHistEntry.KEY_APP_LABEL))
.isEqualTo("Settings");
.isEqualTo("Settings");
assertThat(values.getAsString(BatteryHistEntry.KEY_PACKAGE_NAME))
.isEqualTo("com.google.android.settings.battery");
.isEqualTo("com.google.android.settings.battery");
assertThat(values.getAsBoolean(BatteryHistEntry.KEY_IS_HIDDEN)).isTrue();
assertThat(values.getAsLong(BatteryHistEntry.KEY_BOOT_TIMESTAMP))
.isEqualTo(101L);
.isEqualTo(101L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_TIMESTAMP)).isEqualTo(10001L);
assertThat(values.getAsString(BatteryHistEntry.KEY_ZONE_ID))
.isEqualTo(TimeZone.getDefault().getID());
.isEqualTo(TimeZone.getDefault().getID());
assertThat(values.getAsDouble(BatteryHistEntry.KEY_TOTAL_POWER)).isEqualTo(5.1);
assertThat(values.getAsDouble(BatteryHistEntry.KEY_CONSUME_POWER)).isEqualTo(1.1);
assertThat(values.getAsDouble(BatteryHistEntry.KEY_PERCENT_OF_TOTAL)).isEqualTo(0.3);
assertThat(values.getAsLong(BatteryHistEntry.KEY_FOREGROUND_USAGE_TIME))
.isEqualTo(1234L);
.isEqualTo(1234L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_BACKGROUND_USAGE_TIME))
.isEqualTo(5689L);
.isEqualTo(5689L);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_DRAIN_TYPE)).isEqualTo(expectedType);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_CONSUMER_TYPE))
.isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
.isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_LEVEL)).isEqualTo(12);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_STATUS))
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_HEALTH))
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
}
@Test
public void convert_nullBatteryEntry_returnsExpectedContentValues() {
public void convertToContentValues_nullBatteryEntry_returnsExpectedContentValues() {
final ContentValues values =
ConvertUtils.convert(
/*entry=*/ null,
/*batteryUsageStats=*/ null,
/*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L);
ConvertUtils.convertToContentValues(
/*entry=*/ null,
/*batteryUsageStats=*/ null,
/*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_BOOT_TIMESTAMP))
.isEqualTo(101L);
.isEqualTo(101L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_TIMESTAMP))
.isEqualTo(10001L);
.isEqualTo(10001L);
assertThat(values.getAsString(BatteryHistEntry.KEY_ZONE_ID))
.isEqualTo(TimeZone.getDefault().getID());
.isEqualTo(TimeZone.getDefault().getID());
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_LEVEL)).isEqualTo(12);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_STATUS))
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_HEALTH))
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
assertThat(values.getAsString(BatteryHistEntry.KEY_PACKAGE_NAME))
.isEqualTo(ConvertUtils.FAKE_PACKAGE_NAME);
.isEqualTo(ConvertUtils.FAKE_PACKAGE_NAME);
}
@Test
public void convertToBatteryHistEntry_returnsExpectedResult() {
final int expectedType = 3;
when(mMockBatteryEntry.getUid()).thenReturn(1001);
when(mMockBatteryEntry.getLabel()).thenReturn("Settings");
when(mMockBatteryEntry.getDefaultPackageName())
.thenReturn("com.android.settings.battery");
when(mMockBatteryEntry.isHidden()).thenReturn(true);
when(mBatteryUsageStats.getConsumedPower()).thenReturn(5.1);
when(mMockBatteryEntry.getConsumedPower()).thenReturn(1.1);
mMockBatteryEntry.mPercent = 0.3;
when(mMockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L);
when(mMockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L);
when(mMockBatteryEntry.getPowerComponentId()).thenReturn(expectedType);
when(mMockBatteryEntry.getConsumerType())
.thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
final BatteryHistEntry batteryHistEntry =
ConvertUtils.convertToBatteryHistEntry(
mMockBatteryEntry,
mBatteryUsageStats);
assertThat(batteryHistEntry.mUid).isEqualTo(1001L);
assertThat(batteryHistEntry.mUserId)
.isEqualTo(UserHandle.getUserId(1001));
assertThat(batteryHistEntry.mAppLabel)
.isEqualTo("Settings");
assertThat(batteryHistEntry.mPackageName)
.isEqualTo("com.android.settings.battery");
assertThat(batteryHistEntry.mIsHidden).isTrue();
assertThat(batteryHistEntry.mBootTimestamp)
.isEqualTo(0L);
assertThat(batteryHistEntry.mTimestamp).isEqualTo(0L);
assertThat(batteryHistEntry.mZoneId)
.isEqualTo(TimeZone.getDefault().getID());
assertThat(batteryHistEntry.mTotalPower).isEqualTo(5.1);
assertThat(batteryHistEntry.mConsumePower).isEqualTo(1.1);
assertThat(batteryHistEntry.mPercentOfTotal).isEqualTo(0.3);
assertThat(batteryHistEntry.mForegroundUsageTimeInMs)
.isEqualTo(1234L);
assertThat(batteryHistEntry.mBackgroundUsageTimeInMs)
.isEqualTo(5689L);
assertThat(batteryHistEntry.mDrainType).isEqualTo(expectedType);
assertThat(batteryHistEntry.mConsumerType)
.isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
assertThat(batteryHistEntry.mBatteryLevel).isEqualTo(0);
assertThat(batteryHistEntry.mBatteryStatus).isEqualTo(0);
assertThat(batteryHistEntry.mBatteryHealth).isEqualTo(0);
}
@Test
public void convertToBatteryHistEntry_nullBatteryEntry_returnsExpectedResult() {
final BatteryHistEntry batteryHistEntry =
ConvertUtils.convertToBatteryHistEntry(
/*entry=*/ null,
/*batteryUsageStats=*/ null);
assertThat(batteryHistEntry.mBootTimestamp)
.isEqualTo(0L);
assertThat(batteryHistEntry.mTimestamp)
.isEqualTo(0);
assertThat(batteryHistEntry.mZoneId)
.isEqualTo(TimeZone.getDefault().getID());
assertThat(batteryHistEntry.mBatteryLevel).isEqualTo(0);
assertThat(batteryHistEntry.mBatteryStatus).isEqualTo(0);
assertThat(batteryHistEntry.mBatteryHealth).isEqualTo(0);
assertThat(batteryHistEntry.mPackageName)
.isEqualTo(ConvertUtils.FAKE_PACKAGE_NAME);
}
@Test
public void getIndexedUsageMap_nullOrEmptyHistoryMap_returnEmptyCollection() {
final int timeSlotSize = 2;
final long[] batteryHistoryKeys = new long[] {101L, 102L, 103L, 104L, 105L};
final long[] batteryHistoryKeys = new long[]{101L, 102L, 103L, 104L, 105L};
assertThat(ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys,
/*batteryHistoryMap=*/ null, /*purgeLowPercentageAndFakeData=*/ true))
.isEmpty();
.isEmpty();
assertThat(ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys,
new HashMap<Long, Map<String, BatteryHistEntry>>(),
/*purgeLowPercentageAndFakeData=*/ true))
.isEmpty();
.isEmpty();
}
@Test
public void getIndexedUsageMap_returnsExpectedResult() {
// Creates the fake testing data.
final int timeSlotSize = 2;
final long[] batteryHistoryKeys = new long[] {101L, 102L, 103L, 104L, 105L};
final long[] batteryHistoryKeys = new long[]{generateTimestamp(0), generateTimestamp(1),
generateTimestamp(2), generateTimestamp(3), generateTimestamp(4)};
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap =
new HashMap<>();
new HashMap<>();
final BatteryHistEntry fakeEntry = createBatteryHistEntry(
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
// Adds the index = 0 data.
Map<String, BatteryHistEntry> entryMap = new HashMap<>();
BatteryHistEntry entry = createBatteryHistEntry(
"package1", "label1", 5.0, 1L, 10L, 20L);
"package1", "label1", 5.0, 1L, 10L, 20L);
entryMap.put(entry.getKey(), entry);
entryMap.put(fakeEntry.getKey(), fakeEntry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[0]), entryMap);
@@ -189,38 +264,38 @@ public final class ConvertUtilsTest {
// Adds the index = 2 data.
entryMap = new HashMap<>();
entry = createBatteryHistEntry(
"package2", "label2", 10.0, 2L, 15L, 25L);
"package2", "label2", 10.0, 2L, 15L, 25L);
entryMap.put(entry.getKey(), entry);
entryMap.put(fakeEntry.getKey(), fakeEntry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap);
// Adds the index = 3 data.
entryMap = new HashMap<>();
entry = createBatteryHistEntry(
"package2", "label2", 15.0, 2L, 25L, 35L);
"package2", "label2", 15.0, 2L, 25L, 35L);
entryMap.put(entry.getKey(), entry);
entry = createBatteryHistEntry(
"package3", "label3", 5.0, 3L, 5L, 5L);
"package3", "label3", 5.0, 3L, 5L, 5L);
entryMap.put(entry.getKey(), entry);
entryMap.put(fakeEntry.getKey(), fakeEntry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[3]), entryMap);
// Adds the index = 4 data.
entryMap = new HashMap<>();
entry = createBatteryHistEntry(
"package2", "label2", 30.0, 2L, 30L, 40L);
"package2", "label2", 30.0, 2L, 30L, 40L);
entryMap.put(entry.getKey(), entry);
entry = createBatteryHistEntry(
"package2", "label2", 75.0, 4L, 40L, 50L);
"package2", "label2", 75.0, 4L, 40L, 50L);
entryMap.put(entry.getKey(), entry);
entry = createBatteryHistEntry(
"package3", "label3", 5.0, 3L, 5L, 5L);
"package3", "label3", 5.0, 3L, 5L, 5L);
entryMap.put(entry.getKey(), entry);
entryMap.put(fakeEntry.getKey(), fakeEntry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[4]), entryMap);
final Map<Integer, List<BatteryDiffEntry>> resultMap =
ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ false);
ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ false);
assertThat(resultMap).hasSize(3);
// Verifies the first timestamp result.
@@ -243,9 +318,9 @@ public final class ConvertUtilsTest {
// Test getIndexedUsageMap() with purged data.
ConvertUtils.PERCENTAGE_OF_TOTAL_THRESHOLD = 50;
final Map<Integer, List<BatteryDiffEntry>> purgedResultMap =
ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true);
ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true);
assertThat(purgedResultMap).hasSize(3);
// Verifies the first timestamp result.
@@ -260,18 +335,18 @@ public final class ConvertUtilsTest {
assertThat(entryList).hasSize(1);
// Verifies the fake data is cleared out.
assertThat(entryList.get(0).getPackageName())
.isNotEqualTo(ConvertUtils.FAKE_PACKAGE_NAME);
.isNotEqualTo(ConvertUtils.FAKE_PACKAGE_NAME);
// Adds lacked data into the battery history map.
final int remainingSize = 25 - batteryHistoryKeys.length;
for (int index = 0; index < remainingSize; index++) {
batteryHistoryMap.put(105L + index + 1, new HashMap<>());
}
when(mPowerUsageFeatureProvider.getBatteryHistory(mContext))
.thenReturn(batteryHistoryMap);
when(mPowerUsageFeatureProvider.getBatteryHistorySinceLastFullCharge(mContext))
.thenReturn(batteryHistoryMap);
final List<BatteryDiffEntry> batteryDiffEntryList =
BatteryChartPreferenceController.getBatteryLast24HrUsageData(mContext);
BatteryChartPreferenceController.getAppBatteryUsageData(mContext);
assertThat(batteryDiffEntryList).isNotEmpty();
final BatteryDiffEntry resultEntry = batteryDiffEntryList.get(0);
@@ -281,11 +356,11 @@ public final class ConvertUtilsTest {
@Test
public void getIndexedUsageMap_usageTimeExceed_returnsExpectedResult() {
final int timeSlotSize = 1;
final long[] batteryHistoryKeys = new long[] {101L, 102L, 103L};
final long[] batteryHistoryKeys = new long[]{101L, 102L, 103L};
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap =
new HashMap<>();
new HashMap<>();
final BatteryHistEntry fakeEntry = createBatteryHistEntry(
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
// Adds the index = 0 data.
Map<String, BatteryHistEntry> entryMap = new HashMap<>();
entryMap.put(fakeEntry.getKey(), fakeEntry);
@@ -297,14 +372,14 @@ public final class ConvertUtilsTest {
// Adds the index = 2 data.
entryMap = new HashMap<>();
final BatteryHistEntry entry = createBatteryHistEntry(
"package3", "label3", 500, 5L, 3600000L, 7200000L);
"package3", "label3", 500, 5L, 3600000L, 7200000L);
entryMap.put(entry.getKey(), entry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap);
final Map<Integer, List<BatteryDiffEntry>> purgedResultMap =
ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true);
ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true);
assertThat(purgedResultMap).hasSize(2);
final List<BatteryDiffEntry> entryList = purgedResultMap.get(0);
@@ -313,19 +388,19 @@ public final class ConvertUtilsTest {
final float ratio = (float) (7200) / (float) (3600 + 7200);
final BatteryDiffEntry resultEntry = entryList.get(0);
assertThat(resultEntry.mForegroundUsageTimeInMs)
.isEqualTo(Math.round(entry.mForegroundUsageTimeInMs * ratio));
.isEqualTo(Math.round(entry.mForegroundUsageTimeInMs * ratio));
assertThat(resultEntry.mBackgroundUsageTimeInMs)
.isEqualTo(Math.round(entry.mBackgroundUsageTimeInMs * ratio));
.isEqualTo(Math.round(entry.mBackgroundUsageTimeInMs * ratio));
assertThat(resultEntry.mConsumePower)
.isEqualTo(entry.mConsumePower * ratio);
.isEqualTo(entry.mConsumePower * ratio);
}
@Test
public void getIndexedUsageMap_hideBackgroundUsageTime_returnsExpectedResult() {
final long[] batteryHistoryKeys = new long[] {101L, 102L, 103L};
final long[] batteryHistoryKeys = new long[]{101L, 102L, 103L};
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = new HashMap<>();
final BatteryHistEntry fakeEntry = createBatteryHistEntry(
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
// Adds the index = 0 data.
Map<String, BatteryHistEntry> entryMap = new HashMap<>();
entryMap.put(fakeEntry.getKey(), fakeEntry);
@@ -337,16 +412,16 @@ public final class ConvertUtilsTest {
// Adds the index = 2 data.
entryMap = new HashMap<>();
final BatteryHistEntry entry = createBatteryHistEntry(
"package3", "label3", 500, 5L, 3600000L, 7200000L);
"package3", "label3", 500, 5L, 3600000L, 7200000L);
entryMap.put(entry.getKey(), entry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap);
when(mPowerUsageFeatureProvider.getHideBackgroundUsageTimeSet(mContext))
.thenReturn(new HashSet(Arrays.asList((CharSequence) "package3")));
.thenReturn(new HashSet(Arrays.asList((CharSequence) "package3")));
final Map<Integer, List<BatteryDiffEntry>> purgedResultMap =
ConvertUtils.getIndexedUsageMap(
mContext, /*timeSlotSize=*/ 1, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true);
ConvertUtils.getIndexedUsageMap(
mContext, /*timeSlotSize=*/ 1, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true);
final BatteryDiffEntry resultEntry = purgedResultMap.get(0).get(0);
assertThat(resultEntry.mBackgroundUsageTimeInMs).isEqualTo(0);
@@ -355,7 +430,7 @@ public final class ConvertUtilsTest {
@Test
public void getLocale_nullContext_returnDefaultLocale() {
assertThat(ConvertUtils.getLocale(/*context=*/ null))
.isEqualTo(Locale.getDefault());
.isEqualTo(Locale.getDefault());
}
@Test
@@ -370,6 +445,71 @@ public final class ConvertUtilsTest {
assertThat(ConvertUtils.getLocale(mContext)).isEqualTo(Locale.getDefault());
}
@Test
public void resolveMultiUsersData_replaceOtherUsersItemWithExpectedEntry() {
final int currentUserId = mContext.getUserId();
final Map<Integer, List<BatteryDiffEntry>> entryMap = new HashMap<>();
// Without other users time slot.
entryMap.put(0, Arrays.asList(
createBatteryDiffEntry(
currentUserId,
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*consumePercentage=*/ 50)));
// With other users time slot.
final List<BatteryDiffEntry> withOtherUsersList = new ArrayList<>();
entryMap.put(1, withOtherUsersList);
withOtherUsersList.add(
createBatteryDiffEntry(
currentUserId + 1,
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY,
/*consumePercentage=*/ 20));
withOtherUsersList.add(
createBatteryDiffEntry(
currentUserId + 2,
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*consumePercentage=*/ 30));
withOtherUsersList.add(
createBatteryDiffEntry(
currentUserId + 3,
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*consumePercentage=*/ 40));
ConvertUtils.resolveMultiUsersData(mContext, entryMap);
assertThat(entryMap.get(0).get(0).getPercentOfTotal()).isEqualTo(50);
// Asserts with other users items.
final List<BatteryDiffEntry> entryList = entryMap.get(1);
assertThat(entryList).hasSize(2);
assertBatteryDiffEntry(
entryList.get(0),
currentUserId + 1,
/*uid=*/ 0,
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY,
/*consumePercentage=*/ 20);
assertBatteryDiffEntry(
entryList.get(1),
BatteryUtils.UID_OTHER_USERS,
BatteryUtils.UID_OTHER_USERS,
ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*consumePercentage=*/ 70);
}
private BatteryDiffEntry createBatteryDiffEntry(
long userId, int counsumerType, double consumePercentage) {
final ContentValues values = new ContentValues();
values.put(BatteryHistEntry.KEY_USER_ID, userId);
values.put(BatteryHistEntry.KEY_CONSUMER_TYPE, counsumerType);
final BatteryDiffEntry batteryDiffEntry =
new BatteryDiffEntry(
mContext,
/*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0,
/*consumePower=*/ consumePercentage,
new BatteryHistEntry(values));
batteryDiffEntry.setTotalConsumePower(100f);
return batteryDiffEntry;
}
private static BatteryHistEntry createBatteryHistEntry(
String packageName, String appLabel, double consumePower,
long uid, long foregroundUsageTimeInMs, long backgroundUsageTimeInMs) {
@@ -379,15 +519,24 @@ public final class ConvertUtilsTest {
values.put(BatteryHistEntry.KEY_APP_LABEL, appLabel);
values.put(BatteryHistEntry.KEY_UID, Long.valueOf(uid));
values.put(BatteryHistEntry.KEY_CONSUMER_TYPE,
Integer.valueOf(ConvertUtils.CONSUMER_TYPE_UID_BATTERY));
Integer.valueOf(ConvertUtils.CONSUMER_TYPE_UID_BATTERY));
values.put(BatteryHistEntry.KEY_CONSUME_POWER, consumePower);
values.put(BatteryHistEntry.KEY_FOREGROUND_USAGE_TIME,
Long.valueOf(foregroundUsageTimeInMs));
Long.valueOf(foregroundUsageTimeInMs));
values.put(BatteryHistEntry.KEY_BACKGROUND_USAGE_TIME,
Long.valueOf(backgroundUsageTimeInMs));
Long.valueOf(backgroundUsageTimeInMs));
return new BatteryHistEntry(values);
}
private static void assertBatteryDiffEntry(
BatteryDiffEntry entry, long userId, long uid, int counsumerType,
double consumePercentage) {
assertThat(entry.mBatteryHistEntry.mUid).isEqualTo(uid);
assertThat(entry.mBatteryHistEntry.mUserId).isEqualTo(userId);
assertThat(entry.mBatteryHistEntry.mConsumerType).isEqualTo(counsumerType);
assertThat(entry.getPercentOfTotal()).isEqualTo(consumePercentage);
}
private static void assertBatteryDiffEntry(
BatteryDiffEntry entry, int percentOfTotal,
long foregroundUsageTimeInMs, long backgroundUsageTimeInMs) {
@@ -395,4 +544,9 @@ public final class ConvertUtilsTest {
assertThat(entry.mForegroundUsageTimeInMs).isEqualTo(foregroundUsageTimeInMs);
assertThat(entry.mBackgroundUsageTimeInMs).isEqualTo(backgroundUsageTimeInMs);
}
private static Long generateTimestamp(int index) {
// "2021-04-23 07:00:00 UTC" + index hours
return 1619247600000L + index * DateUtils.HOUR_IN_MILLIS;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,14 +14,13 @@
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
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 android.content.Context;
import android.widget.ImageView;
@@ -74,7 +73,7 @@ public final class ExpandDividerPreferenceTest {
@Test
public void testOnClick_switchExpandStateAndInvokeCallback() {
final boolean[] isExpandedArray = new boolean[] {false};
final boolean[] isExpandedArray = new boolean[]{false};
mExpandDividerPreference.mImageView = mImageView;
mExpandDividerPreference.setOnExpandListener(
isExpanded -> isExpandedArray[0] = isExpanded);
@@ -94,7 +93,7 @@ public final class ExpandDividerPreferenceTest {
@Test
public void testSetIsExpanded_updateStateButNotInvokeCallback() {
final boolean[] isExpandedArray = new boolean[] {false};
final boolean[] isExpandedArray = new boolean[]{false};
mExpandDividerPreference.mImageView = mImageView;
mExpandDividerPreference.setOnExpandListener(
isExpanded -> isExpandedArray[0] = isExpanded);

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2017 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat;
@@ -55,7 +55,7 @@ public class PowerGaugePreferenceTest {
mContext = RuntimeEnvironment.application;
mRootView = LayoutInflater.from(mContext).inflate(R.layout.preference_app, null);
mWidgetView =
LayoutInflater.from(mContext).inflate(R.layout.preference_widget_summary, null);
LayoutInflater.from(mContext).inflate(R.layout.preference_widget_summary, null);
final LinearLayout widgetFrame = mRootView.findViewById(android.R.id.widget_frame);
assertThat(widgetFrame).isNotNull();
widgetFrame.addView(mWidgetView);

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2017 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2016 The Android Open Source Project
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
package com.android.settings.fuelgauge.batteryusage;
import static com.android.settings.fuelgauge.PowerUsageSummary.BATTERY_INFO_LOADER;
import static com.android.settings.fuelgauge.PowerUsageSummary.KEY_BATTERY_ERROR;
import static com.android.settings.fuelgauge.PowerUsageSummary.KEY_BATTERY_USAGE;
import static com.android.settings.fuelgauge.batteryusage.PowerUsageSummary.BATTERY_INFO_LOADER;
import static com.android.settings.fuelgauge.batteryusage.PowerUsageSummary.KEY_BATTERY_ERROR;
import static com.android.settings.fuelgauge.batteryusage.PowerUsageSummary.KEY_BATTERY_USAGE;
import static com.google.common.truth.Truth.assertThat;
@@ -44,6 +44,8 @@ import androidx.preference.PreferenceScreen;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
import com.android.settings.fuelgauge.BatteryBroadcastReceiver;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.XmlTestUtils;
@@ -55,6 +57,7 @@ import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@@ -74,6 +77,7 @@ public class PowerUsageSummaryTest {
public static void beforeClass() {
sAdditionalBatteryInfoIntent = new Intent("com.example.app.ADDITIONAL_BATTERY_INFO");
}
@Mock
private SettingsActivity mSettingsActivity;
@Mock
@@ -111,7 +115,7 @@ public class PowerUsageSummaryTest {
.thenReturn(sAdditionalBatteryInfoIntent);
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mRealContext))
.thenReturn(true);
mFragment.mBatteryUtils = spy(new BatteryUtils(mRealContext));
mFragment.mBatteryUtils = Mockito.spy(new BatteryUtils(mRealContext));
ReflectionHelpers.setField(mFragment, "mVisibilityLoggerMixin", mVisibilityLoggerMixin);
ReflectionHelpers.setField(mFragment, "mBatteryBroadcastReceiver",
mBatteryBroadcastReceiver);
@@ -135,17 +139,7 @@ public class PowerUsageSummaryTest {
}
@Test
public void initPreference_chartGraphEnabled_hasCorrectSummary() {
mFragment.initPreference();
verify(mBatteryUsagePreference).setSummary("View usage for past 24 hours");
}
@Test
public void initPreference_chartGraphDisabled_hasCorrectSummary() {
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mRealContext))
.thenReturn(false);
public void initPreference_hasCorrectSummary() {
mFragment.initPreference();
verify(mBatteryUsagePreference).setSummary("View usage from last full charge");

View File

@@ -1,220 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.gestures;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Application;
import android.content.res.Resources;
import android.provider.Settings;
import androidx.annotation.StringRes;
import androidx.preference.Preference;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class LongPressPowerButtonPreferenceControllerTest {
private static final String KEY_LONG_PRESS_POWER_BUTTON =
"gesture_power_menu_long_press_for_assist";
private Application mContext;
private Resources mResources;
private LongPressPowerButtonPreferenceController mController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(ApplicationProvider.getApplicationContext());
mResources = mock(Resources.class);
when(mContext.getResources()).thenReturn(mResources);
when(mResources.getString(anyInt())).thenAnswer((Answer<String>) invocation -> {
int id = invocation.getArgument(0);
return getString(id);
});
when(mResources.getBoolean(
com.android.internal.R.bool.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
mController = new LongPressPowerButtonPreferenceController(mContext,
KEY_LONG_PRESS_POWER_BUTTON);
mController.mAssistSwitch = mock(Preference.class);
mController.mFooterHint = mock(Preference.class);
}
@Test
public void isAvailable_configIsTrue_shouldReturnTrue() {
when(mResources.getBoolean(
com.android.internal.R.bool.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void isAvailable_configIsFalse_shouldReturnFalse() {
when(mResources.getBoolean(
com.android.internal.R.bool.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(false);
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void preferenceChecked_powerMenuHintTextShown() {
mController.onPreferenceChange(null, true);
verify(mController.mFooterHint).setSummary(
getString(
R.string.power_menu_power_volume_up_hint));
verify(mController.mFooterHint).setVisible(true);
}
@Test
public void preferenceUnchecked_keyChordEnabled_powerMenuHintTextShown() {
when(mResources.getInteger(
com.android.internal.R.integer.config_keyChordPowerVolumeUp))
.thenReturn(
LongPressPowerButtonPreferenceController.KEY_CHORD_POWER_VOLUME_UP_GLOBAL_ACTIONS);
mController.onPreferenceChange(null, false);
verify(mController.mFooterHint).setSummary(
getString(
R.string.power_menu_power_volume_up_hint));
verify(mController.mFooterHint).setVisible(true);
}
@Test
public void preferenceChecked_hushGestureEnabled_powerMenuHintTextIncludesHushHint() {
when(mResources.getBoolean(
com.android.internal.R.bool.config_volumeHushGestureEnabled))
.thenReturn(true);
mController.onPreferenceChange(null, true);
verify(mController.mFooterHint).setSummary(
getString(
R.string.power_menu_power_volume_up_hint) + "\n\n"
+ getString(
R.string.power_menu_power_prevent_ringing_hint));
verify(mController.mFooterHint).setVisible(true);
}
@Test
public void preferenceUnchecked_keyChordDisabled_powerMenuHintTextHidden() {
mController.onPreferenceChange(null, false);
when(mResources.getInteger(
com.android.internal.R.integer.config_keyChordPowerVolumeUp))
.thenReturn(
LongPressPowerButtonPreferenceController.KEY_CHORD_POWER_VOLUME_UP_NO_ACTION);
verify(mController.mFooterHint).setVisible(false);
}
@Test
public void preferenceChecked_longPressPowerSettingSetToAssistant() {
mController.onPreferenceChange(null, true);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS, -1)).isEqualTo(
PowerMenuSettingsUtils.LONG_PRESS_POWER_ASSISTANT_VALUE);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.KEY_CHORD_POWER_VOLUME_UP, -1)).isEqualTo(
LongPressPowerButtonPreferenceController.KEY_CHORD_POWER_VOLUME_UP_GLOBAL_ACTIONS);
}
@Test
public void preferenceUnchecked_longPressPowerSettingSetToDefaultValue() {
when(mResources.getInteger(
com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(
PowerMenuSettingsUtils.LONG_PRESS_POWER_GLOBAL_ACTIONS);
mController.onPreferenceChange(null, false);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS, -1)).isEqualTo(
PowerMenuSettingsUtils.LONG_PRESS_POWER_GLOBAL_ACTIONS);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.KEY_CHORD_POWER_VOLUME_UP, -1)).isEqualTo(
LongPressPowerButtonPreferenceController.KEY_CHORD_POWER_VOLUME_UP_NO_ACTION);
verify(mController.mAssistSwitch).setSummary(
getString(
R.string.power_menu_summary_long_press_for_assist_disabled_with_power_menu));
}
@Test
public void preferenceUnchecked_muteChordDefault_longPressPowerSettingSetToDefaultValue() {
// Value out of range chosen deliberately.
when(mResources.getInteger(
com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(8);
when(mResources.getInteger(
com.android.internal.R.integer.config_keyChordPowerVolumeUp))
.thenReturn(
LongPressPowerButtonPreferenceController.KEY_CHORD_POWER_VOLUME_UP_MUTE_TOGGLE);
mController.onPreferenceChange(null, false);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS, -1)).isEqualTo(8);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.KEY_CHORD_POWER_VOLUME_UP, -1)).isEqualTo(
LongPressPowerButtonPreferenceController.KEY_CHORD_POWER_VOLUME_UP_MUTE_TOGGLE);
}
@Test
public void preferenceUnchecked_assistDefault_setNoAction() {
// Ensure that the Assistant is the default behavior for LPP.
when(mResources.getInteger(
com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(
PowerMenuSettingsUtils.LONG_PRESS_POWER_ASSISTANT_VALUE);
mController.onPreferenceChange(null, false);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS, -1)).isEqualTo(
PowerMenuSettingsUtils.LONG_PRESS_POWER_GLOBAL_ACTIONS);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.KEY_CHORD_POWER_VOLUME_UP, -1)).isEqualTo(
LongPressPowerButtonPreferenceController.KEY_CHORD_POWER_VOLUME_UP_NO_ACTION);
verify(mController.mAssistSwitch).setSummary(getString(
R.string.power_menu_summary_long_press_for_assist_disabled_with_power_menu));
}
private String getString(@StringRes int id) {
return ApplicationProvider.getApplicationContext().getString(id);
}
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.gestures;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.app.Application;
import android.content.res.Resources;
import android.text.TextUtils;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settingslib.widget.FooterPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class LongPressPowerFooterPreferenceControllerTest {
private Application mContext;
private Resources mResources;
private Preference mPreference;
private LongPressPowerFooterPreferenceController mController;
@Before
public void setUp() {
mContext = spy(ApplicationProvider.getApplicationContext());
mResources = spy(mContext.getResources());
when(mContext.getResources()).thenReturn(mResources);
mPreference = new FooterPreference(mContext);
mController = new LongPressPowerFooterPreferenceController(mContext, "test_key");
PreferenceScreen mScreen = mock(PreferenceScreen.class);
when(mScreen.findPreference("test_key")).thenReturn(mPreference);
mController.displayPreference(mScreen);
}
@Test
public void updateState_longPressPowerForPowerMenu_hidesPreference() {
PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
mController.updateState(mPreference);
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void updateState_longPressPowerForAssistant_showsPreference() {
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
mController.updateState(mPreference);
assertThat(mPreference.isVisible()).isTrue();
}
@Test
public void updateState_notEligible_showsPreference() {
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
mController.updateState(mPreference);
assertThat(mPreference.isVisible()).isTrue();
}
@Test
public void updateState_hushGestureEnabled_includesPreventRingingHint() {
when(mResources.getBoolean(com.android.internal.R.bool.config_volumeHushGestureEnabled))
.thenReturn(true);
mController.updateState(mPreference);
assertThat(mPreference.getSummary().toString())
.isEqualTo(
TextUtils.concat(
mContext.getString(R.string.power_menu_power_volume_up_hint),
"\n\n",
mContext.getString(
R.string.power_menu_power_prevent_ringing_hint)));
}
@Test
public void updateState_hushGestureDisabled_doesNotIncludePreventRingingHint() {
when(mResources.getBoolean(com.android.internal.R.bool.config_volumeHushGestureEnabled))
.thenReturn(false);
mController.updateState(mPreference);
assertThat(mPreference.getSummary().toString())
.isEqualTo(mContext.getString(R.string.power_menu_power_volume_up_hint));
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.gestures;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.app.Application;
import android.content.res.Resources;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.core.BasePreferenceController;
import com.android.settingslib.widget.SelectorWithWidgetPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class LongPressPowerForAssistantPreferenceControllerTest {
private Application mContext;
private Resources mResources;
private SelectorWithWidgetPreference mPreference;
private LongPressPowerForAssistantPreferenceController mController;
@Before
public void setUp() {
mContext = spy(ApplicationProvider.getApplicationContext());
mResources = spy(mContext.getResources());
mPreference = new SelectorWithWidgetPreference(mContext);
mController = new LongPressPowerForAssistantPreferenceController(mContext, "test_key");
when(mContext.getResources()).thenReturn(mResources);
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(5); // Default to Assistant
PreferenceScreen mScreen = mock(PreferenceScreen.class);
when(mScreen.findPreference("test_key")).thenReturn(mPreference);
mController.displayPreference(mScreen);
mController.onStart();
}
@Test
public void initialState_longPressPowerForPowerMenu_preferenceNotChecked() {
PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void initialState_longPressPowerForAssistant_preferenceChecked() {
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void getAvailabilityStatus_longPressPowerSettingAvailable_returnsAvailable() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getAvailabilityStatus_longPressPowerSettingNotAvailable_returnsNotAvailable() {
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(false);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void onClick_updatesSettingsValue_checksPreference() {
// Initial state: preference not checked
PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
mController.updateState(mPreference);
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistantEnabled(mContext)).isFalse();
assertThat(mPreference.isChecked()).isFalse();
mPreference.performClick();
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistantEnabled(mContext)).isTrue();
assertThat(mPreference.isChecked()).isTrue();
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.gestures;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.app.Application;
import android.content.res.Resources;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.core.BasePreferenceController;
import com.android.settingslib.widget.SelectorWithWidgetPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class LongPressPowerForPowerMenuPreferenceControllerTest {
private Application mContext;
private Resources mResources;
private SelectorWithWidgetPreference mPreference;
private LongPressPowerForPowerMenuPreferenceController mController;
@Before
public void setUp() {
mContext = spy(ApplicationProvider.getApplicationContext());
mResources = spy(mContext.getResources());
mPreference = new SelectorWithWidgetPreference(mContext);
mController = new LongPressPowerForPowerMenuPreferenceController(mContext, "test_key");
when(mContext.getResources()).thenReturn(mResources);
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(5); // Default to Assistant
PreferenceScreen mScreen = mock(PreferenceScreen.class);
when(mScreen.findPreference("test_key")).thenReturn(mPreference);
mController.displayPreference(mScreen);
mController.onStart();
}
@Test
public void initialState_longPressPowerForPowerMenu_preferenceChecked() {
PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void initialState_longPressPowerForAssistant_preferenceNotChecked() {
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void getAvailabilityStatus_longPressPowerSettingAvailable_returnsAvailable() {
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getAvailabilityStatus_longPressPowerSettingNotAvailable_returnsNotAvailable() {
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(false);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void onClick_updatesSettingsValue_checksPreference() {
// Initial state: preference not checked
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
mController.updateState(mPreference);
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistantEnabled(mContext)).isTrue();
assertThat(mPreference.isChecked()).isFalse();
mPreference.performClick();
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistantEnabled(mContext)).isFalse();
assertThat(mPreference.isChecked()).isTrue();
}
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.gestures;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.app.Application;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settingslib.widget.IllustrationPreference;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class LongPressPowerIllustrationPreferenceControllerTest {
private Application mContext;
private IllustrationPreference mPreference;
private LongPressPowerIllustrationPreferenceController mController;
@Before
public void setUp() {
mContext = ApplicationProvider.getApplicationContext();
mPreference = new IllustrationPreference(mContext);
mController = new LongPressPowerIllustrationPreferenceController(mContext, "test_key");
PreferenceScreen mScreen = mock(PreferenceScreen.class);
when(mScreen.findPreference("test_key")).thenReturn(mPreference);
mController.displayPreference(mScreen);
}
@Test
public void updateState_longPressPowerForPowerMenu_showsPowerMenuAnimation() {
PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
mController.updateState(mPreference);
assertThat(mPreference.getLottieAnimationResId())
.isEqualTo(R.raw.lottie_long_press_power_for_power_menu);
}
@Test
public void updateState_longPressPowerForAssistant_showsAssistantAnimation() {
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
mController.updateState(mPreference);
assertThat(mPreference.getLottieAnimationResId())
.isEqualTo(R.raw.lottie_long_press_power_for_assistant);
}
}

View File

@@ -26,14 +26,20 @@ import android.app.Application;
import android.content.res.Resources;
import android.provider.Settings;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.widget.LabeledSeekBarPreference;
import com.android.settingslib.testutils.shadow.ShadowInteractionJankMonitor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowInteractionJankMonitor.class})
public class LongPressPowerSensitivityPreferenceControllerTest {
private static final String KEY_LONG_PRESS_SENSITIVITY =
@@ -43,7 +49,9 @@ public class LongPressPowerSensitivityPreferenceControllerTest {
private Application mContext;
private Resources mResources;
private LabeledSeekBarPreference mPreference;
private LongPressPowerSensitivityPreferenceController mController;
private PreferenceScreen mScreen;
@Before
public void setUp() {
@@ -52,11 +60,22 @@ public class LongPressPowerSensitivityPreferenceControllerTest {
when(mContext.getResources()).thenReturn(mResources);
when(mResources.getIntArray(
com.android.internal.R.array.config_longPressOnPowerDurationSettings))
com.android.internal.R.array.config_longPressOnPowerDurationSettings))
.thenReturn(SENSITIVITY_VALUES);
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(5); // Default to Assistant
mPreference = new LabeledSeekBarPreference(mContext, null);
mController = new LongPressPowerSensitivityPreferenceController(mContext,
KEY_LONG_PRESS_SENSITIVITY);
mScreen = mock(PreferenceScreen.class);
when(mScreen.findPreference(KEY_LONG_PRESS_SENSITIVITY)).thenReturn(mPreference);
mController.displayPreference(mScreen);
}
@Test
@@ -98,46 +117,64 @@ public class LongPressPowerSensitivityPreferenceControllerTest {
}
@Test
public void longPressForAssistEnabled_isAvailable() {
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS,
PowerMenuSettingsUtils.LONG_PRESS_POWER_ASSISTANT_VALUE);
public void longPressForAssistant_isVisible() {
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
LongPressPowerSensitivityPreferenceController.AVAILABLE);
mController.updateState(mPreference);
assertThat(mPreference.isVisible()).isTrue();
}
@Test
public void longPressForAssistDisabled_isNotAvailableDueToDependentSetting() {
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS,
PowerMenuSettingsUtils.LONG_PRESS_POWER_NO_ACTION);
public void longPressForPowerMenu_isHidden() {
PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
LongPressPowerSensitivityPreferenceController.DISABLED_DEPENDENT_SETTING);
mController.updateState(mPreference);
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void sensitivityValuesAreNull_notAvailable() {
public void longPressPowerSettingNotAvailable_notAvailable_isHidden() {
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(false);
mController.updateState(mPreference);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(LongPressPowerSensitivityPreferenceController.UNSUPPORTED_ON_DEVICE);
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void sensitivityValuesAreNull_notAvailable_isHidden() {
when(mResources.getIntArray(
com.android.internal.R.array.config_longPressOnPowerDurationSettings))
.thenReturn(null);
mController = new LongPressPowerSensitivityPreferenceController(mContext,
KEY_LONG_PRESS_SENSITIVITY);
mController.displayPreference(mScreen);
mController.updateState(mPreference);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
LongPressPowerSensitivityPreferenceController.UNSUPPORTED_ON_DEVICE);
assertThat(mPreference.isVisible()).isFalse();
}
@Test
public void sensitivityValuesArrayTooShort_notAvailable() {
public void sensitivityValuesArrayTooShort_notAvailable_isHidden() {
when(mResources.getIntArray(
com.android.internal.R.array.config_longPressOnPowerDurationSettings))
.thenReturn(new int[]{200});
mController = new LongPressPowerSensitivityPreferenceController(mContext,
KEY_LONG_PRESS_SENSITIVITY);
mController.displayPreference(mScreen);
mController.updateState(mPreference);
assertThat(mController.getAvailabilityStatus()).isEqualTo(
LongPressPowerSensitivityPreferenceController.UNSUPPORTED_ON_DEVICE);
assertThat(mPreference.isVisible()).isFalse();
}
}

View File

@@ -18,20 +18,21 @@ package com.android.settings.gestures;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.res.Resources;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class PowerMenuPreferenceControllerTest {
@@ -41,35 +42,75 @@ public class PowerMenuPreferenceControllerTest {
private static final String KEY_GESTURE_POWER_MENU = "gesture_power_menu";
@Before
public void setUp() {
mContext = spy(RuntimeEnvironment.application);
mResources = mock(Resources.class);
when(mResources.getBoolean(
com.android.internal.R.bool.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
when(mContext.getResources()).thenReturn(mResources);
mContext = spy(ApplicationProvider.getApplicationContext());
mResources = spy(mContext.getResources());
mController = new PowerMenuPreferenceController(mContext, KEY_GESTURE_POWER_MENU);
when(mContext.getResources()).thenReturn(mResources);
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(1); // Default to power menu
}
@Test
public void getAvailabilityStatus_assistAvailable_available() {
public void getAvailabilityStatus_settingsAvailable_returnsAvailable() {
when(mResources.getBoolean(
com.android.internal.R.bool.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(1); // Default to power menu
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.AVAILABLE);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.AVAILABLE);
}
@Test
public void getAvailabilityStatus_assistUnavailable_unavailable() {
public void getAvailabilityStatus_settingsNotAvailable_returnsNotAvailable() {
when(mResources.getBoolean(
com.android.internal.R.bool.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(false);
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(false);
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(1); // Default to power menu
assertThat(mController.getAvailabilityStatus()).isEqualTo(
BasePreferenceController.UNSUPPORTED_ON_DEVICE);
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void getAvailabilityStatus_longPressPowerSettingNotAvailable_returnsNotAvailable() {
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(3); // Default to power off (unsupported setup)
assertThat(mController.getAvailabilityStatus())
.isEqualTo(BasePreferenceController.UNSUPPORTED_ON_DEVICE);
}
@Test
public void getSummary_longPressPowerToAssistant_returnsNotAvailable() {
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
assertThat(mController.getSummary().toString())
.isEqualTo(
mContext.getString(R.string.power_menu_summary_long_press_for_assistant));
}
@Test
public void getSummary_longPressPowerToPowerMenu_returnsNotAvailable() {
PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
assertThat(mController.getSummary().toString())
.isEqualTo(
mContext.getString(R.string.power_menu_summary_long_press_for_power_menu));
}
}

View File

@@ -44,48 +44,123 @@ public class PowerMenuSettingsUtilsTest {
mContext = spy(ApplicationProvider.getApplicationContext());
mResources = mock(Resources.class);
when(mContext.getResources()).thenReturn(mResources);
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(true);
}
@Test
public void longPressBehaviourValuePresent_returnsValue() {
when(mResources.getInteger(
com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(0);
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS, 1);
assertThat(PowerMenuSettingsUtils.getPowerButtonSettingValue(mContext)).isEqualTo(1);
public void isLongPressPowerForAssistantEnabled_valueSetToAssistant_returnsTrue() {
Settings.Global.putInt(
mContext.getContentResolver(), Settings.Global.POWER_BUTTON_LONG_PRESS, 5);
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistantEnabled(mContext)).isTrue();
}
@Test
public void longPressBehaviourValueNotPresent_returnsDefault() {
when(mResources.getInteger(
com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(2);
assertThat(PowerMenuSettingsUtils.getPowerButtonSettingValue(mContext)).isEqualTo(2);
public void isLongPressPowerForAssistantEnabled_valueNotSetToAssistant_returnsFalse() {
Settings.Global.putInt(
mContext.getContentResolver(), Settings.Global.POWER_BUTTON_LONG_PRESS, 3);
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistantEnabled(mContext)).isFalse();
}
@Test
public void longPressBehaviourValueSetToAssistant_isAssistEnabledReturnsTrue() {
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS, 5);
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistEnabled(mContext)).isTrue();
public void isLongPressPowerForAssistantEnabled_valueNotSet_defaultToAssistant_returnsTrue() {
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(5);
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistantEnabled(mContext)).isTrue();
}
@Test
public void longPressBehaviourValueNotSetToAssistant_isAssistEnabledReturnsFalse() {
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS, 3);
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistEnabled(mContext)).isFalse();
public void isLongPressPowerForAssistantEnabled_valueNotSet_defaultToPowerMenu_returnsFalse() {
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(1);
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistantEnabled(mContext)).isFalse();
}
@Test
public void longPressBehaviourDefaultSetToAssistant_isAssistEnabledReturnsFalse() {
when(mResources.getInteger(
com.android.internal.R.integer.config_longPressOnPowerBehavior))
public void isLongPressPowerSettingAvailable_defaultToAssistant_returnsTrue() {
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(5);
assertThat(PowerMenuSettingsUtils.isLongPressPowerSettingAvailable(mContext)).isTrue();
}
@Test
public void isLongPressPowerSettingAvailable_defaultToPowerMenu_returnsTrue() {
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(1);
assertThat(PowerMenuSettingsUtils.isLongPressPowerSettingAvailable(mContext)).isTrue();
}
@Test
public void isLongPressPowerSettingAvailable_defaultToPowerOff_returnsFalse() {
// Power off is the unsupported option in long press power settings
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(3);
assertThat(PowerMenuSettingsUtils.isLongPressPowerSettingAvailable(mContext)).isFalse();
}
assertThat(PowerMenuSettingsUtils.isLongPressPowerForAssistEnabled(mContext)).isFalse();
@Test
public void isLongPressPowerSettingAvailable_settingDisabled_returnsFalse() {
// Disable the setting
when(mResources.getBoolean(
com.android.internal.R.bool
.config_longPressOnPowerForAssistantSettingAvailable))
.thenReturn(false);
when(mResources.getInteger(com.android.internal.R.integer.config_longPressOnPowerBehavior))
.thenReturn(1);
assertThat(PowerMenuSettingsUtils.isLongPressPowerSettingAvailable(mContext)).isFalse();
}
@Test
public void setLongPressPowerForAssistant_updatesValue() throws Exception {
boolean result = PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
assertThat(result).isTrue();
assertThat(
Settings.Global.getInt(
mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS))
.isEqualTo(5);
}
@Test
public void setLongPressPowerForAssistant_updatesKeyChordValueToPowerMenu() throws Exception {
PowerMenuSettingsUtils.setLongPressPowerForAssistant(mContext);
assertThat(
Settings.Global.getInt(
mContext.getContentResolver(),
Settings.Global.KEY_CHORD_POWER_VOLUME_UP))
.isEqualTo(2);
}
@Test
public void setLongPressPowerForPowerMenu_updatesValue() throws Exception {
boolean result = PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
assertThat(result).isTrue();
assertThat(
Settings.Global.getInt(
mContext.getContentResolver(),
Settings.Global.POWER_BUTTON_LONG_PRESS))
.isEqualTo(1);
}
@Test
public void setLongPressPowerForPowerMenu_updatesKeyChordValueToDefault() throws Exception {
when(mResources.getInteger(com.android.internal.R.integer.config_keyChordPowerVolumeUp))
.thenReturn(1);
PowerMenuSettingsUtils.setLongPressPowerForPowerMenu(mContext);
assertThat(
Settings.Global.getInt(
mContext.getContentResolver(),
Settings.Global.KEY_CHORD_POWER_VOLUME_UP))
.isEqualTo(1);
}
}

View File

@@ -31,13 +31,13 @@ import androidx.slice.SliceProvider;
import androidx.slice.widget.SliceLiveData;
import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryUsageStatsLoader;
import com.android.settings.fuelgauge.batterytip.AppInfo;
import com.android.settings.fuelgauge.batterytip.BatteryTipLoader;
import com.android.settings.fuelgauge.batterytip.tips.BatteryTip;
import com.android.settings.fuelgauge.batterytip.tips.EarlyWarningTip;
import com.android.settings.fuelgauge.batterytip.tips.HighUsageTip;
import com.android.settings.fuelgauge.batterytip.tips.LowBatteryTip;
import com.android.settings.fuelgauge.batteryusage.BatteryUsageStatsLoader;
import com.android.settings.slices.SliceBackgroundWorker;
import org.junit.After;

View File

@@ -751,6 +751,15 @@ public class NetworkProviderSettingsTest {
assertThat(keys).contains(NetworkProviderSettings.PREF_KEY_WIFI_TOGGLE);
}
@Test
public void launchConfigNewNetworkFragment_fragmentIsRestricted_ignoreWifiEntry() {
mNetworkProviderSettings.mIsRestricted = true;
mNetworkProviderSettings.launchConfigNewNetworkFragment(mWifiEntry);
verify(mWifiEntry, never()).getKey();
}
@Implements(PreferenceFragmentCompat.class)
public static class ShadowPreferenceFragmentCompat {

View File

@@ -17,14 +17,15 @@
package com.android.settings.network.apn;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import android.content.ContentResolver;
@@ -34,22 +35,21 @@ import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.PersistableBundle;
import android.telephony.CarrierConfigManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.MultiSelectListPreference;
import androidx.preference.SwitchPreference;
import com.android.settings.R;
import com.android.settings.network.ProxySubscriptionManager;
import com.android.settings.network.apn.ApnEditor.ApnData;
import com.android.settings.testutils.shadow.ShadowFragment;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -103,13 +103,15 @@ public class ApnEditorTest {
private FragmentActivity mActivity;
@Mock
private ProxySubscriptionManager mProxySubscriptionMgr;
@Mock
private CarrierConfigManager mCarrierConfigManager;
@Captor
private ArgumentCaptor<Uri> mUriCaptor;
private ApnEditor mApnEditorUT;
private Context mContext;
private Resources mResources;
private PersistableBundle mBundle = new PersistableBundle();
@Before
public void setUp() {
@@ -127,6 +129,10 @@ public class ApnEditorTest {
doReturn(mContext.getTheme()).when(mActivity).getTheme();
doReturn(mContext.getContentResolver()).when(mActivity).getContentResolver();
doReturn(mCarrierConfigManager).when(mContext)
.getSystemService(Context.CARRIER_CONFIG_SERVICE);
doReturn(mBundle).when(mCarrierConfigManager).getConfigForSubId(anyInt());
setMockPreference(mContext);
mApnEditorUT.mApnData = new FakeApnData(APN_DATA);
mApnEditorUT.sNotSet = "Not Set";
@@ -379,6 +385,20 @@ public class ApnEditorTest {
verify(mApnEditorUT).finish();
}
@Test
public void testDeleteApnData_shouldNotPresentMenuWhenNotSupportAdding() {
mBundle.putBoolean(CarrierConfigManager.KEY_ALLOW_ADDING_APNS_BOOL, false);
MenuItem item = Mockito.mock(MenuItem.class);
Menu menu = Mockito.mock(Menu.class);
doReturn(item).when(menu).add(anyInt(), anyInt(), anyInt(), anyInt());
mApnEditorUT.getCarrierCustomizedConfig(mContext);
mApnEditorUT.onCreateOptionsMenu(menu, null);
verify(menu, times(0)).add(anyInt(), eq(ApnEditor.MENU_DELETE), anyInt(), anyInt());
}
@Test(expected = ClassCastException.class)
public void testApnData_invalidIntegerType_throwsInvalidTypeException() {
// GIVEN a ApnData constructed from cursor

View File

@@ -16,29 +16,71 @@
package com.android.settings.notification;
import static com.android.settings.slices.CustomSliceRegistry.VOLUME_MEDIA_URI;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.session.MediaController;
import android.net.Uri;
import androidx.slice.builders.SliceAction;
import com.android.settings.media.MediaOutputIndicatorWorker;
import com.android.settings.slices.SliceBackgroundWorker;
import com.android.settingslib.bluetooth.CachedBluetoothDevice;
import com.android.settingslib.media.BluetoothMediaDevice;
import com.android.settingslib.media.MediaDevice;
import com.android.settingslib.media.MediaOutputConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = MediaVolumePreferenceControllerTest.ShadowSliceBackgroundWorker.class)
public class MediaVolumePreferenceControllerTest {
private static final String ACTION_LAUNCH_BROADCAST_DIALOG =
"android.settings.MEDIA_BROADCAST_DIALOG";
private static MediaOutputIndicatorWorker sMediaOutputIndicatorWorker;
private MediaVolumePreferenceController mController;
private Context mContext;
@Mock
private MediaController mMediaController;
@Mock
private MediaDevice mDevice1;
@Mock
private MediaDevice mDevice2;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = new MediaVolumePreferenceController(mContext);
sMediaOutputIndicatorWorker = spy(
new MediaOutputIndicatorWorker(mContext, VOLUME_MEDIA_URI));
when(mDevice1.isBLEDevice()).thenReturn(true);
when(mDevice2.isBLEDevice()).thenReturn(false);
}
@Test
@@ -68,4 +110,83 @@ public class MediaVolumePreferenceControllerTest {
public void isPublicSlice_returnTrue() {
assertThat(mController.isPublicSlice()).isTrue();
}
@Test
public void isSupportEndItem_withBleDevice_returnsTrue() {
doReturn(mDevice1).when(sMediaOutputIndicatorWorker).getCurrentConnectedMediaDevice();
assertThat(mController.isSupportEndItem()).isTrue();
}
@Test
public void isSupportEndItem_withNonBleDevice_returnsFalse() {
doReturn(mDevice2).when(sMediaOutputIndicatorWorker).getCurrentConnectedMediaDevice();
assertThat(mController.isSupportEndItem()).isFalse();
}
@Test
public void getSliceEndItem_NotSupportEndItem_getsNullSliceAction() {
doReturn(mDevice2).when(sMediaOutputIndicatorWorker).getCurrentConnectedMediaDevice();
final SliceAction sliceAction = mController.getSliceEndItem(mContext);
assertThat(sliceAction).isNull();
}
@Test
public void getSliceEndItem_deviceIsBroadcasting_getsBroadcastIntent() {
doReturn(mDevice1).when(sMediaOutputIndicatorWorker).getCurrentConnectedMediaDevice();
doReturn(true).when(sMediaOutputIndicatorWorker).isDeviceBroadcasting();
doReturn(mMediaController).when(sMediaOutputIndicatorWorker)
.getActiveLocalMediaController();
final SliceAction sliceAction = mController.getSliceEndItem(mContext);
final PendingIntent endItemPendingIntent = sliceAction.getAction();
final PendingIntent expectedToggleIntent = getBroadcastIntent(
MediaOutputConstants.ACTION_LAUNCH_MEDIA_OUTPUT_BROADCAST_DIALOG);
assertThat(endItemPendingIntent).isEqualTo(expectedToggleIntent);
}
@Test
public void getSliceEndItem_deviceIsNotBroadcasting_getsActivityIntent() {
final MediaDevice device = mock(BluetoothMediaDevice.class);
final CachedBluetoothDevice cachedDevice = mock(CachedBluetoothDevice.class);
when(((BluetoothMediaDevice) device).getCachedDevice()).thenReturn(cachedDevice);
when(device.isBLEDevice()).thenReturn(true);
doReturn(device).when(sMediaOutputIndicatorWorker).getCurrentConnectedMediaDevice();
doReturn(false).when(sMediaOutputIndicatorWorker).isDeviceBroadcasting();
doReturn(mMediaController).when(sMediaOutputIndicatorWorker)
.getActiveLocalMediaController();
final SliceAction sliceAction = mController.getSliceEndItem(mContext);
final PendingIntent endItemPendingIntent = sliceAction.getAction();
final PendingIntent expectedPendingIntent =
getActivityIntent(ACTION_LAUNCH_BROADCAST_DIALOG);
assertThat(endItemPendingIntent).isEqualTo(expectedPendingIntent);
}
@Implements(SliceBackgroundWorker.class)
public static class ShadowSliceBackgroundWorker {
@Implementation
public static SliceBackgroundWorker getInstance(Uri uri) {
return sMediaOutputIndicatorWorker;
}
}
private PendingIntent getBroadcastIntent(String action) {
final Intent intent = new Intent(action);
intent.setPackage(MediaOutputConstants.SYSTEMUI_PACKAGE_NAME);
return PendingIntent.getBroadcast(mContext, 0 /* requestCode */, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
}
private PendingIntent getActivityIntent(String action) {
final Intent intent = new Intent(action);
return PendingIntent.getActivity(mContext, 0 /* requestCode */, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
}
}

View File

@@ -16,7 +16,12 @@
package com.android.settings.notification;
import static android.service.notification.NotificationAssistantService.ACTION_NOTIFICATION_ASSISTANT_DETAIL_SETTINGS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@@ -29,16 +34,24 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.UserManager;
import android.provider.Settings;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.testutils.shadow.ShadowSecureSettings;
import com.android.settingslib.PrimarySwitchPreference;
import org.junit.Before;
import org.junit.Test;
@@ -47,9 +60,13 @@ import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication;
import java.util.ArrayList;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class NotificationAssistantPreferenceControllerTest {
@@ -67,23 +84,48 @@ public class NotificationAssistantPreferenceControllerTest {
private NotificationBackend mBackend;
@Mock
private UserManager mUserManager;
@Mock
private PackageManager mPackageManager;
private NotificationAssistantPreferenceController mPreferenceController;
ComponentName mNASComponent = new ComponentName("a", "b");
ComponentName mNASComponent = new ComponentName("pkgname", "clsname");
private PrimarySwitchPreference mPreference;
private ShadowApplication mShadowApplication;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(ApplicationProvider.getApplicationContext());
ShadowApplication.getInstance().setSystemService(Context.USER_SERVICE, mUserManager);
mPreference = spy(new PrimarySwitchPreference(mContext));
mShadowApplication = ShadowApplication.getInstance();
mShadowApplication.setSystemService(Context.USER_SERVICE, mUserManager);
doReturn(mContext).when(mFragment).getContext();
when(mFragment.getFragmentManager()).thenReturn(mFragmentManager);
when(mFragmentManager.beginTransaction()).thenReturn(mFragmentTransaction);
when(mBackend.getDefaultNotificationAssistant()).thenReturn(mNASComponent);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
mPreferenceController = new NotificationAssistantPreferenceController(mContext);
mPreferenceController.setBackend(mBackend);
mPreferenceController.setFragment(mFragment);
mPreferenceController.getDefaultNASIntent();
final PreferenceManager preferenceManager = new PreferenceManager(mContext);
final PreferenceScreen screen = preferenceManager.createPreferenceScreen(mContext);
mPreference.setKey(NotificationAssistantPreferenceController.KEY_NAS);
screen.addPreference(mPreference);
mPreferenceController.displayPreference(screen);
when(mUserManager.getProfileIds(eq(0), anyBoolean())).thenReturn(new int[] {0, 10});
when(mUserManager.getProfileIds(eq(20), anyBoolean())).thenReturn(new int[] {20});
ActivityInfo activityInfo1 = new ActivityInfo();
activityInfo1.packageName = "pkgname";
activityInfo1.name = "name";
ResolveInfo resolveInfo1 = new ResolveInfo();
resolveInfo1.activityInfo = activityInfo1;
List<ResolveInfo> resolvers1 = new ArrayList<>();
resolvers1.add(resolveInfo1);
when(mPackageManager.queryIntentActivities(any(Intent.class), any()))
.thenReturn(resolvers1);
}
@Test
@@ -108,6 +150,34 @@ public class NotificationAssistantPreferenceControllerTest {
verify(mBackend, times(1)).setNotificationAssistantGranted(null);
}
@Test
public void testUpdateState_SettingActivityAvailable() throws Exception {
mPreferenceController.updateState(mPreference);
assertNotNull(mPreference.getIntent());
mPreference.performClick();
Intent nextIntent = Shadows.shadowOf(
(Application) ApplicationProvider.getApplicationContext()).getNextStartedActivity();
assertEquals(nextIntent.getAction(), ACTION_NOTIFICATION_ASSISTANT_DETAIL_SETTINGS);
}
@Test
public void testUpdateState_SettingActivityUnavailable() throws Exception {
when(mPackageManager.queryIntentActivities(any(Intent.class), any()))
.thenReturn(null);
mPreferenceController.updateState(mPreference);
assertNull(mPreference.getIntent());
mPreference.performClick();
Intent nextIntent = Shadows.shadowOf(
(Application) ApplicationProvider.getApplicationContext()).getNextStartedActivity();
assertNull(nextIntent);
// Verify a dialog is shown
verify(mFragmentTransaction).add(
any(NotificationAssistantDialogFragment.class), anyString());
verify(mBackend, times(0)).setNotificationAssistantGranted(any());
}
@Test
@Config(shadows = ShadowSecureSettings.class)
public void testMigrationFromSetting_userEnable_multiProfile() throws Exception {

View File

@@ -27,6 +27,7 @@ import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
import static com.android.internal.widget.LockPatternUtils.PASSWORD_TYPE_KEY;
import static com.android.settings.password.ChooseLockGeneric.CONFIRM_CREDENTIALS;
@@ -158,6 +159,21 @@ public class ChooseLockPasswordTest {
.isNotNull();
}
@Test
public void activity_shouldHaveSecureFlag() {
PasswordPolicy policy = new PasswordPolicy();
policy.quality = PASSWORD_QUALITY_ALPHABETIC;
policy.length = 10;
Intent intent = createIntentForPasswordValidation(
/* minMetrics */ policy.getMinMetrics(),
/* minComplexity= */ PASSWORD_COMPLEXITY_NONE,
/* passwordType= */ PASSWORD_QUALITY_ALPHABETIC);
ChooseLockPassword activity = buildChooseLockPasswordActivity(intent);
final int flags = activity.getWindow().getAttributes().flags;
assertThat(flags & FLAG_SECURE).isEqualTo(FLAG_SECURE);
}
@Test
public void processAndValidatePasswordRequirements_noMinPasswordComplexity() {
PasswordPolicy policy = new PasswordPolicy();

View File

@@ -16,6 +16,8 @@
package com.android.settings.password;
import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
@@ -107,6 +109,14 @@ public class ChooseLockPatternTest {
assertThat(iconView.getVisibility()).isEqualTo(View.GONE);
}
@Test
public void activity_shouldHaveSecureFlag() {
final ChooseLockPattern activity = Robolectric.buildActivity(
ChooseLockPattern.class, new IntentBuilder(application).build()).setup().get();
final int flags = activity.getWindow().getAttributes().flags;
assertThat(flags & FLAG_SECURE).isEqualTo(FLAG_SECURE);
}
private ChooseLockPattern createActivity(boolean addFingerprintExtra) {
return Robolectric.buildActivity(
ChooseLockPattern.class,

View File

@@ -27,6 +27,7 @@ import android.content.pm.PackageManager;
import android.os.UserHandle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.FragmentActivity;
@@ -192,6 +193,18 @@ public class SetupChooseLockPatternTest {
.isEqualTo(application.getString(R.string.lockpattern_retry_button_text));
}
@Test
public void createActivity_patternDescription_shouldBeShown() {
PartnerCustomizationLayout layout = mActivity.findViewById(R.id.setup_wizard_layout);
final TextView patternDescription =
layout.findViewById(R.id.sud_layout_subtitle);
assertThat(patternDescription.getVisibility()).isEqualTo(View.VISIBLE);
assertThat(patternDescription.getText()).isEqualTo(
application.getString(R.string.lockpassword_choose_your_pattern_description));
}
private ChooseLockPatternFragment findFragment(FragmentActivity activity) {
return (ChooseLockPatternFragment)
activity.getSupportFragmentManager().findFragmentById(R.id.main_content);

View File

@@ -21,6 +21,7 @@ import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -30,6 +31,7 @@ import android.content.Context;
import androidx.preference.Preference;
import com.android.settings.enterprise.EnterprisePrivacyFeatureProvider;
import com.android.settings.safetycenter.SafetyCenterManagerWrapper;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
@@ -52,6 +54,7 @@ public class WorkPolicyInfoPreferenceControllerTest {
mContext = RuntimeEnvironment.application;
mFakeFeatureFactory = FakeFeatureFactory.setupForTest();
mEnterpriseProvider = mFakeFeatureFactory.getEnterprisePrivacyFeatureProvider(mContext);
SafetyCenterManagerWrapper.sInstance = mock(SafetyCenterManagerWrapper.class);
}
@Test
@@ -72,6 +75,15 @@ public class WorkPolicyInfoPreferenceControllerTest {
assertThat(controller.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_safetyCenterEnabled_shouldReturnUnsupported() {
when(SafetyCenterManagerWrapper.get().isEnabled(mContext)).thenReturn(true);
WorkPolicyInfoPreferenceController controller =
new WorkPolicyInfoPreferenceController(mContext, "test_key");
assertThat(controller.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
}
@Test
public void handlePreferenceTreeClick_nonMatchingKey_shouldDoNothing() {
when(mEnterpriseProvider.hasWorkPolicyInfo()).thenReturn(true);

View File

@@ -21,13 +21,13 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;
import android.content.ComponentName;
import android.content.Context;
import androidx.preference.Preference;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
import com.android.settings.security.trustagent.TrustAgentManager.TrustAgentComponentInfo;
import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before;
@@ -45,6 +45,8 @@ import java.util.Collections;
@RunWith(RobolectricTestRunner.class)
public class ManageTrustAgentsPreferenceControllerTest {
@Mock
private TrustAgentManager mTrustAgentManager;
@Mock
private LockPatternUtils mLockPatternUtils;
@@ -60,6 +62,8 @@ public class ManageTrustAgentsPreferenceControllerTest {
mFeatureFactory = FakeFeatureFactory.setupForTest();
when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
.thenReturn(mLockPatternUtils);
when(mFeatureFactory.securityFeatureProvider.getTrustAgentManager())
.thenReturn(mTrustAgentManager);
mController = new ManageTrustAgentsPreferenceController(mContext, "key");
mPreference = new Preference(mContext);
mPreference.setKey(mController.getPreferenceKey());
@@ -90,7 +94,8 @@ public class ManageTrustAgentsPreferenceControllerTest {
@Test
public void updateState_isSecure_noTrustAgent_shouldShowGenericSummary() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.getEnabledTrustAgents(anyInt())).thenReturn(new ArrayList<>());
when(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, false))
.thenReturn(new ArrayList<>());
mController.updateState(mPreference);
@@ -102,8 +107,8 @@ public class ManageTrustAgentsPreferenceControllerTest {
@Test
public void updateState_isSecure_hasTrustAgent_shouldShowDetailedSummary() {
when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
when(mLockPatternUtils.getEnabledTrustAgents(anyInt())).thenReturn(
Collections.singletonList(new ComponentName("packageName", "className")));
when(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, false))
.thenReturn(Collections.singletonList(new TrustAgentComponentInfo()));
mController.updateState(mPreference);

View File

@@ -18,11 +18,27 @@ package com.android.settings.security.trustagent;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.when;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.UserInfo;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.os.UserManager;
import android.service.trust.TrustAgentService;
import com.android.internal.widget.LockPatternUtils;
import org.junit.Before;
import org.junit.Test;
@@ -30,21 +46,55 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class TrustAgentManagerTest {
private static final String CANNED_PACKAGE_NAME = "com.test.package";
private static final String CANNED_CLASS_NAME = "TestTrustAgent";
private static final String CANNED_TRUST_AGENT_TITLE = "TestTrustAgentTitle";
@Mock
private PackageManager mPackageManager;
@Mock
private Context mContext;
@Mock
private DevicePolicyManager mDevicePolicyManager;
@Mock
private LockPatternUtils mLockPatternUtils;
@Mock
private UserManager mUserManager;
@Mock
private UserInfo mUserInfo;
@Mock
private XmlResourceParser mXmlResourceParser;
@Mock
private Resources mResources;
@Mock
private TypedArray mTypedArray;
private TrustAgentManager mTrustAgentManager;
@Before
public void setUp() {
public void setUp() throws NameNotFoundException {
MockitoAnnotations.initMocks(this);
mTrustAgentManager = new TrustAgentManager();
when(mContext.getSystemService(DevicePolicyManager.class))
.thenReturn(mDevicePolicyManager);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mContext.getSystemService(Context.USER_SERVICE))
.thenReturn(mUserManager);
when(mResources.obtainAttributes(any(), any())).thenReturn(mTypedArray);
when(mPackageManager.getResourcesForApplication(any(ApplicationInfo.class)))
.thenReturn(mResources);
when(mPackageManager.getXml(any(), anyInt(), any())).thenReturn(mXmlResourceParser);
when(mUserManager.getUserInfo(anyInt())).thenReturn(mUserInfo);
}
@Test
@@ -72,4 +122,77 @@ public class TrustAgentManagerTest {
assertThat(mTrustAgentManager.shouldProvideTrust(resolveInfo, mPackageManager)).isFalse();
}
@Test
public void getAllActiveTrustAgentsAndComponentSet_returnsTrustAgents()
throws XmlPullParserException, IOException {
setUpGetActiveTrustAgents(true);
assertThat(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, false))
.isNotEmpty();
}
@Test
public void getActiveTrustAgentsAndComponentSet_componentSet_returnsTrustAgents()
throws XmlPullParserException, IOException {
setUpGetActiveTrustAgents(true);
assertThat(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, true))
.isNotEmpty();
}
@Test
public void getAllActiveTrustAgentsAndComponentNotSet_returnsTrustAgents()
throws XmlPullParserException, IOException {
setUpGetActiveTrustAgents(false);
assertThat(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, false))
.isNotEmpty();
}
@Test
public void getActiveTrustAgentsAndComponentSet_returnsEmpty()
throws XmlPullParserException, IOException {
setUpGetActiveTrustAgents(false);
assertThat(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils, true))
.isEmpty();
}
private void setUpGetActiveTrustAgents(boolean hasSettingsActivity)
throws XmlPullParserException, IOException {
String settingsActivity =
hasSettingsActivity ? CANNED_PACKAGE_NAME + "." + CANNED_CLASS_NAME : "";
when(mXmlResourceParser.next()).thenReturn(XmlPullParser.START_TAG);
when(mXmlResourceParser.getName()).thenReturn("trust-agent");
List<ResolveInfo> resolveInfos =
Collections.singletonList(createResolveInfo(hasSettingsActivity));
List<ComponentName> enabledTrustAgents =
Collections.singletonList(
new ComponentName(CANNED_PACKAGE_NAME, CANNED_CLASS_NAME));
when(mPackageManager.queryIntentServices(any(), anyInt())).thenReturn(resolveInfos);
when(mLockPatternUtils.getEnabledTrustAgents(anyInt())).thenReturn(enabledTrustAgents);
when(mUserInfo.isManagedProfile()).thenReturn(false);
when(mUserManager.getProfiles(anyInt())).thenReturn(null);
when(mPackageManager.checkPermission(TrustAgentManager.PERMISSION_PROVIDE_AGENT,
CANNED_PACKAGE_NAME)).thenReturn(PackageManager.PERMISSION_GRANTED);
when(mTypedArray.getString(com.android.internal.R.styleable.TrustAgent_title))
.thenReturn(CANNED_TRUST_AGENT_TITLE);
when(mTypedArray.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity))
.thenReturn(settingsActivity);
}
private ResolveInfo createResolveInfo(boolean hasSettingsActivity) {
ServiceInfo serviceInfo = new ServiceInfo();
Bundle metaData = new Bundle();
metaData.putInt(TrustAgentService.TRUST_AGENT_META_DATA, 1);
serviceInfo.packageName = CANNED_PACKAGE_NAME;
serviceInfo.name = CANNED_CLASS_NAME;
serviceInfo.metaData = metaData;
serviceInfo.applicationInfo = new ApplicationInfo();
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = serviceInfo;
return resolveInfo;
}
}

View File

@@ -42,6 +42,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -74,6 +75,7 @@ import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Arrays;
import java.util.concurrent.Executor;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowAlertDialogCompat.class)
@@ -81,6 +83,8 @@ public class SimSelectNotificationTest {
@Mock
private Context mContext;
@Mock
private Executor mExecutor;
@Mock
private NotificationManager mNotificationManager;
@Mock
private TelephonyManager mTelephonyManager;
@@ -94,6 +98,8 @@ public class SimSelectNotificationTest {
private SubscriptionInfo mSubInfo;
@Mock
private DisplayMetrics mDisplayMetrics;
@Mock
private SimDialogActivity mActivity;
private final String mFakeDisplayName = "fake_display_name";
private final CharSequence mFakeNotificationChannelTitle = "fake_notification_channel_title";
@@ -236,27 +242,18 @@ public class SimSelectNotificationTest {
@Test
public void onReceivePrimarySubListChange_WithDismissExtra_shouldDismiss() {
doReturn(mExecutor).when(mActivity).getMainExecutor();
SimDialogProhibitService.supportDismiss(mActivity);
Intent intent = new Intent(TelephonyManager.ACTION_PRIMARY_SUBSCRIPTION_LIST_CHANGED);
intent.putExtra(EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE,
EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DATA);
EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS);
mSimSelectNotification.onReceive(mContext, intent);
clearInvocations(mContext);
// Dismiss.
intent.putExtra(EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE,
EXTRA_DEFAULT_SUBSCRIPTION_SELECT_TYPE_DISMISS);
mSimSelectNotification.onReceive(mContext, intent);
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
verify(mContext).startActivity(intentCaptor.capture());
Intent capturedIntent = intentCaptor.getValue();
assertThat(capturedIntent).isNotNull();
assertThat(capturedIntent.getComponent().getClassName()).isEqualTo(
SimDialogActivity.class.getName());
assertThat(capturedIntent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK)
.isNotEqualTo(0);
assertThat(capturedIntent.getIntExtra(SimDialogActivity.DIALOG_TYPE_KEY, INVALID_PICK))
.isEqualTo(PICK_DISMISS);
verify(mExecutor).execute(any());
}
@Test
public void onReceivePrimarySubListChange_DualCdmaWarning_notificationShouldSend() {

View File

@@ -47,6 +47,7 @@ import com.android.settings.security.SecurityFeatureProvider;
import com.android.settings.security.SecuritySettingsFeatureProvider;
import com.android.settings.slices.SlicesFeatureProvider;
import com.android.settings.users.UserFeatureProvider;
import com.android.settings.vpn2.AdvancedVpnFeatureProvider;
import com.android.settings.wifi.WifiTrackerLibProvider;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
@@ -87,6 +88,7 @@ public class FakeFeatureFactory extends FeatureFactory {
public SecuritySettingsFeatureProvider securitySettingsFeatureProvider;
public AccessibilitySearchFeatureProvider mAccessibilitySearchFeatureProvider;
public AccessibilityMetricsFeatureProvider mAccessibilityMetricsFeatureProvider;
public AdvancedVpnFeatureProvider mAdvancedVpnFeatureProvider;
/**
* Call this in {@code @Before} method of the test class to use fake factory.
@@ -136,6 +138,7 @@ public class FakeFeatureFactory extends FeatureFactory {
securitySettingsFeatureProvider = mock(SecuritySettingsFeatureProvider.class);
mAccessibilitySearchFeatureProvider = mock(AccessibilitySearchFeatureProvider.class);
mAccessibilityMetricsFeatureProvider = mock(AccessibilityMetricsFeatureProvider.class);
mAdvancedVpnFeatureProvider = mock(AdvancedVpnFeatureProvider.class);
}
@Override
@@ -272,4 +275,9 @@ public class FakeFeatureFactory extends FeatureFactory {
public AccessibilityMetricsFeatureProvider getAccessibilityMetricsFeatureProvider() {
return mAccessibilityMetricsFeatureProvider;
}
@Override
public AdvancedVpnFeatureProvider getAdvancedVpnFeatureProvider() {
return mAdvancedVpnFeatureProvider;
}
}

View File

@@ -226,4 +226,32 @@ public class ShadowUserManager extends org.robolectric.shadows.ShadowUserManager
return new UserInfo(PRIMARY_USER_ID, null, null,
UserInfo.FLAG_INITIALIZED | UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY);
}
protected boolean setUserEphemeral(@UserIdInt int userId, boolean enableEphemeral) {
UserInfo userInfo = mUserProfileInfos.stream()
.filter(user -> user.id == userId)
.findFirst()
.orElse(super.getUserInfo(userId));
boolean isSuccess = false;
boolean isEphemeralUser =
(userInfo.flags & UserInfo.FLAG_EPHEMERAL) != 0;
boolean isEphemeralOnCreateUser =
(userInfo.flags & UserInfo.FLAG_EPHEMERAL_ON_CREATE)
!= 0;
// when user is created in ephemeral mode via FLAG_EPHEMERAL
// its state cannot be changed.
// FLAG_EPHEMERAL_ON_CREATE is used to keep track of this state
if (!isEphemeralOnCreateUser) {
isSuccess = true;
if (isEphemeralUser != enableEphemeral) {
if (enableEphemeral) {
userInfo.flags |= UserInfo.FLAG_EPHEMERAL;
} else {
userInfo.flags &= ~UserInfo.FLAG_EPHEMERAL;
}
}
}
return isSuccess;
}
}

View File

@@ -56,6 +56,7 @@ import android.view.MenuInflater;
import android.view.MenuItem;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
@@ -152,6 +153,8 @@ public class UserSettingsTest {
ReflectionHelpers.setField(mFragment, "mDefaultIconDrawable", mDefaultIconDrawable);
ReflectionHelpers.setField(mFragment, "mAddingUser", false);
ReflectionHelpers.setField(mFragment, "mMetricsFeatureProvider", mMetricsFeatureProvider);
ReflectionHelpers.setField(mFragment, "mRemoveGuestOnExitPreferenceController",
mock(RemoveGuestOnExitPreferenceController.class));
doReturn(mUserManager).when(mActivity).getSystemService(UserManager.class);
doReturn(mPackageManager).when(mActivity).getPackageManager();
@@ -178,6 +181,10 @@ public class UserSettingsTest {
mFragment.mAddSupervisedUser = mAddSupervisedUserPreference;
mFragment.mAddGuest = mAddGuestPreference;
mFragment.mUserListCategory = mock(PreferenceCategory.class);
mFragment.mGuestUserCategory = mock(PreferenceCategory.class);
mFragment.mGuestCategory = mock(PreferenceCategory.class);
mFragment.mGuestResetPreference = mock(Preference.class);
mFragment.mGuestExitPreference = mock(Preference.class);
}
@After
@@ -219,7 +226,7 @@ public class UserSettingsTest {
@Test
public void testExitGuest_ShouldLogAction() {
mUserCapabilities.mIsGuest = true;
mFragment.exitGuest();
mFragment.clearAndExitGuest();
verify(mMetricsFeatureProvider).action(any(),
eq(SettingsEnums.ACTION_USER_GUEST_EXIT_CONFIRMED));
}
@@ -227,7 +234,7 @@ public class UserSettingsTest {
@Test
public void testExitGuestWhenNotGuest_ShouldNotLogAction() {
mUserCapabilities.mIsGuest = false;
mFragment.exitGuest();
mFragment.clearAndExitGuest();
verify(mMetricsFeatureProvider, never()).action(any(),
eq(SettingsEnums.ACTION_USER_GUEST_EXIT_CONFIRMED));
}
@@ -323,7 +330,6 @@ public class UserSettingsTest {
verify(mAddGuestPreference).setVisible(true);
verify(mAddGuestPreference).setEnabled(true);
verify(mAddGuestPreference).setIcon(any(Drawable.class));
verify(mAddGuestPreference).setSelectable(true);
}
@@ -371,7 +377,6 @@ public class UserSettingsTest {
verify(mAddGuestPreference).setVisible(true);
verify(mAddGuestPreference).setEnabled(false);
verify(mAddGuestPreference).setIcon(any(Drawable.class));
verify(mAddGuestPreference).setSelectable(true);
}
@@ -473,9 +478,9 @@ public class UserSettingsTest {
mFragment.updateUserList();
ArgumentCaptor<UserPreference> captor = ArgumentCaptor.forClass(UserPreference.class);
verify(mFragment.mUserListCategory, times(2))
verify(mFragment.mGuestUserCategory, times(1))
.addPreference(captor.capture());
UserPreference guestPref = captor.getAllValues().get(1);
UserPreference guestPref = captor.getAllValues().get(0);
assertThat(guestPref.getUserId()).isEqualTo(INACTIVE_GUEST_USER_ID);
assertThat(guestPref.getTitle()).isEqualTo("Guest");
assertThat(guestPref.getIcon()).isNotNull();
@@ -595,9 +600,9 @@ public class UserSettingsTest {
mFragment.updateUserList();
ArgumentCaptor<UserPreference> captor = ArgumentCaptor.forClass(UserPreference.class);
verify(mFragment.mUserListCategory, times(2))
verify(mFragment.mGuestUserCategory, times(1))
.addPreference(captor.capture());
UserPreference userPref = captor.getAllValues().get(1);
UserPreference userPref = captor.getAllValues().get(0);
assertThat(userPref.getUserId()).isEqualTo(INACTIVE_GUEST_USER_ID);
assertThat(userPref.getSummary()).isNull();
}

View File

@@ -16,9 +16,18 @@
package com.android.settings.widget;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import androidx.preference.PreferenceViewHolder;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
@@ -26,23 +35,301 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class CardPreferenceTest {
private Context mContext;
private CardPreference mCardPreference;
private PreferenceViewHolder mHolder;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
mContext.setTheme(R.style.SettingsPreferenceTheme);
mCardPreference = new CardPreference(mContext);
Context context = ApplicationProvider.getApplicationContext();
context.setTheme(R.style.Theme_Settings);
mCardPreference = new CardPreference(context);
View rootView = View.inflate(context, R.layout.card_preference_layout, /* parent= */ null);
mHolder = PreferenceViewHolder.createInstanceForTests(rootView);
}
@Test
public void getLayoutResource() {
assertThat(mCardPreference.getLayoutResource()).isEqualTo(R.layout.card_preference_layout);
public void newACardPreference_layoutResourceShouldBeCardPreferenceLayout() {
Context context = ApplicationProvider.getApplicationContext();
context.setTheme(R.style.SettingsPreferenceTheme);
CardPreference cardPreference = new CardPreference(context);
assertThat(cardPreference.getLayoutResource()).isEqualTo(R.layout.card_preference_layout);
}
@Test
public void onBindViewHolder_noButtonVisible_buttonsLayoutShouldBeGone() {
mCardPreference.onBindViewHolder(mHolder);
assertThat(getCardPreferenceButtonsView().getVisibility()).isEqualTo(GONE);
}
@Test
public void onBindViewHolder_setPrimaryButtonVisibility_buttonsLayoutShouldBeVisible() {
mCardPreference.setPrimaryButtonVisible(true);
mCardPreference.onBindViewHolder(mHolder);
assertThat(getCardPreferenceButtonsView().getVisibility()).isEqualTo(VISIBLE);
}
@Test
public void onBindViewHolder_setPrimaryButtonVisibility_shouldApplyToPrimaryButton() {
mCardPreference.setPrimaryButtonVisible(true);
mCardPreference.onBindViewHolder(mHolder);
assertThat(getPrimaryButton().getVisibility()).isEqualTo(VISIBLE);
}
@Test
public void onBindViewHolder_setSecondaryButtonVisibility_buttonsLayoutShouldBeVisible() {
mCardPreference.setSecondaryButtonVisible(true);
mCardPreference.onBindViewHolder(mHolder);
assertThat(getCardPreferenceButtonsView().getVisibility()).isEqualTo(VISIBLE);
}
@Test
public void onBindViewHolder_setSecondaryButtonVisibility_shouldApplyToSecondaryButton() {
mCardPreference.setSecondaryButtonVisible(true);
mCardPreference.onBindViewHolder(mHolder);
assertThat(getSecondaryButton().getVisibility()).isEqualTo(VISIBLE);
}
@Test
public void onBindViewHolder_setPrimaryButtonText_shouldApplyToPrimaryButton() {
String expectedText = "primary-button";
mCardPreference.setPrimaryButtonText(expectedText);
mCardPreference.onBindViewHolder(mHolder);
assertThat(getPrimaryButton().getText().toString()).isEqualTo(expectedText);
}
@Test
public void onBindViewHolder_setSecondaryButtonText_shouldApplyToSecondaryButton() {
String expectedText = "secondary-button";
mCardPreference.setSecondaryButtonText(expectedText);
mCardPreference.onBindViewHolder(mHolder);
assertThat(getSecondaryButton().getText().toString()).isEqualTo(expectedText);
}
@Test
public void onBindViewHolder_initialTextForPrimaryButtonShouldBeEmpty() {
mCardPreference.onBindViewHolder(mHolder);
assertThat(getPrimaryButton().getText().toString()).isEqualTo("");
}
@Test
public void onBindViewHolder_initialTextForSecondaryButtonShouldBeEmpty() {
mCardPreference.onBindViewHolder(mHolder);
assertThat(getSecondaryButton().getText().toString()).isEqualTo("");
}
@Test
public void performClickOnPrimaryButton_shouldCalledClickListener() {
final boolean[] hasCalled = {false};
View.OnClickListener clickListener = v -> hasCalled[0] = true;
mCardPreference.setPrimaryButtonClickListener(clickListener);
mCardPreference.onBindViewHolder(mHolder);
getPrimaryButton().performClick();
assertThat(hasCalled[0]).isTrue();
}
@Test
public void performClickOnSecondaryButton_shouldCalledClickListener() {
final boolean[] hasCalled = {false};
View.OnClickListener clickListener = v -> hasCalled[0] = true;
mCardPreference.setSecondaryButtonClickListener(clickListener);
mCardPreference.onBindViewHolder(mHolder);
getSecondaryButton().performClick();
assertThat(hasCalled[0]).isTrue();
}
@Test
public void onBindViewHolder_primaryButtonDefaultIsGone() {
mCardPreference.onBindViewHolder(mHolder);
assertThat(getPrimaryButton().getVisibility()).isEqualTo(GONE);
}
@Test
public void onBindViewHolder_secondaryButtonDefaultIsGone() {
mCardPreference.onBindViewHolder(mHolder);
assertThat(getSecondaryButton().getVisibility()).isEqualTo(GONE);
}
@Test
public void setPrimaryButtonVisibility_setTrueAfterBindViewHolder_shouldBeVisible() {
mCardPreference.setPrimaryButtonVisible(false);
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setPrimaryButtonVisible(true);
assertThat(getPrimaryButton().getVisibility()).isEqualTo(VISIBLE);
}
@Test
public void setPrimaryButtonText_setAfterBindViewHolder_setOnUi() {
String expectedText = "123456";
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setPrimaryButtonText(expectedText);
assertThat(getPrimaryButton().getText().toString()).isEqualTo(expectedText);
}
@Test
public void setPrimaryButtonText_setNull_shouldBeEmptyText() {
final String emptyString = "";
mCardPreference.setPrimaryButtonText("1234");
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setPrimaryButtonText(null);
assertThat(getPrimaryButton().getText().toString()).isEqualTo(emptyString);
}
@Test
public void setPrimaryButtonClickListener_setAfterOnBindViewHolder() {
final String[] hasCalled = {""};
String expectedClickedResult = "was called";
View.OnClickListener clickListener = v -> hasCalled[0] = expectedClickedResult;
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setPrimaryButtonClickListener(clickListener);
getPrimaryButton().performClick();
assertThat(hasCalled[0]).isEqualTo(expectedClickedResult);
}
@Test
public void setPrimaryButtonClickListener_setNull_shouldClearTheOnClickListener() {
final String[] hasCalled = {"not called"};
View.OnClickListener clickListener = v -> hasCalled[0] = "called once";
mCardPreference.setPrimaryButtonClickListener(clickListener);
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setPrimaryButtonClickListener(null);
getPrimaryButton().performClick();
assertThat(hasCalled[0]).isEqualTo("not called");
}
@Test
public void setSecondaryButtonVisibility_setTrueAfterBindViewHolder_shouldBeVisible() {
mCardPreference.setSecondaryButtonVisible(false);
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setSecondaryButtonVisible(true);
assertThat(getSecondaryButton().getVisibility()).isEqualTo(VISIBLE);
}
@Test
public void setSecondaryButtonText_setAfterBindViewHolder_setOnUi() {
String expectedText = "10101010";
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setSecondaryButtonText(expectedText);
assertThat(getSecondaryButton().getText().toString()).isEqualTo(expectedText);
}
@Test
public void setSecondaryButtonText_setNull_shouldBeEmptyText() {
String emptyString = "";
mCardPreference.setSecondaryButtonText("1234");
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setSecondaryButtonText(null);
assertThat(getSecondaryButton().getText().toString()).isEqualTo(emptyString);
}
@Test
public void setSecondaryButtonClickListener_setAfterOnBindViewHolder() {
final String[] hasCalled = {""};
String expectedClickedResult = "2nd was called";
View.OnClickListener clickListener = v -> hasCalled[0] = expectedClickedResult;
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setSecondaryButtonClickListener(clickListener);
getSecondaryButton().performClick();
assertThat(hasCalled[0]).isEqualTo(expectedClickedResult);
}
@Test
public void setSecondaryButtonClickListener_setNull_shouldClearTheOnClickListener() {
final String[] hasCalled = {"not called"};
View.OnClickListener clickListener = v -> hasCalled[0] = "called once";
mCardPreference.setSecondaryButtonClickListener(clickListener);
mCardPreference.onBindViewHolder(mHolder);
mCardPreference.setSecondaryButtonClickListener(null);
getSecondaryButton().performClick();
assertThat(hasCalled[0]).isEqualTo("not called");
}
@Test
public void
setPrimaryButtonVisibility_onlyPrimaryButtonVisible_setGone_buttonGroupShouldBeGone() {
mCardPreference.setPrimaryButtonVisible(true);
mCardPreference.setSecondaryButtonVisible(false);
mCardPreference.onBindViewHolder(mHolder);
assertWithMessage("PreCondition: buttonsView should be Visible")
.that(getCardPreferenceButtonsView().getVisibility())
.isEqualTo(VISIBLE);
mCardPreference.setPrimaryButtonVisible(false);
assertThat(getCardPreferenceButtonsView().getVisibility()).isEqualTo(GONE);
}
@Test
public void
setSecondaryButtonVisibility_only2ndButtonVisible_setGone_buttonGroupShouldBeGone() {
mCardPreference.setPrimaryButtonVisible(false);
mCardPreference.setSecondaryButtonVisible(true);
mCardPreference.onBindViewHolder(mHolder);
assertWithMessage("PreCondition: buttonsView should be Visible")
.that(getCardPreferenceButtonsView().getVisibility())
.isEqualTo(VISIBLE);
mCardPreference.setSecondaryButtonVisible(false);
assertThat(getCardPreferenceButtonsView().getVisibility()).isEqualTo(GONE);
}
private View getCardPreferenceButtonsView() {
return mHolder.findViewById(R.id.card_preference_buttons);
}
private Button getPrimaryButton() {
return (Button) mHolder.findViewById(android.R.id.button1);
}
private Button getSecondaryButton() {
return (Button) mHolder.findViewById(android.R.id.button2);
}
}

View File

@@ -1,41 +1,180 @@
package com.android.settings.wifi;
import static com.android.settings.wifi.ConfigureWifiSettings.KEY_INSTALL_CREDENTIALS;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
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 android.annotation.Nullable;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.UserManager;
import android.view.View;
import android.widget.TextView;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.testutils.XmlTestUtils;
import com.android.settingslib.core.AbstractPreferenceController;
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.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class ConfigureWifiSettingsTest {
private Context mContext;
@Rule
public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Spy
Context mContext = ApplicationProvider.getApplicationContext();
@Mock
UserManager mUserManager;
@Mock
WifiManager mWifiManager;
@Mock
FragmentActivity mActivity;
@Mock
WifiWakeupPreferenceController mWifiWakeupPreferenceController;
@Mock
Preference mInstallCredentialsPref;
@Mock
PreferenceScreen mPreferenceScreen;
@Mock
TextView mEmptyView;
TestConfigureWifiSettings mSettings;
@Before
public void setUp() {
mContext = spy(RuntimeEnvironment.application);
when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mUserManager.isGuestUser()).thenReturn(false);
when(mActivity.getSystemService(WifiManager.class)).thenReturn(mWifiManager);
mSettings = spy(new TestConfigureWifiSettings());
when(mSettings.getContext()).thenReturn(mContext);
when(mSettings.getActivity()).thenReturn(mActivity);
when(mSettings.use(WifiWakeupPreferenceController.class))
.thenReturn(mWifiWakeupPreferenceController);
when(mSettings.findPreference(KEY_INSTALL_CREDENTIALS)).thenReturn(mInstallCredentialsPref);
}
@Test
public void onAttach_isNotGuestUser_setupController() {
when(mUserManager.isGuestUser()).thenReturn(false);
mSettings.onAttach(mContext);
verify(mWifiWakeupPreferenceController).setFragment(any());
}
@Test
public void onAttach_isGuestUser_doNotSetupController() {
when(mUserManager.isGuestUser()).thenReturn(true);
mSettings.onAttach(mContext);
verify(mWifiWakeupPreferenceController, never()).setFragment(any());
}
@Test
@Config(shadows = ShadowDashboardFragment.class)
public void onCreate_isNotGuestUser_setupPreference() {
when(mUserManager.isGuestUser()).thenReturn(false);
mSettings.onCreate(null);
verify(mInstallCredentialsPref).setOnPreferenceClickListener(any());
}
@Test
@Config(shadows = ShadowDashboardFragment.class)
public void onCreate_isGuestUser_doNotSetupPreference() {
when(mUserManager.isGuestUser()).thenReturn(true);
mSettings.onCreate(null);
verify(mInstallCredentialsPref, never()).setOnPreferenceClickListener(any());
}
@Test
@Config(shadows = ShadowDashboardFragment.class)
public void onViewCreated_isNotGuestUser_doNotRestrictUi() {
when(mUserManager.isGuestUser()).thenReturn(false);
when(mActivity.findViewById(android.R.id.empty)).thenReturn(mEmptyView);
doReturn(mPreferenceScreen).when(mSettings).getPreferenceScreen();
mSettings.onViewCreated(mock(View.class), null);
verify(mEmptyView, never()).setVisibility(View.VISIBLE);
verify(mPreferenceScreen, never()).removeAll();
}
@Test
@Config(shadows = ShadowDashboardFragment.class)
public void onViewCreated_isGuestUser_restrictUi() {
when(mUserManager.isGuestUser()).thenReturn(true);
when(mActivity.findViewById(android.R.id.empty)).thenReturn(mEmptyView);
doReturn(mPreferenceScreen).when(mSettings).getPreferenceScreen();
mSettings.onViewCreated(mock(View.class), null);
verify(mEmptyView).setVisibility(View.VISIBLE);
verify(mPreferenceScreen).removeAll();
}
@Test
@Config(qualifiers = "mcc999")
public void testNonIndexableKeys_ifPageDisabled_shouldNotIndexResource() {
public void getNonIndexableKeys_ifPageDisabled_shouldNotIndexResource() {
final List<String> niks =
ConfigureWifiSettings.SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(mContext);
final int xmlId = new ConfigureWifiSettings().getPreferenceScreenResId();
final int xmlId = mSettings.getPreferenceScreenResId();
final List<String> keys = XmlTestUtils.getKeysFromPreferenceXml(mContext, xmlId);
assertThat(keys).isNotNull();
assertThat(niks).containsAtLeastElementsIn(keys);
}
public static class TestConfigureWifiSettings extends ConfigureWifiSettings {
@Override
public <T extends AbstractPreferenceController> T use(Class<T> clazz) {
return super.use(clazz);
}
}
@Implements(DashboardFragment.class)
public static class ShadowDashboardFragment {
@Implementation
public void onCreate(Bundle icicle) {
// do nothing
}
@Implementation
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
// do nothing
}
}
}

View File

@@ -16,6 +16,8 @@
package com.android.settings.wifi;
import static com.android.settings.wifi.WifiConfigController2.WIFI_EAP_METHOD_SIM;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -86,6 +88,8 @@ public class WifiConfigController2Test {
private AndroidKeystoreAliasLoader mAndroidKeystoreAliasLoader;
@Mock
private WifiManager mWifiManager;
@Mock
Spinner mEapMethodSimSpinner;
private View mView;
private Spinner mHiddenSettingsSpinner;
private Spinner mEapCaCertSpinner;
@@ -141,6 +145,7 @@ public class WifiConfigController2Test {
mContext.getString(R.string.wifi_do_not_provide_eap_user_cert);
ipSettingsSpinner.setSelection(DHCP);
mShadowSubscriptionManager = shadowOf(mContext.getSystemService(SubscriptionManager.class));
when(mEapMethodSimSpinner.getSelectedItemPosition()).thenReturn(WIFI_EAP_METHOD_SIM);
mController = new TestWifiConfigController2(mConfigUiBase, mView, mWifiEntry,
WifiConfigUiBase2.MODE_CONNECT);
@@ -813,10 +818,7 @@ public class WifiConfigController2Test {
when(mWifiEntry.getSecurity()).thenReturn(WifiEntry.SECURITY_EAP);
mController = new TestWifiConfigController2(mConfigUiBase, mView, mWifiEntry,
WifiConfigUiBase2.MODE_CONNECT);
final Spinner eapMethodSpinner = mock(Spinner.class);
when(eapMethodSpinner.getSelectedItemPosition()).thenReturn(
WifiConfigController2.WIFI_EAP_METHOD_SIM);
mController.mEapMethodSpinner = eapMethodSpinner;
mController.mEapMethodSpinner = mEapMethodSimSpinner;
mController.loadSims();
@@ -837,10 +839,7 @@ public class WifiConfigController2Test {
mShadowSubscriptionManager.setActiveSubscriptionInfoList(Arrays.asList(subscriptionInfo));
mController = new TestWifiConfigController2(mConfigUiBase, mView, mWifiEntry,
WifiConfigUiBase2.MODE_CONNECT);
final Spinner eapMethodSpinner = mock(Spinner.class);
when(eapMethodSpinner.getSelectedItemPosition()).thenReturn(
WifiConfigController2.WIFI_EAP_METHOD_SIM);
mController.mEapMethodSpinner = eapMethodSpinner;
mController.mEapMethodSpinner = mEapMethodSimSpinner;
mController.loadSims();
@@ -848,6 +847,48 @@ public class WifiConfigController2Test {
assertThat(wifiConfiguration.carrierId).isEqualTo(carrierId);
}
@Test
public void loadSims_twoSimsWithDifferentCarrierId_showTwoSims() {
SubscriptionInfo sub1 = createMockSubscription(1, "sub1", 8888);
SubscriptionInfo sub2 = createMockSubscription(2, "sub2", 9999);
SubscriptionUtil.setAvailableSubscriptionsForTesting(Arrays.asList(sub1, sub2));
mShadowSubscriptionManager.setActiveSubscriptionInfoList(Arrays.asList(sub1, sub2));
when(mWifiEntry.getSecurity()).thenReturn(WifiEntry.SECURITY_EAP);
mController = new TestWifiConfigController2(mConfigUiBase, mView, mWifiEntry,
WifiConfigUiBase2.MODE_CONNECT);
mController.mEapMethodSpinner = mEapMethodSimSpinner;
ShadowSubscriptionManager.setDefaultDataSubscriptionId(1);
mController.loadSims();
assertThat(mController.mEapSimSpinner.getAdapter().getCount()).isEqualTo(2);
}
@Test
public void loadSims_twoSimsWithSameCarrierId_showOneDefaultDataSim() {
SubscriptionInfo sub1 = createMockSubscription(1, "sub1", 9999);
SubscriptionInfo sub2 = createMockSubscription(2, "sub2", 9999);
SubscriptionUtil.setAvailableSubscriptionsForTesting(Arrays.asList(sub1, sub2));
mShadowSubscriptionManager.setActiveSubscriptionInfoList(Arrays.asList(sub1, sub2));
when(mWifiEntry.getSecurity()).thenReturn(WifiEntry.SECURITY_EAP);
mController = new TestWifiConfigController2(mConfigUiBase, mView, mWifiEntry,
WifiConfigUiBase2.MODE_CONNECT);
mController.mEapMethodSpinner = mEapMethodSimSpinner;
ShadowSubscriptionManager.setDefaultDataSubscriptionId(1);
mController.loadSims();
assertThat(mController.mEapSimSpinner.getAdapter().getCount()).isEqualTo(1);
assertThat(mController.mEapSimSpinner.getSelectedItem().toString()).isEqualTo("sub1");
ShadowSubscriptionManager.setDefaultDataSubscriptionId(2);
mController.loadSims();
assertThat(mController.mEapSimSpinner.getAdapter().getCount()).isEqualTo(1);
assertThat(mController.mEapSimSpinner.getSelectedItem().toString()).isEqualTo("sub2");
}
@Test
public void loadCaCertificateValue_shouldPersistentAsDefault() {
setUpModifyingSavedCertificateConfigController(null, null);
@@ -940,4 +981,12 @@ public class WifiConfigController2Test {
// certificates are covered by mController.onItemSelected after showSecurityFields end.
mController.mEapMethodSpinner.setSelection(Eap.TLS);
}
private SubscriptionInfo createMockSubscription(int subId, String displayName, int carrierId) {
SubscriptionInfo sub = mock(SubscriptionInfo.class);
when(sub.getSubscriptionId()).thenReturn(subId);
when(sub.getDisplayName()).thenReturn(displayName);
when(sub.getCarrierId()).thenReturn(carrierId);
return sub;
}
}

View File

@@ -18,6 +18,7 @@ package com.android.settings.wifi;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.os.UserManager.DISALLOW_CONFIG_WIFI;
import static com.android.settings.wifi.WifiDialogActivity.REQUEST_CODE_WIFI_DPP_ENROLLEE_QR_CODE_SCANNER;
import static com.android.settings.wifi.WifiDialogActivity.RESULT_CONNECTED;
@@ -32,10 +33,12 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.KeyguardManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.UserManager;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.wifi.AccessPoint;
@@ -57,6 +60,8 @@ public class WifiDialogActivityTest {
static final String CALLING_PACKAGE = "calling_package";
static final int REQUEST_CODE = REQUEST_CODE_WIFI_DPP_ENROLLEE_QR_CODE_SCANNER;
@Mock
UserManager mUserManager;
@Mock
PackageManager mPackageManager;
@Mock
@@ -77,6 +82,8 @@ public class WifiDialogActivityTest {
Intent mResultData;
@Mock
WifiConfigController mController;
@Mock
KeyguardManager mKeyguardManager;
WifiDialogActivity mActivity;
@@ -92,7 +99,9 @@ public class WifiDialogActivityTest {
FakeFeatureFactory.setupForTest();
mActivity = spy(Robolectric.setupActivity(WifiDialogActivity.class));
when(mActivity.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mActivity.getSystemService(WifiManager.class)).thenReturn(mWifiManager);
when(mActivity.getSystemService(KeyguardManager.class)).thenReturn(mKeyguardManager);
}
@Test
@@ -211,6 +220,20 @@ public class WifiDialogActivityTest {
verify(mActivity).setResult(RESULT_CONNECTED, mResultData);
}
@Test
public void isConfigWifiAllowed_hasNoUserRestriction_returnTrue() {
when(mUserManager.hasUserRestriction(DISALLOW_CONFIG_WIFI)).thenReturn(false);
assertThat(mActivity.isConfigWifiAllowed()).isTrue();
}
@Test
public void isConfigWifiAllowed_hasUserRestriction_returnFalse() {
when(mUserManager.hasUserRestriction(DISALLOW_CONFIG_WIFI)).thenReturn(true);
assertThat(mActivity.isConfigWifiAllowed()).isFalse();
}
@Test
public void hasPermissionForResult_noCallingPackage_returnFalse() {
when(mActivity.getCallingPackage()).thenReturn(null);
@@ -274,4 +297,35 @@ public class WifiDialogActivityTest {
assertThat(result).isTrue();
}
@Test
public void dismissDialog_hasDialog_dialogDismiss() {
mActivity.mDialog = mWifiDialog;
mActivity.mDialog2 = mWifiDialog2;
mActivity.dismissDialog();
verify(mWifiDialog).dismiss();
verify(mWifiDialog2).dismiss();
}
@Test
public void onKeyguardLockedStateChanged_keyguardIsNotLocked_doNotDismissDialog() {
WifiDialogActivity.LockScreenMonitor lockScreenMonitor =
new WifiDialogActivity.LockScreenMonitor(mActivity);
lockScreenMonitor.onKeyguardLockedStateChanged(false /* isKeyguardLocked */);
verify(mActivity, never()).dismissDialog();
}
@Test
public void onKeyguardLockedStateChanged_keyguardIsLocked_dismissDialog() {
WifiDialogActivity.LockScreenMonitor lockScreenMonitor =
new WifiDialogActivity.LockScreenMonitor(mActivity);
lockScreenMonitor.onKeyguardLockedStateChanged(true /* isKeyguardLocked */);
verify(mActivity).dismissDialog();
}
}

View File

@@ -17,6 +17,8 @@ package com.android.settings.wifi;
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 android.content.Context;
@@ -252,4 +254,14 @@ public class WifiEntryPreferenceTest {
assertThat(view.findViewById(R.id.icon_button).getVisibility()).isEqualTo(View.GONE);
}
@Test
public void updateIcon_ShouldSetTintListForDrawable() {
WifiEntryPreference pref =
new WifiEntryPreference(mContext, mMockWifiEntry, mMockIconInjector);
pref.updateIcon(false /* showX */, 4 /* level */);
verify(mMockDrawable4).setTintList(any());
}
}

View File

@@ -18,11 +18,17 @@ package com.android.settings.wifi;
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 android.content.Context;
import android.os.UserManager;
import android.text.TextUtils;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.testutils.shadow.ShadowUtils;
import com.android.settingslib.wifi.WifiPermissionChecker;
@@ -32,6 +38,7 @@ 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.Robolectric;
@@ -47,6 +54,10 @@ public class WifiScanModeActivityTest {
@Rule
public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Spy
Context mContext = ApplicationProvider.getApplicationContext();
@Mock
UserManager mUserManager;
@Mock
WifiPermissionChecker mWifiPermissionChecker;
@@ -54,7 +65,11 @@ public class WifiScanModeActivityTest {
@Before
public void setUp() {
when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mUserManager.isGuestUser()).thenReturn(false);
mActivity = spy(Robolectric.setupActivity(WifiScanModeActivity.class));
when(mActivity.getApplicationContext()).thenReturn(mContext);
mActivity.mWifiPermissionChecker = mWifiPermissionChecker;
}
@@ -87,4 +102,22 @@ public class WifiScanModeActivityTest {
assertThat(mActivity.mApp).isEqualTo(APP_LABEL);
}
@Test
public void createDialog_isNotGuestUser_shouldNotFinishDialog() {
when(mUserManager.isGuestUser()).thenReturn(false);
mActivity.createDialog();
verify(mActivity, never()).finish();
}
@Test
public void createDialog_isGuestUser_shouldFinishDialog() {
when(mUserManager.isGuestUser()).thenReturn(true);
mActivity.createDialog();
verify(mActivity).finish();
}
}

View File

@@ -16,6 +16,9 @@
package com.android.settings.wifi;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.DISABLED_DEPENDENT_SETTING;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
@@ -68,6 +71,41 @@ public class WifiWakeupPreferenceControllerTest {
doReturn(true).when(mLocationManager).isLocationEnabled();
}
@Test
public void getAvailabilityStatus_fragmentIsNotNull_returnAvailable() {
mController.setFragment(mFragment);
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
}
@Test
public void getAvailabilityStatus_fragmentIsNullAndLocationDisabled_returnDisabled() {
mController.setFragment(null);
when(mLocationManager.isLocationEnabled()).thenReturn(false);
assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_DEPENDENT_SETTING);
}
@Test
public void getAvailabilityStatus_fragmentIsNullAndWifiScanDisabled_returnDisabled() {
mController.setFragment(null);
when(mWifiManager.isScanAlwaysAvailable()).thenReturn(false);
assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_DEPENDENT_SETTING);
}
@Test
public void setChecked_mFragmentIsNullLocationEnable_wifiWakeupEnable() {
mController.setFragment(null);
when(mLocationManager.isLocationEnabled()).thenReturn(true);
when(mWifiManager.isScanAlwaysAvailable()).thenReturn(true);
when(mWifiManager.isAutoWakeupEnabled()).thenReturn(false);
mController.setChecked(true);
verify(mWifiManager).setAutoWakeupEnabled(true);
}
@Test
public void setChecked_scanEnableLocationEnable_wifiWakeupEnable() {
when(mWifiManager.isAutoWakeupEnabled()).thenReturn(false);

View File

@@ -18,24 +18,38 @@ package com.android.settings.wifi.addappnetworks;
import static com.google.common.truth.Truth.assertThat;
import android.annotation.Nullable;
import android.app.IActivityManager;
import android.os.RemoteException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.annotation.Nullable;
import android.app.IActivityManager;
import android.content.Context;
import android.os.RemoteException;
import android.os.UserManager;
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.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class AddAppNetworksActivityTest {
@Rule
public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Spy
Context mContext = ApplicationProvider.getApplicationContext();
@Mock
UserManager mUserManager;
@Mock
private IActivityManager mIActivityManager;
@@ -43,10 +57,13 @@ public class AddAppNetworksActivityTest {
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mUserManager.isGuestUser()).thenReturn(false);
mActivity = Robolectric.buildActivity(FakeAddAppNetworksActivity.class).create().get();
mActivity = spy(Robolectric.buildActivity(FakeAddAppNetworksActivity.class).create().get());
when(mActivity.getApplicationContext()).thenReturn(mContext);
mActivity.mActivityManager = mIActivityManager;
fakeCallingPackage("com.android.settings");
}
@Test
@@ -84,6 +101,20 @@ public class AddAppNetworksActivityTest {
assertThat(mActivity.showAddNetworksFragment()).isFalse();
}
@Test
public void showAddNetworksFragment_isGuestUser_returnFalse() {
when(mUserManager.isGuestUser()).thenReturn(true);
assertThat(mActivity.showAddNetworksFragment()).isFalse();
}
@Test
public void showAddNetworksFragment_notGuestUser_returnTrue() {
when(mUserManager.isGuestUser()).thenReturn(false);
assertThat(mActivity.showAddNetworksFragment()).isTrue();
}
private void fakeCallingPackage(@Nullable String packageName) {
try {
when(mIActivityManager.getLaunchedFromPackage(any())).thenReturn(packageName);

View File

@@ -455,6 +455,36 @@ public class AddAppNetworksFragmentTest {
AddAppNetworksFragment.MESSAGE_SHOW_SAVE_FAILED)).isTrue();
}
@Test
public void uiConfigurationItem_putCrToDisplayedSsid_shouldRemoveCr() {
String testSsid = "\r" + FAKE_NEW_WPA_SSID + "\r";
AddAppNetworksFragment.UiConfigurationItem item =
new AddAppNetworksFragment.UiConfigurationItem(testSsid, null, 0, 0);
assertThat(item.mDisplayedSsid).isEqualTo(FAKE_NEW_WPA_SSID);
}
@Test
public void uiConfigurationItem_putLfToDisplayedSsid_shouldRemoveLf() {
String testSsid = "\n" + FAKE_NEW_WPA_SSID + "\n";
AddAppNetworksFragment.UiConfigurationItem item =
new AddAppNetworksFragment.UiConfigurationItem(testSsid, null, 0, 0);
assertThat(item.mDisplayedSsid).isEqualTo(FAKE_NEW_WPA_SSID);
}
@Test
public void uiConfigurationItem_putCrLfToDisplayedSsid_shouldRemoveCrLf() {
String testSsid = "\r\n" + FAKE_NEW_WPA_SSID + "\r\n";
AddAppNetworksFragment.UiConfigurationItem item =
new AddAppNetworksFragment.UiConfigurationItem(testSsid, null, 0, 0);
assertThat(item.mDisplayedSsid).isEqualTo(FAKE_NEW_WPA_SSID);
}
private void setUpOneScannedNetworkWithScanedLevel4() {
final ArrayList list = new ArrayList<>();
list.add(mWifiEntry);

View File

@@ -59,6 +59,7 @@ import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.provider.Settings;
import android.telephony.SubscriptionInfo;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
@@ -108,6 +109,7 @@ import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
// TODO(b/143326832): Should add test cases for connect button.
@@ -1791,4 +1793,74 @@ public class WifiDetailPreferenceController2Test {
return pref;
}
@Test
public void fineSubscriptionInfo_noMatchedCarrierId_returnNull() {
setUpSpyController();
SubscriptionInfo sub1 = mockSubscriptionInfo(1, "sim1", 1111);
SubscriptionInfo sub2 = mockSubscriptionInfo(2, "sim2", 2222);
List<SubscriptionInfo> activeSubInfos = Arrays.asList(sub1, sub2);
SubscriptionInfo info = mController.fineSubscriptionInfo(3333, activeSubInfos, 1);
assertThat(info).isNull();
info = mController.fineSubscriptionInfo(3333, activeSubInfos, 2);
assertThat(info).isNull();
}
@Test
public void fineSubscriptionInfo_diffCarrierId_returnMatchedOne() {
setUpSpyController();
SubscriptionInfo sub1 = mockSubscriptionInfo(1, "sim1", 1111);
SubscriptionInfo sub2 = mockSubscriptionInfo(2, "sim2", 2222);
List<SubscriptionInfo> activeSubInfos = Arrays.asList(sub1, sub2);
SubscriptionInfo info = mController.fineSubscriptionInfo(1111, activeSubInfos, 1);
assertThat(info).isNotNull();
assertThat(info.getDisplayName().toString()).isEqualTo("sim1");
info = mController.fineSubscriptionInfo(1111, activeSubInfos, 2);
assertThat(info).isNotNull();
assertThat(info.getDisplayName().toString()).isEqualTo("sim1");
info = mController.fineSubscriptionInfo(2222, activeSubInfos, 1);
assertThat(info).isNotNull();
assertThat(info.getDisplayName().toString()).isEqualTo("sim2");
info = mController.fineSubscriptionInfo(2222, activeSubInfos, 2);
assertThat(info).isNotNull();
assertThat(info.getDisplayName().toString()).isEqualTo("sim2");
}
@Test
public void fineSubscriptionInfo_sameCarrierId_returnDefaultDataOne() {
setUpSpyController();
SubscriptionInfo sub1 = mockSubscriptionInfo(1, "sim1", 1111);
SubscriptionInfo sub2 = mockSubscriptionInfo(2, "sim2", 1111);
List<SubscriptionInfo> activeSubInfos = Arrays.asList(sub1, sub2);
SubscriptionInfo info = mController.fineSubscriptionInfo(1111, activeSubInfos, 1);
assertThat(info).isNotNull();
assertThat(info.getDisplayName().toString()).isEqualTo("sim1");
info = mController.fineSubscriptionInfo(1111, activeSubInfos, 2);
assertThat(info).isNotNull();
assertThat(info.getDisplayName().toString()).isEqualTo("sim2");
}
private SubscriptionInfo mockSubscriptionInfo(int subId, String displayName, int carrierId) {
SubscriptionInfo info = mock(SubscriptionInfo.class);
when(info.getSubscriptionId()).thenReturn(subId);
when(info.getDisplayName()).thenReturn(displayName);
when(info.getCarrierId()).thenReturn(carrierId);
return info;
}
}

View File

@@ -16,16 +16,78 @@
package com.android.settings.wifi.dpp;
import static org.mockito.Mockito.doNothing;
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 android.content.Context;
import android.content.Intent;
import android.os.UserManager;
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.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class WifiDppConfiguratorActivityTest {
@Rule
public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Spy
Context mContext = ApplicationProvider.getApplicationContext();
@Mock
UserManager mUserManager;
WifiDppConfiguratorActivity mActivity;
Intent mIntent;
@Before
public void setUp() {
when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mUserManager.isGuestUser()).thenReturn(false);
mIntent = new Intent(WifiDppConfiguratorActivity.ACTION_CONFIGURATOR_QR_CODE_SCANNER);
mIntent.putExtra(WifiDppUtils.EXTRA_WIFI_SSID, "GoogleGuest");
mIntent.putExtra(WifiDppUtils.EXTRA_WIFI_SECURITY, "WPA");
mIntent.putExtra(WifiDppUtils.EXTRA_WIFI_PRE_SHARED_KEY, "\\012345678,");
mActivity = spy(Robolectric.setupActivity(WifiDppConfiguratorActivity.class));
when(mActivity.getApplicationContext()).thenReturn(mContext);
}
@Test
public void launchActivity_noIntentAction_shouldNotFatalException() {
WifiDppConfiguratorActivity wifiDppConfiguratorActivity =
Robolectric.setupActivity(WifiDppConfiguratorActivity.class);
}
@Test
public void handleIntent_isGuestUser_shouldFinish() {
when(mUserManager.isGuestUser()).thenReturn(true);
mActivity.handleIntent(mIntent);
verify(mActivity).finish();
}
@Test
public void handleIntent_notGuestUser_shouldNotFinish() {
when(mUserManager.isGuestUser()).thenReturn(false);
doNothing().when(mActivity).showQrCodeScannerFragment();
mActivity.handleIntent(mIntent);
verify(mActivity, never()).finish();
}
}

View File

@@ -33,6 +33,7 @@ import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.UserManager;
import androidx.slice.Slice;
import androidx.slice.SliceItem;
@@ -84,6 +85,8 @@ public class WifiSliceTest {
@Spy
Context mContext = ApplicationProvider.getApplicationContext();
@Mock
private UserManager mUserManager;
@Mock
private WifiManager mWifiManager;
@Mock
private PackageManager mPackageManager;
@@ -98,6 +101,8 @@ public class WifiSliceTest {
@Before
public void setUp() {
doReturn(mResolver).when(mContext).getContentResolver();
doReturn(mUserManager).when(mContext).getSystemService(UserManager.class);
doReturn(false).when(mUserManager).isGuestUser();
doReturn(mWifiManager).when(mContext).getSystemService(WifiManager.class);
doReturn(WifiManager.WIFI_STATE_ENABLED).when(mWifiManager).getWifiState();
when(mContext.getPackageManager()).thenReturn(mPackageManager);
@@ -114,6 +119,33 @@ public class WifiSliceTest {
mWifiSlice = new WifiSlice(mContext, mWifiRestriction);
}
@Test
public void getWifiSlice_isGuestUser_shouldReturnNoToggle() {
doReturn(true).when(mUserManager).isGuestUser();
final Slice wifiSlice = mWifiSlice.getSlice();
final SliceMetadata metadata = SliceMetadata.from(mContext, wifiSlice);
final List<SliceAction> toggles = metadata.getToggles();
assertThat(toggles).hasSize(0);
final int rows = SliceQuery.findAll(wifiSlice, FORMAT_SLICE, HINT_LIST_ITEM,
null /* nonHints */).size();
// Title row
assertThat(rows).isEqualTo(1);
}
@Test
public void getWifiSlice_isNotGuestUser_shouldHaveTitleAndToggle() {
doReturn(false).when(mUserManager).isGuestUser();
final Slice wifiSlice = mWifiSlice.getSlice();
assertThat(wifiSlice).isNotNull();
final SliceMetadata metadata = SliceMetadata.from(mContext, wifiSlice);
final List<SliceAction> toggles = metadata.getToggles();
assertThat(toggles).hasSize(1);
}
@Test
public void getWifiSlice_fromSIPackage_shouldHaveTitleAndToggle() {
when(mPackageManager.getPackagesForUid(USER_ID)).thenReturn(new String[]{mSIPackageName});