Move PreferenceControllers to member variables to prevent memory leak

- Move PreferenceControllers to xml
- Clean up the PreferenceController so that it's less tied to a fragment
- Update and clean up the related robolectric test, so there are less
  mocks needed

Bug: 352606511
Test: manually check the Color Correction screen is shown correctly, and
choosing color correction options are reflected correctly
Test: atest DaltonizerRadioButtonPreferenceControllerTest
Test: atest ToggleDaltonizerPreferenceFragmentTest
Flag: EXEMPT (moving controller to xml can't be flagged)

Change-Id: I89b9366cfd7a398bb0572d34226d31d49373fd94
This commit is contained in:
Chun-Ku Lin
2024-07-13 04:21:38 +00:00
parent dc5469cf24
commit ec61f8bea3
5 changed files with 173 additions and 292 deletions

View File

@@ -18,61 +18,65 @@ package com.android.settings.accessibility;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.provider.Settings;
import androidx.preference.Preference;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.widget.SelectorWithWidgetPreference;
import org.junit.After;
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.shadows.ShadowLooper;
/**
* Tests for {@link DaltonizerRadioButtonPreferenceController}
*/
@RunWith(RobolectricTestRunner.class)
public class DaltonizerRadioButtonPreferenceControllerTest implements
DaltonizerRadioButtonPreferenceController.OnChangeListener {
private static final String PREF_KEY = "daltonizer_mode_protanomaly";
private static final String PREF_VALUE = "11";
private static final String PREF_FAKE_VALUE = "-1";
public class DaltonizerRadioButtonPreferenceControllerTest {
private static final int DALTONIZER_MODE_INDEX = 0;
private static final String PREF_INVALID_VALUE = "-1";
private final Context mContext = ApplicationProvider.getApplicationContext();
private final String mPrefKey =
mContext.getResources()
.getStringArray(R.array.daltonizer_mode_keys)[DALTONIZER_MODE_INDEX];
private final String mPrefValue =
String.valueOf(mContext.getResources()
.getIntArray(R.array.daltonizer_type_values)[DALTONIZER_MODE_INDEX]);
private DaltonizerRadioButtonPreferenceController mController;
@Mock
private SelectorWithWidgetPreference mMockPref;
private Context mContext;
@Mock
private SelectorWithWidgetPreference mPreference;
private PreferenceScreen mScreen;
private LifecycleOwner mLifecycleOwner;
private Lifecycle mLifecycle;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = new DaltonizerRadioButtonPreferenceController(mContext, mock(Lifecycle.class),
PREF_KEY);
mController.setOnChangeListener(this);
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mMockPref);
when(mMockPref.getKey()).thenReturn(PREF_KEY);
// initialize the value as unchecked
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, PREF_INVALID_VALUE);
mController = new DaltonizerRadioButtonPreferenceController(mContext, mPrefKey);
mPreference = new SelectorWithWidgetPreference(mContext);
mPreference.setKey(mPrefKey);
mScreen = new PreferenceManager(mContext).createPreferenceScreen(mContext);
mScreen.addPreference(mPreference);
mController.displayPreference(mScreen);
mLifecycleOwner = () -> mLifecycle;
mLifecycle = new Lifecycle(mLifecycleOwner);
}
@Override
public void onCheckedChanged(Preference preference) {
mController.updateState(preference);
@After
public void cleanUp() {
mLifecycle.removeObserver(mController);
}
@Test
@@ -81,36 +85,62 @@ public class DaltonizerRadioButtonPreferenceControllerTest implements
}
@Test
public void updateState_notChecked() {
public void updateState_valueNotMatched_notChecked() {
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, PREF_FAKE_VALUE);
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, PREF_INVALID_VALUE);
mController.updateState(mMockPref);
mController.updateState(mPreference);
// the first checked state is set to false by control
verify(mMockPref, atLeastOnce()).setChecked(false);
verify(mMockPref, never()).setChecked(true);
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void updateState_checked() {
public void updateState_valueMatched_checked() {
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, PREF_VALUE);
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, mPrefValue);
mController.updateState(mMockPref);
mController.updateState(mPreference);
// the first checked state is set to false by control
verify(mMockPref, atLeastOnce()).setChecked(false);
verify(mMockPref, atLeastOnce()).setChecked(true);
assertThat(mPreference.isChecked()).isTrue();
}
@Test
public void onRadioButtonClick_shouldReturnDaltonizerValue() {
mController.onRadioButtonClicked(mMockPref);
mController.onRadioButtonClicked(mPreference);
final String accessibilityDaltonizerValue = Settings.Secure.getString(
mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER);
assertThat(accessibilityDaltonizerValue).isEqualTo(mPrefValue);
}
assertThat(accessibilityDaltonizerValue).isEqualTo(PREF_VALUE);
@Test
public void onResume_settingsValueChangedToUnmatch_preferenceBecomesUnchecked() {
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, mPrefValue);
mController.updateState(mPreference);
assertThat(mPreference.isChecked()).isTrue();
mLifecycle.addObserver(mController);
mLifecycle.handleLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_RESUME);
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, PREF_INVALID_VALUE);
ShadowLooper.idleMainLooper();
assertThat(mPreference.isChecked()).isFalse();
}
@Test
public void onPause_settingsValueChangedAndMatch_preferenceStateNotUpdated() {
assertThat(mPreference.isChecked()).isFalse();
mLifecycle.addObserver(mController);
mLifecycle.handleLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_RESUME);
mLifecycle.handleLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_PAUSE);
Settings.Secure.putString(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, mPrefValue);
ShadowLooper.idleMainLooper();
assertThat(mPreference.isChecked()).isFalse();
}
}

View File

@@ -18,53 +18,34 @@ package com.android.settings.accessibility;
import static com.android.settings.accessibility.AccessibilityUtil.State.OFF;
import static com.android.settings.accessibility.AccessibilityUtil.State.ON;
import static com.android.settings.accessibility.ToggleDaltonizerPreferenceFragment.KEY_DEUTERANOMALY;
import static com.android.settings.accessibility.ToggleDaltonizerPreferenceFragment.KEY_GRAYSCALE;
import static com.android.settings.accessibility.ToggleDaltonizerPreferenceFragment.KEY_PROTANOMALY;
import static com.android.settings.accessibility.ToggleDaltonizerPreferenceFragment.KEY_TRITANOMEALY;
import static com.android.settings.accessibility.ToggleDaltonizerPreferenceFragment.KEY_USE_SERVICE_PREFERENCE;
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.settings.SettingsEnums;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.platform.test.annotations.DisableFlags;
import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.Flags;
import android.widget.PopupWindow;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.fragment.app.Fragment;
import androidx.test.core.app.ApplicationProvider;
import com.android.settings.R;
import com.android.settings.accessibility.AccessibilityUtil.QuickSettingsTooltipType;
import com.android.settings.SettingsActivity;
import com.android.settings.testutils.XmlTestUtils;
import com.android.settings.testutils.shadow.ShadowFragment;
import com.android.settings.widget.SettingsMainSwitchPreference;
import com.android.settingslib.widget.SelectorWithWidgetPreference;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowApplication;
@@ -72,89 +53,52 @@ import java.util.List;
/** Tests for {@link ToggleDaltonizerPreferenceFragment} */
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowFragment.class)
public class ToggleDaltonizerPreferenceFragmentTest {
@Rule
public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private final Context mContext = ApplicationProvider.getApplicationContext();
private TestToggleDaltonizerPreferenceFragment mFragment;
private PreferenceScreen mScreen;
private SettingsMainSwitchPreference mSwitchPreference;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private PreferenceManager mPreferenceManager;
@Mock
private SelectorWithWidgetPreference mMockDeuteranomalyPref;
@Mock
private SelectorWithWidgetPreference mMockProtanomalyPref;
@Mock
private SelectorWithWidgetPreference mMockTritanomalyPref;
@Mock
private SelectorWithWidgetPreference mMockGrayscalePref;
@Mock
private FragmentActivity mActivity;
private ActivityController<SettingsActivity> mActivityController;
@Before
public void setUpTestFragment() {
MockitoAnnotations.initMocks(this);
public void setUp() {
Intent intent = new Intent();
intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT,
ToggleDaltonizerPreferenceFragment.class.getName());
intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, new Bundle());
mFragment = spy(new TestToggleDaltonizerPreferenceFragment(mContext));
when(mFragment.getPreferenceManager()).thenReturn(mPreferenceManager);
when(mFragment.getPreferenceManager().getContext()).thenReturn(mContext);
when(mFragment.getContext()).thenReturn(mContext);
when(mFragment.getActivity()).thenReturn(mActivity);
when(mActivity.getContentResolver()).thenReturn(mContext.getContentResolver());
mScreen = spy(new PreferenceScreen(mContext, /* attrs= */ null));
when(mScreen.findPreference(KEY_USE_SERVICE_PREFERENCE))
.thenReturn(mFragment.mToggleServiceSwitchPreference);
when(mScreen.findPreference(KEY_DEUTERANOMALY)).thenReturn(mMockDeuteranomalyPref);
when(mMockDeuteranomalyPref.getKey()).thenReturn(KEY_DEUTERANOMALY);
when(mScreen.findPreference(KEY_PROTANOMALY)).thenReturn(mMockProtanomalyPref);
when(mMockProtanomalyPref.getKey()).thenReturn(KEY_PROTANOMALY);
when(mScreen.findPreference(KEY_TRITANOMEALY)).thenReturn(mMockTritanomalyPref);
when(mMockTritanomalyPref.getKey()).thenReturn(KEY_TRITANOMEALY);
when(mScreen.findPreference(KEY_GRAYSCALE)).thenReturn(mMockGrayscalePref);
when(mMockGrayscalePref.getKey()).thenReturn(KEY_GRAYSCALE);
when(mScreen.getPreferenceManager()).thenReturn(mPreferenceManager);
doReturn(mScreen).when(mFragment).getPreferenceScreen();
mSwitchPreference = mScreen.findPreference(KEY_USE_SERVICE_PREFERENCE);
mActivityController = ActivityController.of(new SettingsActivity(), intent);
}
@Test
public void onResume_colorCorrectEnabled_shouldReturnTrue() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, ON);
mFragment.onAttach(mContext);
mFragment.onCreate(Bundle.EMPTY);
mFragment.onResume();
ToggleDaltonizerPreferenceFragment fragment = getFragmentInResumedState();
assertThat(mSwitchPreference.isChecked()).isTrue();
SettingsMainSwitchPreference switchPreference = getMainFeatureToggle(fragment);
assertThat(switchPreference.isChecked()).isTrue();
}
@Test
public void onResume_colorCorrectDisabled_shouldReturnFalse() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, OFF);
mFragment.onAttach(mContext);
mFragment.onCreate(Bundle.EMPTY);
mFragment.onResume();
ToggleDaltonizerPreferenceFragment fragment = getFragmentInResumedState();
assertThat(mSwitchPreference.isChecked()).isFalse();
SettingsMainSwitchPreference switchPreference = getMainFeatureToggle(fragment);
assertThat(switchPreference.isChecked()).isFalse();
}
@Test
public void onResume_colorCorrectEnabled_switchPreferenceChecked_notShowTooltips() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, ON);
mSwitchPreference.setChecked(true);
mFragment.onAttach(mContext);
mFragment.onCreate(Bundle.EMPTY);
mFragment.onResume();
ToggleDaltonizerPreferenceFragment fragment = getFragmentInResumedState();
SettingsMainSwitchPreference switchPreference = getMainFeatureToggle(fragment);
assertThat(switchPreference.isChecked()).isTrue();
assertThat(getLatestPopupWindow()).isNull();
}
@@ -164,12 +108,10 @@ public class ToggleDaltonizerPreferenceFragmentTest {
public void onPreferenceToggled_colorCorrectDisabled_shouldReturnTrueAndShowTooltipView() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, OFF);
mSwitchPreference.setChecked(false);
mFragment.onAttach(mContext);
mFragment.onCreateView(LayoutInflater.from(mContext), mock(ViewGroup.class), Bundle.EMPTY);
mFragment.onViewCreated(mFragment.getView(), Bundle.EMPTY);
ToggleDaltonizerPreferenceFragment fragment = getFragmentInResumedState();
SettingsMainSwitchPreference switchPreference = getMainFeatureToggle(fragment);
mFragment.onPreferenceToggled(mSwitchPreference.getKey(), true);
fragment.onPreferenceToggled(switchPreference.getKey(), true);
final boolean isEnabled = Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, OFF) == ON;
@@ -182,11 +124,10 @@ public class ToggleDaltonizerPreferenceFragmentTest {
public void onPreferenceToggled_colorCorrectEnabled_shouldReturnFalseAndNotShowTooltipView() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, ON);
mSwitchPreference.setChecked(true);
mFragment.onAttach(mContext);
mFragment.onCreate(Bundle.EMPTY);
ToggleDaltonizerPreferenceFragment fragment = getFragmentInResumedState();
SettingsMainSwitchPreference switchPreference = getMainFeatureToggle(fragment);
mFragment.onPreferenceToggled(mSwitchPreference.getKey(), false);
fragment.onPreferenceToggled(switchPreference.getKey(), false);
final boolean isEnabled = Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, OFF) == ON;
@@ -196,19 +137,25 @@ public class ToggleDaltonizerPreferenceFragmentTest {
@Test
public void getMetricsCategory_returnsCorrectCategory() {
assertThat(mFragment.getMetricsCategory()).isEqualTo(
ToggleDaltonizerPreferenceFragment fragment = getFragmentInResumedState();
assertThat(fragment.getMetricsCategory()).isEqualTo(
SettingsEnums.ACCESSIBILITY_TOGGLE_DALTONIZER);
}
@Test
public void getPreferenceScreenResId_returnsCorrectXml() {
assertThat(mFragment.getPreferenceScreenResId()).isEqualTo(
ToggleDaltonizerPreferenceFragment fragment = getFragmentInResumedState();
assertThat(fragment.getPreferenceScreenResId()).isEqualTo(
R.xml.accessibility_daltonizer_settings);
}
@Test
public void getHelpResource_returnsCorrectHelpResource() {
assertThat(mFragment.getHelpResource()).isEqualTo(R.string.help_url_color_correction);
ToggleDaltonizerPreferenceFragment fragment = getFragmentInResumedState();
assertThat(fragment.getHelpResource()).isEqualTo(R.string.help_url_color_correction);
}
@Test
@@ -228,55 +175,20 @@ public class ToggleDaltonizerPreferenceFragmentTest {
return shadowApplication.getLatestPopupWindow();
}
private static class TestToggleDaltonizerPreferenceFragment extends
ToggleDaltonizerPreferenceFragment {
private static final String PLACEHOLDER_PACKAGE_NAME = "com.placeholder.example";
private static final String PLACEHOLDER_CLASS_NAME =
PLACEHOLDER_PACKAGE_NAME + ".placeholder";
private static final ComponentName PLACEHOLDER_COMPONENT_NAME = new ComponentName(
PLACEHOLDER_PACKAGE_NAME, PLACEHOLDER_CLASS_NAME);
private static final String PLACEHOLDER_TILE_TOOLTIP_CONTENT =
PLACEHOLDER_PACKAGE_NAME + "tooltip_content";
private ToggleDaltonizerPreferenceFragment getFragmentInResumedState() {
TestToggleDaltonizerPreferenceFragment(Context context) {
super();
mComponentName = PLACEHOLDER_COMPONENT_NAME;
final SettingsMainSwitchPreference switchPreference =
new SettingsMainSwitchPreference(context);
switchPreference.setKey(KEY_USE_SERVICE_PREFERENCE);
mToggleServiceSwitchPreference = switchPreference;
setArguments(new Bundle());
}
mActivityController.create().start().resume();
Fragment fragment = mActivityController.get().getSupportFragmentManager().findFragmentById(
R.id.main_content);
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// do nothing
}
assertThat(fragment).isNotNull();
assertThat(fragment).isInstanceOf(ToggleDaltonizerPreferenceFragment.class);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return mock(View.class);
}
return (ToggleDaltonizerPreferenceFragment) fragment;
}
@Override
protected void updateShortcutPreference() {
// UI related function, do nothing in tests
}
@Override
ComponentName getTileComponentName() {
return PLACEHOLDER_COMPONENT_NAME;
}
@Override
protected CharSequence getTileTooltipContent(@QuickSettingsTooltipType int type) {
return PLACEHOLDER_TILE_TOOLTIP_CONTENT;
}
@Override
public View getView() {
return mock(View.class);
}
private SettingsMainSwitchPreference getMainFeatureToggle(
ToggleDaltonizerPreferenceFragment fragment) {
return fragment.findPreference(KEY_USE_SERVICE_PREFERENCE);
}
}