[Wi-Fi] Replace WifiTracker with WifiPickerTracker in WifiSettings

WifiSettings uses WifiTracker in SettingsLib while WifiSettings2
uses WifiPickerTracker in WifiSettingsLib.

1. Remove WifiSettings.
2. Rename WifiSettings2 to WifiSettings.
3. Remove the files only used in the removed WifiSettings.
   (Saved networks files are not included)

Bug: 152571756
Test: make RunSettingsRoboTests -j ROBOTEST_FILTER=com.android.settings.wifi
      atest WifiSettingsUiTest
Change-Id: I800b434c8049121db115cff87d51e164e4529999
This commit is contained in:
Arc Wang
2020-05-11 21:30:42 +08:00
parent 29d45e2d6b
commit 41f23de712
20 changed files with 737 additions and 3265 deletions

View File

@@ -269,25 +269,6 @@
android:value="true" />
</activity>
<activity
android:name="Settings$WifiSettings2Activity"
android:label="@string/wifi_settings"
android:icon="@drawable/ic_settings_wireless"
android:configChanges="orientation|keyboardHidden|screenSize">
<intent-filter android:priority="1">
<action android:name="android.settings.WIFI_SETTINGS2" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter android:priority="1">
<action android:name="android.intent.action.MAIN" />
<category android:name="com.android.settings.SHORTCUT" />
</intent-filter>
<meta-data android:name="com.android.settings.FRAGMENT_CLASS"
android:value="com.android.settings.wifi.WifiSettings2" />
<meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
android:value="true" />
</activity>
<activity
android:name=".wifi.WifiPickerActivity">
<intent-filter android:priority="1">

View File

@@ -17,21 +17,19 @@
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:settings="http://schemas.android.com/apk/res-auto"
android:title="@string/wifi_settings">
android:title="@string/wifi_settings"
settings:keywords="@string/keywords_wifi">
<com.android.settings.wifi.LinkablePreference
android:key="wifi_status_message"
settings:searchable="false"/>
android:key="wifi_status_message"/>
<PreferenceCategory
android:key="connected_access_point"
android:layout="@layout/preference_category_no_label"
settings:searchable="false"/>
android:layout="@layout/preference_category_no_label"/>
<PreferenceCategory
android:key="access_points"
android:layout="@layout/preference_category_no_label"
settings:searchable="false"/>
android:layout="@layout/preference_category_no_label"/>
<Preference
android:key="configure_wifi_settings"
@@ -42,10 +40,9 @@
<Preference
android:key="saved_networks"
android:title="@string/wifi_saved_access_points_label"
android:fragment="com.android.settings.wifi.savedaccesspoints.SavedAccessPointsWifiSettings"/>
android:fragment="com.android.settings.wifi.savedaccesspoints2.SavedAccessPointsWifiSettings2"/>
<com.android.settings.datausage.DataUsagePreference
android:key="wifi_data_usage"
android:title="@string/wifi_data_usage"
settings:keywords="@string/keywords_wifi_data_usage"/>
android:title="@string/wifi_data_usage"/>
</PreferenceScreen>

View File

@@ -1,48 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2019 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.
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:settings="http://schemas.android.com/apk/res-auto"
android:title="@string/wifi_settings"
settings:keywords="@string/keywords_wifi">
<com.android.settings.wifi.LinkablePreference
android:key="wifi_status_message"/>
<PreferenceCategory
android:key="connected_access_point"
android:layout="@layout/preference_category_no_label"/>
<PreferenceCategory
android:key="access_points"
android:layout="@layout/preference_category_no_label"/>
<Preference
android:key="configure_wifi_settings"
android:title="@string/wifi_configure_settings_preference_title"
settings:allowDividerAbove="true"
android:fragment="com.android.settings.wifi.ConfigureWifiSettings"/>
<Preference
android:key="saved_networks"
android:title="@string/wifi_saved_access_points_label"
android:fragment="com.android.settings.wifi.savedaccesspoints2.SavedAccessPointsWifiSettings2"/>
<com.android.settings.datausage.DataUsagePreference
android:key="wifi_data_usage"
android:title="@string/wifi_data_usage"/>
</PreferenceScreen>

View File

@@ -150,7 +150,6 @@ import com.android.settings.wifi.ConfigureWifiSettings;
import com.android.settings.wifi.WifiAPITest;
import com.android.settings.wifi.WifiInfo;
import com.android.settings.wifi.WifiSettings;
import com.android.settings.wifi.WifiSettings2;
import com.android.settings.wifi.calling.WifiCallingDisclaimerFragment;
import com.android.settings.wifi.calling.WifiCallingSettings;
import com.android.settings.wifi.p2p.WifiP2pSettings;
@@ -168,7 +167,6 @@ public class SettingsGateway {
AdvancedConnectedDeviceDashboardFragment.class.getName(),
CreateShortcut.class.getName(),
WifiSettings.class.getName(),
WifiSettings2.class.getName(),
ConfigureWifiSettings.class.getName(),
SavedAccessPointsWifiSettings.class.getName(),
SavedAccessPointsWifiSettings2.class.getName(),
@@ -323,7 +321,6 @@ public class SettingsGateway {
SupportDashboardActivity.class.getName(),
// Home page > Network & Internet
Settings.WifiSettingsActivity.class.getName(),
Settings.WifiSettings2Activity.class.getName(),
Settings.DataUsageSummaryActivity.class.getName(),
// Home page > Connected devices
Settings.BluetoothSettingsActivity.class.getName(),

View File

@@ -20,14 +20,12 @@ import android.app.settings.SettingsEnums;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.FeatureFlagUtils;
import com.android.settings.R;
import com.android.settings.SubSettings;
import com.android.settings.slices.CustomSliceRegistry;
import com.android.settings.slices.SliceBuilderUtils;
import com.android.settings.wifi.WifiSettings;
import com.android.settings.wifi.WifiSettings2;
import java.util.ArrayList;
import java.util.List;
@@ -63,20 +61,11 @@ public class WifiPanel implements PanelContent {
public Intent getSeeMoreIntent() {
final String screenTitle =
mContext.getText(R.string.wifi_settings).toString();
Intent intent;
if (FeatureFlagUtils.isEnabled(mContext, FeatureFlagUtils.SETTINGS_WIFITRACKER2)) {
intent = SliceBuilderUtils.buildSearchResultPageIntent(mContext,
WifiSettings2.class.getName(),
null /* key */,
screenTitle,
SettingsEnums.WIFI);
} else {
intent = SliceBuilderUtils.buildSearchResultPageIntent(mContext,
final Intent intent = SliceBuilderUtils.buildSearchResultPageIntent(mContext,
WifiSettings.class.getName(),
null /* key */,
screenTitle,
SettingsEnums.WIFI);
}
intent.setClassName(mContext.getPackageName(), SubSettings.class.getName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;

View File

@@ -35,7 +35,7 @@ import com.android.settings.security.SecuritySettings;
import com.android.settings.security.screenlock.ScreenLockSettings;
import com.android.settings.system.SystemDashboardFragment;
import com.android.settings.wallpaper.WallpaperSuggestionActivity;
import com.android.settings.wifi.WifiSettings2;
import com.android.settings.wifi.WifiSettings;
import java.util.Map;
@@ -55,7 +55,7 @@ public class CustomSiteMapRegistry {
CUSTOM_SITE_MAP.put(
WallpaperSuggestionActivity.class.getName(), DisplaySettings.class.getName());
CUSTOM_SITE_MAP.put(
WifiSettings2.class.getName(), NetworkDashboardFragment.class.getName());
WifiSettings.class.getName(), NetworkDashboardFragment.class.getName());
CUSTOM_SITE_MAP.put(PowerUsageAdvanced.class.getName(), PowerUsageSummary.class.getName());
CUSTOM_SITE_MAP.put(RecentLocationRequestSeeAllFragment.class.getName(),
LocationSettings.class.getName());

View File

@@ -32,7 +32,6 @@ import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.graphics.drawable.LayerDrawable;
import android.net.ConnectivityManager;
import android.util.FeatureFlagUtils;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
@@ -46,8 +45,6 @@ import androidx.preference.PreferenceGroup;
import com.android.settings.R;
import com.android.settings.Settings.TetherSettingsActivity;
import com.android.settings.Settings.WifiSettings2Activity;
import com.android.settings.Settings.WifiSettingsActivity;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
@@ -190,15 +187,6 @@ public class CreateShortcutPreferenceController extends BasePreferenceController
Log.d(TAG, "Skipping non-system app: " + info.activityInfo);
continue;
}
if (FeatureFlagUtils.isEnabled(mContext, FeatureFlagUtils.SETTINGS_WIFITRACKER2)) {
if (info.activityInfo.name.endsWith(WifiSettingsActivity.class.getSimpleName())) {
continue;
}
} else {
if (info.activityInfo.name.endsWith(WifiSettings2Activity.class.getSimpleName())) {
continue;
}
}
shortcuts.add(info);
}
Collections.sort(shortcuts, SHORTCUT_COMPARATOR);

View File

@@ -34,7 +34,10 @@ import com.android.settings.R;
import com.android.settings.core.InstrumentedFragment;
import com.android.settings.wifi.dpp.WifiDppUtils;
public class AddNetworkFragment extends InstrumentedFragment implements WifiConfigUiBase,
/**
* A full screen UI component for users to edit and add a Wi-Fi network.
*/
public class AddNetworkFragment extends InstrumentedFragment implements WifiConfigUiBase2,
View.OnClickListener {
final static String WIFI_CONFIG_KEY = "wifi_config_key";
@@ -46,7 +49,7 @@ public class AddNetworkFragment extends InstrumentedFragment implements WifiConf
private static final int REQUEST_CODE_WIFI_DPP_ENROLLEE_QR_CODE_SCANNER = 0;
private WifiConfigController mUIController;
private WifiConfigController2 mUIController;
private Button mSubmitBtn;
private Button mCancelBtn;
@@ -76,7 +79,7 @@ public class AddNetworkFragment extends InstrumentedFragment implements WifiConf
mSubmitBtn.setOnClickListener(this);
mCancelBtn.setOnClickListener(this);
ssidScannerButton.setOnClickListener(this);
mUIController = new WifiConfigController(this, rootView, null, getMode());
mUIController = new WifiConfigController2(this, rootView, null, getMode());
return rootView;
}
@@ -124,7 +127,7 @@ public class AddNetworkFragment extends InstrumentedFragment implements WifiConf
}
@Override
public WifiConfigController getController() {
public WifiConfigController2 getController() {
return mUIController;
}

View File

@@ -1,91 +0,0 @@
/*
* Copyright (C) 2018 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.wifi;
import android.net.ConnectivityManager.NetworkCallback;
import android.net.Network;
import android.net.NetworkCapabilities;
import com.android.internal.util.Preconditions;
/** Listens for changes to NetworkCapabilities to update the ConnectedAccessPointPreference. */
class CaptivePortalNetworkCallback extends NetworkCallback {
private final ConnectedAccessPointPreference mConnectedApPreference;
private final Network mNetwork;
private boolean mIsCaptivePortal;
CaptivePortalNetworkCallback(
Network network, ConnectedAccessPointPreference connectedApPreference) {
mNetwork = Preconditions.checkNotNull(network);
mConnectedApPreference = Preconditions.checkNotNull(connectedApPreference);
}
@Override
public final void onLost(Network network) {
if (mNetwork.equals(network)) {
setIsCaptivePortal(false);
}
}
@Override
public final void onCapabilitiesChanged(Network network,
NetworkCapabilities networkCapabilities) {
if (mNetwork.equals(network)) {
boolean isCaptivePortal = WifiUtils.canSignIntoNetwork(networkCapabilities);
setIsCaptivePortal(isCaptivePortal);
mConnectedApPreference.setCaptivePortal(isCaptivePortal);
}
}
/**
* Called when captive portal capability changes for the current network. Default implementation
* is a no-op. Use {@link CaptivePortalNetworkCallback#isCaptivePortal()} to read new
* capability.
*/
public void onCaptivePortalCapabilityChanged() {}
private void setIsCaptivePortal(boolean isCaptivePortal) {
if (isCaptivePortal == mIsCaptivePortal) {
return;
}
mIsCaptivePortal = isCaptivePortal;
onCaptivePortalCapabilityChanged();
}
/**
* Returns true if the supplied network and preference are not null and are the same as the
* originally supplied values.
*/
public final boolean isSameNetworkAndPreference(
Network network, ConnectedAccessPointPreference connectedApPreference) {
return mNetwork.equals(network) && mConnectedApPreference == connectedApPreference;
}
/**
* Returns true if the most recent update to the NetworkCapabilities indicates a captive portal
* network and the Network was not lost in the interim.
*/
public final boolean isCaptivePortal() {
return mIsCaptivePortal;
}
/** Returns the currently associated network. */
public final Network getNetwork() {
return mNetwork;
}
}

View File

@@ -1,178 +0,0 @@
/*
* Copyright (C) 2019 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.wifi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.settings.SettingsEnums;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.VisibleForTesting;
import com.android.settings.R;
import com.android.settings.core.InstrumentedFragment;
import com.android.settingslib.wifi.AccessPoint;
/**
* Detail page for configuring Wi-Fi network.
*
* The AccessPoint should be saved to the argument when launching this class in order to properly
* render this page.
*
* Migrating from Wi-Fi SettingsLib to to WifiTrackerLib, this object will be removed in the near
* future, please develop in {@link ConfigureWifiEntryFragment}.
*/
public class ConfigureAccessPointFragment extends InstrumentedFragment implements WifiConfigUiBase {
public static final String NETWORK_CONFIG_KEY = "network_config_key";
private static final int SUBMIT_BUTTON_ID = android.R.id.button1;
private static final int CANCEL_BUTTON_ID = android.R.id.button2;
private WifiConfigController mUiController;
private Button mSubmitBtn;
private Button mCancelBtn;
private AccessPoint mAccessPoint;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mAccessPoint = new AccessPoint(context, getArguments());
}
@Override
public int getMetricsCategory() {
return SettingsEnums.SETTINGS_WIFI_CONFIGURE_NETWORK;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.wifi_add_network_view,
container, false /* attachToRoot */);
final Button neutral = rootView.findViewById(android.R.id.button3);
if (neutral != null) {
neutral.setVisibility(View.GONE);
}
mSubmitBtn = rootView.findViewById(SUBMIT_BUTTON_ID);
mCancelBtn = rootView.findViewById(CANCEL_BUTTON_ID);
mSubmitBtn.setOnClickListener(view -> handleSubmitAction());
mCancelBtn.setOnClickListener(view -> handleCancelAction());
mUiController = new WifiConfigController(this, rootView, mAccessPoint,
getMode(), false /* requestFocus */);
/**
* For this add AccessPoint UI, need to remove the Home button, so set related feature as
* false.
*/
final ActionBar actionBar = getActivity().getActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setHomeButtonEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
}
return rootView;
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
mUiController.updatePassword();
}
@Override
public int getMode() {
return WifiConfigUiBase.MODE_CONNECT;
}
@Override
public WifiConfigController getController() {
return mUiController;
}
@Override
public void dispatchSubmit() {
handleSubmitAction();
}
@Override
public void setTitle(int id) {
getActivity().setTitle(id);
}
@Override
public void setTitle(CharSequence title) {
getActivity().setTitle(title);
}
@Override
public void setSubmitButton(CharSequence text) {
mSubmitBtn.setText(text);
}
@Override
public void setCancelButton(CharSequence text) {
mCancelBtn.setText(text);
}
@Override
public void setForgetButton(CharSequence text) {
// AddNetwork doesn't need forget button.
}
@Override
public Button getSubmitButton() {
return mSubmitBtn;
}
@Override
public Button getCancelButton() {
return mCancelBtn;
}
@Override
public Button getForgetButton() {
// AddNetwork doesn't need forget button.
return null;
}
@VisibleForTesting
void handleSubmitAction() {
final Intent intent = new Intent();
final Activity activity = getActivity();
intent.putExtra(NETWORK_CONFIG_KEY, mUiController.getConfig());
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
}
@VisibleForTesting
void handleCancelAction() {
final Activity activity = getActivity();
activity.setResult(Activity.RESULT_CANCELED);
activity.finish();
}
}

View File

@@ -1,99 +0,0 @@
/*
* Copyright (C) 2017 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.wifi;
import android.content.Context;
import android.view.View;
import androidx.annotation.DrawableRes;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceViewHolder;
import com.android.settings.R;
import com.android.settingslib.wifi.AccessPoint;
/**
* An AP preference for the currently connected AP.
*
* Migrating from Wi-Fi SettingsLib to to WifiTrackerLib, this object will be removed in the near
* future, please develop in {@link ConnectedWifiEntryPreference}.
*/
public class ConnectedAccessPointPreference extends LongPressAccessPointPreference implements
View.OnClickListener {
private OnGearClickListener mOnGearClickListener;
private boolean mIsCaptivePortal;
public ConnectedAccessPointPreference(AccessPoint accessPoint, Context context,
UserBadgeCache cache, @DrawableRes int iconResId, boolean forSavedNetworks,
Fragment fragment) {
super(accessPoint, context, cache, forSavedNetworks, iconResId, fragment);
}
@Override
protected int getWidgetLayoutResourceId() {
return R.layout.preference_widget_gear_optional_background;
}
@Override
public void refresh() {
super.refresh();
setShowDivider(mIsCaptivePortal);
if (mIsCaptivePortal) {
setSummary(R.string.wifi_tap_to_sign_in);
}
}
public void setOnGearClickListener(OnGearClickListener l) {
mOnGearClickListener = l;
notifyChanged();
}
@Override
public void onBindViewHolder(PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
final View gear = holder.findViewById(R.id.settings_button);
gear.setOnClickListener(this);
final View gearNoBg = holder.findViewById(R.id.settings_button_no_background);
gearNoBg.setVisibility(mIsCaptivePortal ? View.INVISIBLE : View.VISIBLE);
gear.setVisibility(mIsCaptivePortal ? View.VISIBLE : View.INVISIBLE);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.settings_button) {
if (mOnGearClickListener != null) {
mOnGearClickListener.onGearClick(this);
}
}
}
public void setCaptivePortal(boolean isCaptivePortal) {
if (mIsCaptivePortal != isCaptivePortal) {
mIsCaptivePortal = isCaptivePortal;
refresh();
}
}
public interface OnGearClickListener {
void onGearClick(ConnectedAccessPointPreference p);
}
}

View File

@@ -1,51 +0,0 @@
/*
* Copyright (C) 2015 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.wifi;
import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceViewHolder;
import com.android.settingslib.wifi.AccessPoint;
import com.android.settingslib.wifi.AccessPointPreference;
/**
* An AP preference for the currently connected AP.
*
* Migrating from Wi-Fi SettingsLib to to WifiTrackerLib, this object will be removed in the near
* future, please develop in {@link com.android.settingslib.wifi.LongPressWifiEntryPreference}.
*/
public class LongPressAccessPointPreference extends AccessPointPreference {
private final Fragment mFragment;
public LongPressAccessPointPreference(AccessPoint accessPoint, Context context,
UserBadgeCache cache, boolean forSavedNetworks, int iconResId, Fragment fragment) {
super(accessPoint, context, cache, iconResId, forSavedNetworks);
mFragment = fragment;
}
@Override
public void onBindViewHolder(final PreferenceViewHolder view) {
super.onBindViewHolder(view);
if (mFragment != null) {
view.itemView.setOnCreateContextMenuListener(mFragment);
view.itemView.setTag(this);
view.itemView.setLongClickable(true);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -35,7 +35,7 @@ import com.android.settings.security.SecuritySettings;
import com.android.settings.security.screenlock.ScreenLockSettings;
import com.android.settings.system.SystemDashboardFragment;
import com.android.settings.wallpaper.WallpaperSuggestionActivity;
import com.android.settings.wifi.WifiSettings2;
import com.android.settings.wifi.WifiSettings;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -58,8 +58,8 @@ public class CustomSiteMapRegistryTest {
}
@Test
public void shouldContainWifiSettings2Pairs() {
assertThat(CustomSiteMapRegistry.CUSTOM_SITE_MAP.get(WifiSettings2.class.getName()))
public void shouldContainWifiSettingsPairs() {
assertThat(CustomSiteMapRegistry.CUSTOM_SITE_MAP.get(WifiSettings.class.getName()))
.isEqualTo(NetworkDashboardFragment.class.getName());
}

View File

@@ -1,100 +0,0 @@
/*
* Copyright (C) 2019 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.wifi;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import android.app.settings.SettingsEnums;
import android.os.Bundle;
import com.android.settings.testutils.shadow.ShadowConnectivityManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.androidx.fragment.FragmentController;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = ShadowConnectivityManager.class)
public class ConfigureAccessPointFragmentTest {
private static final String KEY_SSID = "key_ssid";
private static final String KEY_SECURITY = "key_security";
private ConfigureAccessPointFragment mConfigureAccessPointFragment;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
Bundle bundle = new Bundle();
bundle.putString(KEY_SSID, "Test AP");
bundle.putInt(KEY_SECURITY, 1 /* WEP */);
mConfigureAccessPointFragment = spy(new ConfigureAccessPointFragment());
mConfigureAccessPointFragment.setArguments(bundle);
FragmentController.setupFragment(mConfigureAccessPointFragment);
}
@Test
public void getMetricsCategory_shouldReturnConfigureNetwork() {
assertThat(mConfigureAccessPointFragment.getMetricsCategory()).isEqualTo(
SettingsEnums.SETTINGS_WIFI_CONFIGURE_NETWORK);
}
@Test
public void getMode_shouldBeModeConnected() {
assertThat(mConfigureAccessPointFragment.getMode()).isEqualTo(
WifiConfigUiBase.MODE_CONNECT);
}
@Test
public void launchFragment_shouldShowSubmitButton() {
assertThat(mConfigureAccessPointFragment.getSubmitButton()).isNotNull();
}
@Test
public void launchFragment_shouldShowCancelButton() {
assertThat(mConfigureAccessPointFragment.getCancelButton()).isNotNull();
}
@Test
public void onClickSubmitButton_shouldHandleSubmitAction() {
mConfigureAccessPointFragment.getSubmitButton().performClick();
verify(mConfigureAccessPointFragment).handleSubmitAction();
}
@Test
public void dispatchSubmit_shouldHandleSubmitAction() {
mConfigureAccessPointFragment.dispatchSubmit();
verify(mConfigureAccessPointFragment).handleSubmitAction();
}
@Test
public void onClickCancelButton_shouldHandleCancelAction() {
mConfigureAccessPointFragment.getCancelButton().performClick();
verify(mConfigureAccessPointFragment).handleCancelAction();
}
}

View File

@@ -1,94 +0,0 @@
/*
* Copyright (C) 2017 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.wifi;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.view.View;
import com.android.settings.R;
import com.android.settingslib.wifi.AccessPoint;
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;
@RunWith(RobolectricTestRunner.class)
public class ConnectedAccessPointPreferenceTest {
@Mock
private AccessPoint mAccessPoint;
@Mock
private View mView;
@Mock
private ConnectedAccessPointPreference.OnGearClickListener mOnGearClickListener;
private Context mContext;
private ConnectedAccessPointPreference mConnectedAccessPointPreference;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mConnectedAccessPointPreference = new ConnectedAccessPointPreference(mAccessPoint, mContext,
null, 0 /* iconResId */, false /* forSavedNetworks */, null /* fragment */);
mConnectedAccessPointPreference.setOnGearClickListener(mOnGearClickListener);
}
@Test
public void testOnClick_gearClicked_listenerInvoked() {
when(mView.getId()).thenReturn(R.id.settings_button);
mConnectedAccessPointPreference.onClick(mView);
verify(mOnGearClickListener).onGearClick(mConnectedAccessPointPreference);
}
@Test
public void testOnClick_gearNotClicked_listenerNotInvoked() {
mConnectedAccessPointPreference.onClick(mView);
verify(mOnGearClickListener, never()).onGearClick(mConnectedAccessPointPreference);
}
@Test
public void testCaptivePortalStatus_isCaptivePortal_dividerDrawn() {
mConnectedAccessPointPreference.setCaptivePortal(true);
assertThat(mConnectedAccessPointPreference.shouldShowDivider()).isTrue();
}
@Test
public void testCaptivePortalStatus_isNotCaptivePortal_dividerNotDrawn() {
mConnectedAccessPointPreference.setCaptivePortal(false);
assertThat(mConnectedAccessPointPreference.shouldShowDivider()).isFalse();
}
@Test
public void testWidgetLayoutPreference() {
assertThat(mConnectedAccessPointPreference.getWidgetLayoutResource())
.isEqualTo(R.layout.preference_widget_gear_optional_background);
}
}

View File

@@ -1,367 +0,0 @@
/*
* Copyright (C) 2019 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.wifi;
import static com.android.settings.wifi.WifiConfigUiBase2.MODE_CONNECT;
import static com.android.settings.wifi.WifiConfigUiBase2.MODE_MODIFY;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.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.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.UserManager;
import android.provider.Settings;
import android.view.ContextMenu;
import android.view.View;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R;
import com.android.settings.datausage.DataUsagePreference;
import com.android.settings.testutils.shadow.ShadowDataUsageUtils;
import com.android.settings.testutils.shadow.ShadowFragment;
import com.android.settingslib.wifi.LongPressWifiEntryPreference;
import com.android.wifitrackerlib.WifiEntry;
import com.android.wifitrackerlib.WifiPickerTracker;
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.shadows.ShadowToast;
@RunWith(RobolectricTestRunner.class)
public class WifiSettings2Test {
private static final int NUM_NETWORKS = 4;
private static final String FAKE_URI_STRING = "fakeuri";
@Mock
private PowerManager mPowerManager;
@Mock
private WifiManager mWifiManager;
@Mock
private DataUsagePreference mDataUsagePreference;
private Context mContext;
private WifiSettings2 mWifiSettings2;
@Mock
private WifiPickerTracker mMockWifiPickerTracker;
@Mock
private PreferenceManager mPreferenceManager;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application);
mWifiSettings2 = spy(new WifiSettings2());
doReturn(mContext).when(mWifiSettings2).getContext();
doReturn(mPreferenceManager).when(mWifiSettings2).getPreferenceManager();
doReturn(mPowerManager).when(mContext).getSystemService(PowerManager.class);
doReturn(mWifiManager).when(mContext).getSystemService(WifiManager.class);
doReturn(mContext).when(mPreferenceManager).getContext();
mWifiSettings2.mAddWifiNetworkPreference = new AddWifiNetworkPreference(mContext);
mWifiSettings2.mSavedNetworksPreference = new Preference(mContext);
mWifiSettings2.mConfigureWifiSettingsPreference = new Preference(mContext);
mWifiSettings2.mWifiPickerTracker = mMockWifiPickerTracker;
mWifiSettings2.mWifiManager = mWifiManager;
}
@Test
public void addNetworkFragmentSendResult_onActivityResult_shouldHandleEvent() {
final WifiSettings2 wifiSettings2 = spy(new WifiSettings2());
final Intent intent = new Intent();
doNothing().when(wifiSettings2).handleAddNetworkRequest(anyInt(), any(Intent.class));
wifiSettings2.onActivityResult(WifiSettings2.ADD_NETWORK_REQUEST, Activity.RESULT_OK,
intent);
verify(wifiSettings2).handleAddNetworkRequest(anyInt(), any(Intent.class));
}
@Test
public void setAdditionalSettingsSummaries_hasSavedNetwork_preferenceVisible() {
when(mMockWifiPickerTracker.getNumSavedNetworks()).thenReturn(NUM_NETWORKS);
when(mMockWifiPickerTracker.getNumSavedSubscriptions()).thenReturn(0 /* count */);
mWifiSettings2.setAdditionalSettingsSummaries();
assertThat(mWifiSettings2.mSavedNetworksPreference.isVisible()).isTrue();
assertThat(mWifiSettings2.mSavedNetworksPreference.getSummary()).isEqualTo(
mContext.getResources().getQuantityString(
R.plurals.wifi_saved_access_points_summary,
NUM_NETWORKS, NUM_NETWORKS));
}
@Test
public void setAdditionalSettingsSummaries_hasSavedPasspointNetwork_preferenceVisible() {
when(mMockWifiPickerTracker.getNumSavedNetworks()).thenReturn(0 /* count */);
when(mMockWifiPickerTracker.getNumSavedSubscriptions()).thenReturn(NUM_NETWORKS);
mWifiSettings2.setAdditionalSettingsSummaries();
assertThat(mWifiSettings2.mSavedNetworksPreference.isVisible()).isTrue();
assertThat(mWifiSettings2.mSavedNetworksPreference.getSummary()).isEqualTo(
mContext.getResources().getQuantityString(
R.plurals.wifi_saved_passpoint_access_points_summary,
NUM_NETWORKS, NUM_NETWORKS));
}
@Test
public void setAdditionalSettingsSummaries_hasTwoKindsSavedNetwork_preferenceVisible() {
when(mMockWifiPickerTracker.getNumSavedNetworks()).thenReturn(NUM_NETWORKS);
when(mMockWifiPickerTracker.getNumSavedSubscriptions()).thenReturn(NUM_NETWORKS);
mWifiSettings2.setAdditionalSettingsSummaries();
assertThat(mWifiSettings2.mSavedNetworksPreference.isVisible()).isTrue();
assertThat(mWifiSettings2.mSavedNetworksPreference.getSummary()).isEqualTo(
mContext.getResources().getQuantityString(
R.plurals.wifi_saved_all_access_points_summary,
NUM_NETWORKS*2, NUM_NETWORKS*2));
}
@Test
public void setAdditionalSettingsSummaries_noSavedNetwork_preferenceInvisible() {
when(mMockWifiPickerTracker.getNumSavedNetworks()).thenReturn(0 /* count */);
when(mMockWifiPickerTracker.getNumSavedSubscriptions()).thenReturn(0 /* count */);
mWifiSettings2.setAdditionalSettingsSummaries();
assertThat(mWifiSettings2.mSavedNetworksPreference.isVisible()).isFalse();
}
@Test
public void setAdditionalSettingsSummaries_wifiWakeupEnabled_displayOn() {
final ContentResolver contentResolver = mContext.getContentResolver();
when(mWifiManager.isAutoWakeupEnabled()).thenReturn(true);
when(mWifiManager.isScanAlwaysAvailable()).thenReturn(true);
Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0);
when(mPowerManager.isPowerSaveMode()).thenReturn(false);
mWifiSettings2.setAdditionalSettingsSummaries();
assertThat(mWifiSettings2.mConfigureWifiSettingsPreference.getSummary()).isEqualTo(
mContext.getString(R.string.wifi_configure_settings_preference_summary_wakeup_on));
}
@Test
public void setAdditionalSettingsSummaries_wifiWakeupDisabled_displayOff() {
final ContentResolver contentResolver = mContext.getContentResolver();
when(mWifiManager.isAutoWakeupEnabled()).thenReturn(false);
mWifiSettings2.setAdditionalSettingsSummaries();
assertThat(mWifiSettings2.mConfigureWifiSettingsPreference.getSummary()).isEqualTo(
mContext.getString(R.string.wifi_configure_settings_preference_summary_wakeup_off));
}
@Test
public void checkAddWifiNetworkPrefernce_preferenceVisible() {
assertThat(mWifiSettings2.mAddWifiNetworkPreference.isVisible()).isTrue();
assertThat(mWifiSettings2.mAddWifiNetworkPreference.getTitle()).isEqualTo(
mContext.getString(R.string.wifi_add_network));
}
private void setUpForOnCreate() {
final FragmentActivity activity = mock(FragmentActivity.class);
when(mWifiSettings2.getActivity()).thenReturn(activity);
final Resources.Theme theme = mContext.getTheme();
when(activity.getTheme()).thenReturn(theme);
UserManager userManager = mock(UserManager.class);
when(activity.getSystemService(Context.USER_SERVICE))
.thenReturn(userManager);
when(mWifiSettings2.findPreference(WifiSettings2.PREF_KEY_DATA_USAGE))
.thenReturn(mDataUsagePreference);
}
@Test
@Config(shadows = {ShadowDataUsageUtils.class, ShadowFragment.class})
public void checkDataUsagePreference_perferenceInvisibleIfWifiNotSupported() {
setUpForOnCreate();
ShadowDataUsageUtils.IS_WIFI_SUPPORTED = false;
mWifiSettings2.onCreate(Bundle.EMPTY);
verify(mDataUsagePreference).setVisible(false);
}
@Test
@Config(shadows = {ShadowDataUsageUtils.class, ShadowFragment.class})
public void checkDataUsagePreference_perferenceVisibleIfWifiSupported() {
setUpForOnCreate();
ShadowDataUsageUtils.IS_WIFI_SUPPORTED = true;
mWifiSettings2.onCreate(Bundle.EMPTY);
verify(mDataUsagePreference).setVisible(true);
verify(mDataUsagePreference).setTemplate(any(), eq(0) /*subId*/, eq(null) /*service*/);
}
@Test
public void onCreateAdapter_hasStableIdsTrue() {
final PreferenceScreen preferenceScreen = mock(PreferenceScreen.class);
when(preferenceScreen.getContext()).thenReturn(mContext);
RecyclerView.Adapter adapter = mWifiSettings2.onCreateAdapter(preferenceScreen);
assertThat(adapter.hasStableIds()).isTrue();
}
@Test
public void onCreateContextMenu_shouldHaveForgetAndDisconnectMenuForConnectedWifiEntry() {
final FragmentActivity activity = mock(FragmentActivity.class);
when(activity.getApplicationContext()).thenReturn(mContext);
when(mWifiSettings2.getActivity()).thenReturn(activity);
final WifiEntry wifiEntry = mock(WifiEntry.class);
when(wifiEntry.canDisconnect()).thenReturn(true);
when(wifiEntry.canForget()).thenReturn(true);
when(wifiEntry.isSaved()).thenReturn(true);
when(wifiEntry.getConnectedState()).thenReturn(WifiEntry.CONNECTED_STATE_CONNECTED);
final LongPressWifiEntryPreference connectedWifiEntryPreference =
mWifiSettings2.createLongPressWifiEntryPreference(wifiEntry);
final View view = mock(View.class);
when(view.getTag()).thenReturn(connectedWifiEntryPreference);
final ContextMenu menu = mock(ContextMenu.class);
mWifiSettings2.onCreateContextMenu(menu, view, null /* info */);
verify(menu).add(anyInt(), eq(WifiSettings2.MENU_ID_FORGET), anyInt(), anyInt());
verify(menu).add(anyInt(), eq(WifiSettings2.MENU_ID_DISCONNECT), anyInt(), anyInt());
}
@Test
public void onWifiEntriesChanged_shouldChangeNextButtonState() {
mWifiSettings2.onWifiEntriesChanged();
verify(mWifiSettings2).changeNextButtonState(anyBoolean());
}
@Test
public void openSubscriptionHelpPage_shouldCallStartActivityForResult() {
doReturn(new Intent()).when(mWifiSettings2).getHelpIntent(mContext, FAKE_URI_STRING);
doNothing().when(mWifiSettings2).startActivityForResult(any(Intent.class), anyInt());
final WifiEntry mockWifiEntry = mock(WifiEntry.class);
when(mockWifiEntry.getHelpUriString()).thenReturn(FAKE_URI_STRING);
mWifiSettings2.openSubscriptionHelpPage(mockWifiEntry);
verify(mWifiSettings2, times(1)).startActivityForResult(any(), anyInt());
}
@Test
public void onNumSavedNetworksChanged_isFinishing_ShouldNotCrash() {
final FragmentActivity activity = mock(FragmentActivity.class);
when(activity.isFinishing()).thenReturn(true);
when(mWifiSettings2.getActivity()).thenReturn(activity);
when(mWifiSettings2.getContext()).thenReturn(null);
mWifiSettings2.onNumSavedNetworksChanged();
}
@Test
public void onNumSavedSubscriptionsChanged_isFinishing_ShouldNotCrash() {
final FragmentActivity activity = mock(FragmentActivity.class);
when(activity.isFinishing()).thenReturn(true);
when(mWifiSettings2.getActivity()).thenReturn(activity);
when(mWifiSettings2.getContext()).thenReturn(null);
mWifiSettings2.onNumSavedSubscriptionsChanged();
}
@Test
public void onSubmit_modeModifyNoConfig_toastErrorMessage() {
WifiDialog2 dialog = createWifiDialog2(MODE_MODIFY, null /* config */);
mWifiSettings2.onSubmit(dialog);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_failed_save_message));
}
@Test
public void onSubmit_modeModifyHasConfig_saveWifiManager() {
final WifiConfiguration config = mock(WifiConfiguration.class);
WifiDialog2 dialog = createWifiDialog2(MODE_MODIFY, config);
mWifiSettings2.onSubmit(dialog);
verify(mWifiManager).save(eq(config), any());
}
@Test
public void onSubmit_modeConnectNoConfig_connectWifiEntry() {
WifiDialog2 dialog = createWifiDialog2(MODE_CONNECT, null /* config */);
final WifiEntry wifiEntry = dialog.getWifiEntry();
mWifiSettings2.onAttach(mContext);
mWifiSettings2.onSubmit(dialog);
verify(mWifiSettings2).connect(wifiEntry, false /* editIfNoConfig */,
false /* fullScreenEdit*/);
}
@Test
public void onSubmit_modeConnectHasConfig_connectWifiManager() {
final WifiConfiguration config = mock(WifiConfiguration.class);
WifiDialog2 dialog = createWifiDialog2(MODE_CONNECT, config);
mWifiSettings2.onSubmit(dialog);
verify(mWifiManager).connect(eq(config), any(WifiManager.ActionListener.class));
}
private WifiDialog2 createWifiDialog2(int mode, WifiConfiguration config) {
final WifiEntry wifiEntry = mock(WifiEntry.class);
when(wifiEntry.canConnect()).thenReturn(true);
final WifiConfigController2 controller = mock(WifiConfigController2.class);
when(controller.getConfig()).thenReturn(config);
final WifiDialog2 wifiDialog2 = spy(WifiDialog2.createModal(mContext, null /* listener */,
wifiEntry, mode));
when(wifiDialog2.getController()).thenReturn(controller);
return wifiDialog2;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C) 2017 The Android Open Source Project
* Copyright (C) 2019 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.
@@ -15,17 +15,20 @@
*/
package com.android.settings.wifi;
import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
import static com.android.settings.wifi.WifiConfigUiBase2.MODE_CONNECT;
import static com.android.settings.wifi.WifiConfigUiBase2.MODE_MODIFY;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.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.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -33,91 +36,58 @@ import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.wifi.EAPConstants;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.hotspot2.PasspointConfiguration;
import android.net.wifi.hotspot2.pps.Credential;
import android.net.wifi.hotspot2.pps.HomeSp;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.UserManager;
import android.provider.Settings;
import android.util.FeatureFlagUtils;
import android.view.ContextMenu;
import android.view.View;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
import com.android.settings.datausage.DataUsagePreference;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowDataUsageUtils;
import com.android.settings.testutils.shadow.ShadowFragment;
import com.android.settings.widget.SwitchBar;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.wifi.AccessPoint;
import com.android.settingslib.wifi.WifiTracker;
import com.android.settingslib.wifi.WifiTrackerFactory;
import com.android.settingslib.wifi.LongPressWifiEntryPreference;
import com.android.wifitrackerlib.WifiEntry;
import com.android.wifitrackerlib.WifiPickerTracker;
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 org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.robolectric.shadows.ShadowToast;
@RunWith(RobolectricTestRunner.class)
public class WifiSettingsTest {
private static final int NUM_NETWORKS = 4;
private static final String FAKE_URI_STRING = "fakeuri";
@Mock
private WifiTracker mWifiTracker;
@Mock
private PowerManager mPowerManager;
@Mock
private DataUsagePreference mDataUsagePreference;
@Mock
private RecyclerView mRecyclerView;
@Mock
private RecyclerView.Adapter mRecyclerViewAdapter;
@Mock
private View mHeaderView;
@Mock
private WifiManager mWifiManager;
@Mock
private ConnectivityManager mConnectivityManager;
@Mock
private Intent mActivityIntent;
@Mock
private SwitchBar mSwitchBar;
@Mock
private WifiInfo mWifiInfo;
@Mock
private PackageManager mPackageManager;
private DataUsagePreference mDataUsagePreference;
private Context mContext;
private WifiSettings mWifiSettings;
private FakeFeatureFactory mFakeFeatureFactory;
private MetricsFeatureProvider mMetricsFeatureProvider;
@Mock
private WifiPickerTracker mMockWifiPickerTracker;
@Mock
private PreferenceManager mPreferenceManager;
@Before
public void setUp() {
@@ -126,75 +96,33 @@ public class WifiSettingsTest {
mWifiSettings = spy(new WifiSettings());
doReturn(mContext).when(mWifiSettings).getContext();
doReturn(mRecyclerViewAdapter).when(mRecyclerView).getAdapter();
doReturn(mRecyclerView).when(mWifiSettings).getListView();
doReturn(mPreferenceManager).when(mWifiSettings).getPreferenceManager();
doReturn(mPowerManager).when(mContext).getSystemService(PowerManager.class);
doReturn(mHeaderView).when(mWifiSettings).setPinnedHeaderView(anyInt());
doReturn(mWifiInfo).when(mWifiManager).getConnectionInfo();
doReturn(mWifiManager).when(mWifiTracker).getManager();
doReturn(mWifiManager).when(mContext).getSystemService(WifiManager.class);
doReturn(mContext).when(mPreferenceManager).getContext();
mWifiSettings.mAddWifiNetworkPreference = new AddWifiNetworkPreference(mContext);
mWifiSettings.mSavedNetworksPreference = new Preference(mContext);
mWifiSettings.mConfigureWifiSettingsPreference = new Preference(mContext);
mWifiSettings.mWifiTracker = mWifiTracker;
mWifiSettings.mWifiPickerTracker = mMockWifiPickerTracker;
mWifiSettings.mWifiManager = mWifiManager;
mWifiSettings.mConnectivityManager = mConnectivityManager;
mFakeFeatureFactory = FakeFeatureFactory.setupForTest();
mMetricsFeatureProvider = mFakeFeatureFactory.getMetricsFeatureProvider();
ReflectionHelpers.setField(mWifiSettings, "mMetricsFeatureProvider",
mMetricsFeatureProvider);
WifiTrackerFactory.setTestingWifiTracker(mWifiTracker);
}
@Test
public void addNetworkFragmentSendResult_onActivityResult_shouldHandleEvent() {
final WifiSettings wifiSettings = spy(new WifiSettings());
final WifiSettings WifiSettings = spy(new WifiSettings());
final Intent intent = new Intent();
doNothing().when(wifiSettings).handleAddNetworkRequest(anyInt(), any(Intent.class));
doNothing().when(WifiSettings).handleAddNetworkRequest(anyInt(), any(Intent.class));
wifiSettings.onActivityResult(WifiSettings.ADD_NETWORK_REQUEST, Activity.RESULT_OK, intent);
WifiSettings.onActivityResult(WifiSettings.ADD_NETWORK_REQUEST, Activity.RESULT_OK,
intent);
verify(wifiSettings).handleAddNetworkRequest(anyInt(), any(Intent.class));
}
private List<WifiConfiguration> createMockWifiConfigurations(int count) {
final List<WifiConfiguration> mockConfigs = new ArrayList<>();
for (int i = 0; i < count; i++) {
mockConfigs.add(new WifiConfiguration());
}
return mockConfigs;
}
private List<PasspointConfiguration> createMockPasspointConfigurations(int count) {
final List<PasspointConfiguration> mockConfigs = new ArrayList<>();
for (int i = 0; i < count; i++) {
final HomeSp sp = new HomeSp();
sp.setFqdn("fqdn");
final PasspointConfiguration config = new PasspointConfiguration();
config.setHomeSp(sp);
Credential.SimCredential simCredential = new Credential.SimCredential();
Credential credential = new Credential();
credential.setRealm("test.example.com");
simCredential.setImsi("12345*");
simCredential.setEapType(EAPConstants.EAP_SIM);
credential.setSimCredential(simCredential);
config.setCredential(credential);
mockConfigs.add(config);
}
return mockConfigs;
}
static NetworkCapabilities makeCaptivePortalNetworkCapabilities() {
final NetworkCapabilities capabilities = new NetworkCapabilities();
capabilities.clearAll();
capabilities.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
capabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
return capabilities;
verify(WifiSettings).handleAddNetworkRequest(anyInt(), any(Intent.class));
}
@Test
public void setAdditionalSettingsSummaries_hasSavedNetwork_preferenceVisible() {
when(mWifiManager.getConfiguredNetworks())
.thenReturn(createMockWifiConfigurations(NUM_NETWORKS));
when(mMockWifiPickerTracker.getNumSavedNetworks()).thenReturn(NUM_NETWORKS);
when(mMockWifiPickerTracker.getNumSavedSubscriptions()).thenReturn(0 /* count */);
mWifiSettings.setAdditionalSettingsSummaries();
@@ -207,8 +135,8 @@ public class WifiSettingsTest {
@Test
public void setAdditionalSettingsSummaries_hasSavedPasspointNetwork_preferenceVisible() {
when(mWifiManager.getPasspointConfigurations())
.thenReturn(createMockPasspointConfigurations(NUM_NETWORKS));
when(mMockWifiPickerTracker.getNumSavedNetworks()).thenReturn(0 /* count */);
when(mMockWifiPickerTracker.getNumSavedSubscriptions()).thenReturn(NUM_NETWORKS);
mWifiSettings.setAdditionalSettingsSummaries();
@@ -221,10 +149,8 @@ public class WifiSettingsTest {
@Test
public void setAdditionalSettingsSummaries_hasTwoKindsSavedNetwork_preferenceVisible() {
when(mWifiManager.getConfiguredNetworks())
.thenReturn(createMockWifiConfigurations(NUM_NETWORKS));
when(mWifiManager.getPasspointConfigurations())
.thenReturn(createMockPasspointConfigurations(NUM_NETWORKS));
when(mMockWifiPickerTracker.getNumSavedNetworks()).thenReturn(NUM_NETWORKS);
when(mMockWifiPickerTracker.getNumSavedSubscriptions()).thenReturn(NUM_NETWORKS);
mWifiSettings.setAdditionalSettingsSummaries();
@@ -237,8 +163,8 @@ public class WifiSettingsTest {
@Test
public void setAdditionalSettingsSummaries_noSavedNetwork_preferenceInvisible() {
when(mWifiManager.getConfiguredNetworks())
.thenReturn(createMockWifiConfigurations(0 /* count */));
when(mMockWifiPickerTracker.getNumSavedNetworks()).thenReturn(0 /* count */);
when(mMockWifiPickerTracker.getNumSavedSubscriptions()).thenReturn(0 /* count */);
mWifiSettings.setAdditionalSettingsSummaries();
@@ -278,29 +204,21 @@ public class WifiSettingsTest {
}
private void setUpForOnCreate() {
final SettingsActivity activity = mock(SettingsActivity.class);
when(activity.getSwitchBar()).thenReturn(mSwitchBar);
final FragmentActivity activity = mock(FragmentActivity.class);
when(mWifiSettings.getActivity()).thenReturn(activity);
final Resources.Theme theme = mContext.getTheme();
when(activity.getTheme()).thenReturn(theme);
when(activity.getIntent()).thenReturn(mActivityIntent);
UserManager userManager = mock(UserManager.class);
when(activity.getSystemService(Context.USER_SERVICE))
.thenReturn(userManager);
when(mWifiSettings.findPreference(WifiSettings.PREF_KEY_DATA_USAGE))
.thenReturn(mDataUsagePreference);
when(activity.getSystemService(Context.WIFI_SERVICE)).thenReturn(mWifiManager);
when(activity.getSystemService(ConnectivityManager.class)).thenReturn(mConnectivityManager);
when(activity.getPackageManager()).thenReturn(mPackageManager);
}
@Test
@Config(shadows = {ShadowDataUsageUtils.class, ShadowFragment.class})
public void checkDataUsagePreference_perferenceInvisibleIfWifiNotSupported() {
if (FeatureFlagUtils.isEnabled(mContext, FeatureFlagUtils.SETTINGS_WIFITRACKER2)) {
return;
}
setUpForOnCreate();
ShadowDataUsageUtils.IS_WIFI_SUPPORTED = false;
@@ -312,10 +230,6 @@ public class WifiSettingsTest {
@Test
@Config(shadows = {ShadowDataUsageUtils.class, ShadowFragment.class})
public void checkDataUsagePreference_perferenceVisibleIfWifiSupported() {
if (FeatureFlagUtils.isEnabled(mContext, FeatureFlagUtils.SETTINGS_WIFITRACKER2)) {
return;
}
setUpForOnCreate();
ShadowDataUsageUtils.IS_WIFI_SUPPORTED = true;
@@ -325,28 +239,6 @@ public class WifiSettingsTest {
verify(mDataUsagePreference).setTemplate(any(), eq(0) /*subId*/, eq(null) /*service*/);
}
@Test
public void onCreateContextMenu_shouldHaveForgetMenuForConnectedAccessPreference() {
final FragmentActivity mockActivity = mock(FragmentActivity.class);
when(mockActivity.getApplicationContext()).thenReturn(mContext);
when(mWifiSettings.getActivity()).thenReturn(mockActivity);
final AccessPoint accessPoint = mock(AccessPoint.class);
when(accessPoint.isConnectable()).thenReturn(false);
when(accessPoint.isSaved()).thenReturn(true);
when(accessPoint.isActive()).thenReturn(true);
final ConnectedAccessPointPreference connectedPreference =
mWifiSettings.createConnectedAccessPointPreference(accessPoint, mContext);
final View view = mock(View.class);
when(view.getTag()).thenReturn(connectedPreference);
final ContextMenu menu = mock(ContextMenu.class);
mWifiSettings.onCreateContextMenu(menu, view, null /* info */);
verify(menu).add(anyInt(), eq(WifiSettings.MENU_ID_FORGET), anyInt(), anyInt());
}
@Test
public void onCreateAdapter_hasStableIdsTrue() {
final PreferenceScreen preferenceScreen = mock(PreferenceScreen.class);
@@ -358,60 +250,118 @@ public class WifiSettingsTest {
}
@Test
@Config(shadows = {ShadowDataUsageUtils.class, ShadowFragment.class})
public void clickOnWifiNetworkWith_shouldStartCaptivePortalApp() {
if (FeatureFlagUtils.isEnabled(mContext, FeatureFlagUtils.SETTINGS_WIFITRACKER2)) {
return;
public void onCreateContextMenu_shouldHaveForgetAndDisconnectMenuForConnectedWifiEntry() {
final FragmentActivity activity = mock(FragmentActivity.class);
when(activity.getApplicationContext()).thenReturn(mContext);
when(mWifiSettings.getActivity()).thenReturn(activity);
final WifiEntry wifiEntry = mock(WifiEntry.class);
when(wifiEntry.canDisconnect()).thenReturn(true);
when(wifiEntry.canForget()).thenReturn(true);
when(wifiEntry.isSaved()).thenReturn(true);
when(wifiEntry.getConnectedState()).thenReturn(WifiEntry.CONNECTED_STATE_CONNECTED);
final LongPressWifiEntryPreference connectedWifiEntryPreference =
mWifiSettings.createLongPressWifiEntryPreference(wifiEntry);
final View view = mock(View.class);
when(view.getTag()).thenReturn(connectedWifiEntryPreference);
final ContextMenu menu = mock(ContextMenu.class);
mWifiSettings.onCreateContextMenu(menu, view, null /* info */);
verify(menu).add(anyInt(), eq(WifiSettings.MENU_ID_FORGET), anyInt(), anyInt());
verify(menu).add(anyInt(), eq(WifiSettings.MENU_ID_DISCONNECT), anyInt(), anyInt());
}
when(mWifiManager.getConfiguredNetworks()).thenReturn(createMockWifiConfigurations(
NUM_NETWORKS));
when(mWifiTracker.isConnected()).thenReturn(true);
@Test
public void onWifiEntriesChanged_shouldChangeNextButtonState() {
mWifiSettings.onWifiEntriesChanged();
final AccessPoint accessPointActive = mock(AccessPoint.class);
when(accessPointActive.isActive()).thenReturn(true);
when(accessPointActive.isSaved()).thenReturn(false);
when(accessPointActive.getConfig()).thenReturn(mock(WifiConfiguration.class));
verify(mWifiSettings).changeNextButtonState(anyBoolean());
}
final AccessPoint accessPointInactive = mock(AccessPoint.class);
when(accessPointInactive.isActive()).thenReturn(false);
when(accessPointInactive.isSaved()).thenReturn(false);
when(accessPointInactive.getConfig()).thenReturn(mock(WifiConfiguration.class));
@Test
public void openSubscriptionHelpPage_shouldCallStartActivityForResult() {
doReturn(new Intent()).when(mWifiSettings).getHelpIntent(mContext, FAKE_URI_STRING);
doNothing().when(mWifiSettings).startActivityForResult(any(Intent.class), anyInt());
final WifiEntry mockWifiEntry = mock(WifiEntry.class);
when(mockWifiEntry.getHelpUriString()).thenReturn(FAKE_URI_STRING);
when(mWifiTracker.getAccessPoints()).thenReturn(Arrays.asList(accessPointActive,
accessPointInactive));
when(mWifiManager.getWifiState()).thenReturn(WIFI_STATE_ENABLED);
when(mWifiManager.isWifiEnabled()).thenReturn(true);
mWifiSettings.openSubscriptionHelpPage(mockWifiEntry);
final Network network = mock(Network.class);
when(mWifiManager.getCurrentNetwork()).thenReturn(network);
verify(mWifiSettings, times(1)).startActivityForResult(any(), anyInt());
}
// Simulate activity creation cycle
setUpForOnCreate();
ShadowDataUsageUtils.IS_WIFI_SUPPORTED = true;
mWifiSettings.onCreate(Bundle.EMPTY);
mWifiSettings.onActivityCreated(null);
mWifiSettings.onViewCreated(new View(mContext), new Bundle());
mWifiSettings.onStart();
@Test
public void onNumSavedNetworksChanged_isFinishing_ShouldNotCrash() {
final FragmentActivity activity = mock(FragmentActivity.class);
when(activity.isFinishing()).thenReturn(true);
when(mWifiSettings.getActivity()).thenReturn(activity);
when(mWifiSettings.getContext()).thenReturn(null);
// Click on open network
final Preference openWifiPref = new LongPressAccessPointPreference(accessPointInactive,
mContext, null,
false /* forSavedNetworks */, R.drawable.ic_wifi_signal_0,
null);
mWifiSettings.onPreferenceTreeClick(openWifiPref);
mWifiSettings.onNumSavedNetworksChanged();
}
// Ensure connect() was called, and fake success.
ArgumentCaptor<WifiManager.ActionListener> wifiCallbackCaptor = ArgumentCaptor.forClass(
WifiManager.ActionListener.class);
verify(mWifiManager).connect(any(WifiConfiguration.class), wifiCallbackCaptor.capture());
wifiCallbackCaptor.getValue().onSuccess();
@Test
public void onNumSavedSubscriptionsChanged_isFinishing_ShouldNotCrash() {
final FragmentActivity activity = mock(FragmentActivity.class);
when(activity.isFinishing()).thenReturn(true);
when(mWifiSettings.getActivity()).thenReturn(activity);
when(mWifiSettings.getContext()).thenReturn(null);
// Simulate capability change
mWifiSettings.mCaptivePortalNetworkCallback.onCapabilitiesChanged(network,
makeCaptivePortalNetworkCapabilities());
mWifiSettings.onNumSavedSubscriptionsChanged();
}
// Ensure CP was called
verify(mConnectivityManager).startCaptivePortalApp(eq(network));
@Test
public void onSubmit_modeModifyNoConfig_toastErrorMessage() {
WifiDialog2 dialog = createWifiDialog2(MODE_MODIFY, null /* config */);
mWifiSettings.onSubmit(dialog);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_failed_save_message));
}
@Test
public void onSubmit_modeModifyHasConfig_saveWifiManager() {
final WifiConfiguration config = mock(WifiConfiguration.class);
WifiDialog2 dialog = createWifiDialog2(MODE_MODIFY, config);
mWifiSettings.onSubmit(dialog);
verify(mWifiManager).save(eq(config), any());
}
@Test
public void onSubmit_modeConnectNoConfig_connectWifiEntry() {
WifiDialog2 dialog = createWifiDialog2(MODE_CONNECT, null /* config */);
final WifiEntry wifiEntry = dialog.getWifiEntry();
mWifiSettings.onAttach(mContext);
mWifiSettings.onSubmit(dialog);
verify(mWifiSettings).connect(wifiEntry, false /* editIfNoConfig */,
false /* fullScreenEdit*/);
}
@Test
public void onSubmit_modeConnectHasConfig_connectWifiManager() {
final WifiConfiguration config = mock(WifiConfiguration.class);
WifiDialog2 dialog = createWifiDialog2(MODE_CONNECT, config);
mWifiSettings.onSubmit(dialog);
verify(mWifiManager).connect(eq(config), any(WifiManager.ActionListener.class));
}
private WifiDialog2 createWifiDialog2(int mode, WifiConfiguration config) {
final WifiEntry wifiEntry = mock(WifiEntry.class);
when(wifiEntry.canConnect()).thenReturn(true);
final WifiConfigController2 controller = mock(WifiConfigController2.class);
when(controller.getConfig()).thenReturn(config);
final WifiDialog2 wifiDialog2 = spy(WifiDialog2.createModal(mContext, null /* listener */,
wifiEntry, mode));
when(wifiDialog2.getController()).thenReturn(controller);
return wifiDialog2;
}
}

View File

@@ -15,31 +15,27 @@
*/
package com.android.settings.wifi;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.doesNotExist;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.Visibility.VISIBLE;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static com.google.common.truth.Truth.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.startsWith;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.test.uiautomator.UiDevice;
import androidx.fragment.app.Fragment;
import androidx.test.InstrumentationRegistry;
@@ -48,11 +44,8 @@ import androidx.test.runner.AndroidJUnit4;
import com.android.settings.Settings.WifiSettingsActivity;
import com.android.settingslib.utils.ThreadUtils;
import com.android.settingslib.wifi.AccessPoint;
import com.android.settingslib.wifi.TestAccessPointBuilder;
import com.android.settingslib.wifi.WifiTracker;
import com.android.settingslib.wifi.WifiTracker.WifiListener;
import com.android.settingslib.wifi.WifiTrackerFactory;
import com.android.wifitrackerlib.WifiEntry;
import com.android.wifitrackerlib.WifiPickerTracker;
import com.google.common.collect.Lists;
@@ -63,36 +56,28 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.nio.charset.StandardCharsets;
import java.util.List;
@RunWith(AndroidJUnit4.class)
public class WifiSettingsUiTest {
private static final String TEST_SSID = "\"Test Ssid\"";
private static final String TEST_UNQUOTED_SSID = "Test Ssid";
private static final String TEST_BSSID = "0a:08:5c:67:89:00";
private static final int TEST_RSSI = 123;
private static final int TEST_NETWORK_ID = 1;
private static final String TEST_SSID = "Test Ssid";
private static final String TEST_KEY = "Test Key";
// Keys used to lookup resources by name (see the resourceId/resourceString helper methods).
private static final String ID = "id";
private static final String STRING = "string";
private static final String WIFI_CONFIGURE_SETTINGS_PREFERENCE_TITLE =
"wifi_configure_settings_preference_title";
private static final String WIFI_SAVED_ACCESS_POINTS_LABEL = "wifi_saved_access_points_label";
private static final String WIFI_EMPTY_LIST_WIFI_OFF = "wifi_empty_list_wifi_off";
private static final String WIFI_DISPLAY_STATUS_CONNECTED = "wifi_display_status_connected";
private static final String WIFI_PASSWORD = "wifi_password";
private static final String WIFI_SHOW_PASSWORD = "wifi_show_password";
private static final String PASSWORD_LAYOUT = "password_layout";
private static final String PASSWORD = "password";
@Mock
private WifiTracker mWifiTracker;
private WifiPickerTracker mWifiTracker;
@Mock
private WifiManager mWifiManager;
private WifiPickerTracker.WifiPickerTrackerCallback mWifiListener;
private Context mContext;
private WifiListener mWifiListener;
private UiDevice mDevice;
@Rule
public ActivityTestRule<WifiSettingsActivity> mActivityRule =
@@ -102,8 +87,7 @@ public class WifiSettingsUiTest {
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = InstrumentationRegistry.getTargetContext();
WifiTrackerFactory.setTestingWifiTracker(mWifiTracker);
when(mWifiTracker.getManager()).thenReturn(mWifiManager);
mDevice = UiDevice.getInstance(getInstrumentation());
}
/**
@@ -121,33 +105,6 @@ public class WifiSettingsUiTest {
return mContext.getResources().getString(resourceId(STRING, name));
}
private void setupConnectedAccessPoint() {
WifiConfiguration config = new WifiConfiguration();
config.SSID = TEST_SSID;
config.BSSID = TEST_BSSID;
config.networkId = TEST_NETWORK_ID;
WifiInfo wifiInfo = new WifiInfo.Builder()
.setSsid(TEST_UNQUOTED_SSID.getBytes(StandardCharsets.UTF_8))
.setBssid(TEST_BSSID)
.setRssi(TEST_RSSI)
.setNetworkId(TEST_NETWORK_ID)
.build();
NetworkInfo networkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, null, null);
networkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null);
AccessPoint accessPoint = new AccessPoint(mContext, config);
accessPoint.update(config, wifiInfo, networkInfo);
assertThat(accessPoint.getSsidStr()).isEqualTo(TEST_UNQUOTED_SSID);
assertThat(accessPoint.getBssid()).isEqualTo(TEST_BSSID);
assertThat(accessPoint.getNetworkInfo()).isNotNull();
assertThat(accessPoint.isActive()).isTrue();
assertThat(accessPoint.getSettingsSummary()).isEqualTo(
resourceString(WIFI_DISPLAY_STATUS_CONNECTED));
when(mWifiTracker.getAccessPoints()).thenReturn(
Lists.asList(accessPoint, new AccessPoint[] {}));
}
/** Launch the activity via an Intent with a String extra. */
private void launchActivity(String extraName, String extraValue) {
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
@@ -156,11 +113,10 @@ public class WifiSettingsUiTest {
}
mActivityRule.launchActivity(intent);
verify(mWifiTracker).getManager();
List<Fragment> fragments =
mActivityRule.getActivity().getSupportFragmentManager().getFragments();
assertThat(fragments.size()).isEqualTo(1);
((WifiSettings) fragments.get(0)).mWifiPickerTracker = mWifiTracker;
mWifiListener = (WifiSettings) fragments.get(0);
assertThat(mWifiListener).isNotNull();
}
@@ -171,13 +127,7 @@ public class WifiSettingsUiTest {
}
private void setWifiState(int wifiState) {
when(mWifiManager.getWifiState()).thenReturn(wifiState);
when(mWifiManager.isWifiEnabled()).thenReturn(wifiState == WifiManager.WIFI_STATE_ENABLED);
}
private void callOnWifiStateChanged(int state) {
mActivityRule.getActivity().getMainThreadHandler()
.post(() -> mWifiListener.onWifiStateChanged(state));
when(mWifiTracker.getWifiState()).thenReturn(wifiState);
}
@Test
@@ -210,28 +160,32 @@ public class WifiSettingsUiTest {
when(mWifiTracker.getNumSavedNetworks()).thenReturn(1);
launchActivity();
mActivityRule.getActivity().getMainThreadHandler()
.post(() -> mWifiListener.onNumSavedNetworksChanged());
onView(allOf(withText(resourceId(STRING, WIFI_SAVED_ACCESS_POINTS_LABEL)),
withEffectiveVisibility(VISIBLE))).check(matches(isDisplayed()));
}
@Test
public void onDisableWifi_seeOffMessage() {
public void onWifiStateChanged_wifiDisabled_seeOffMessage() {
setWifiState(WifiManager.WIFI_STATE_DISABLED);
launchActivity();
callOnWifiStateChanged(WifiManager.WIFI_STATE_DISABLED);
mActivityRule.getActivity().getMainThreadHandler()
.post(() -> mWifiListener.onWifiStateChanged());
onView(withText(startsWith(resourceString(WIFI_EMPTY_LIST_WIFI_OFF)))).check(
matches(isDisplayed()));
}
@Test
public void onEnableWifi_shouldNotSeeOffMessage() {
public void onWifiStateChanged_wifiEnabled_shouldNotSeeOffMessage() {
setWifiState(WifiManager.WIFI_STATE_ENABLED);
launchActivity();
callOnWifiStateChanged(WifiManager.WIFI_STATE_ENABLED);
mActivityRule.getActivity().getMainThreadHandler()
.post(() -> mWifiListener.onWifiStateChanged());
onView(withText(startsWith(resourceString(WIFI_EMPTY_LIST_WIFI_OFF)))).check(
doesNotExist());
@@ -240,94 +194,55 @@ public class WifiSettingsUiTest {
@Test
public void onConnected_shouldSeeConnectedMessage() {
setWifiState(WifiManager.WIFI_STATE_ENABLED);
setupConnectedAccessPoint();
when(mWifiTracker.isConnected()).thenReturn(true);
final WifiEntry wifiEntry = mock(WifiEntry.class);
when(wifiEntry.getConnectedState()).thenReturn(WifiEntry.CONNECTED_STATE_CONNECTED);
when(wifiEntry.getSummary(false /* concise */))
.thenReturn(resourceString(WIFI_DISPLAY_STATUS_CONNECTED));
when(wifiEntry.getKey()).thenReturn(TEST_KEY);
when(mWifiTracker.getConnectedWifiEntry()).thenReturn(wifiEntry);
launchActivity();
ThreadUtils.postOnMainThread(() -> mWifiListener.onWifiEntriesChanged());
mDevice.waitForIdle();
onView(withText(resourceString(WIFI_DISPLAY_STATUS_CONNECTED))).check(
matches(isDisplayed()));
}
@Test
public void changingSecurityStateOnApShouldNotCauseMultipleListItems() {
public void changingSecurityStateOnAp_ShouldNotCauseMultipleListItems() {
setWifiState(WifiManager.WIFI_STATE_ENABLED);
TestAccessPointBuilder builder = new TestAccessPointBuilder(mContext)
.setSsid(TEST_SSID)
.setSecurity(AccessPoint.SECURITY_NONE)
.setRssi(TEST_RSSI);
AccessPoint open = builder.build();
builder.setSecurity(AccessPoint.SECURITY_EAP);
AccessPoint eap = builder.build();
final WifiEntry openWifiEntry = mock(WifiEntry.class);
when(openWifiEntry.getTitle()).thenReturn(TEST_SSID);
when(openWifiEntry.getSecurity()).thenReturn(WifiEntry.SECURITY_NONE);
builder.setSecurity(AccessPoint.SECURITY_WEP);
AccessPoint wep = builder.build();
final WifiEntry eapWifiEntry = mock(WifiEntry.class);
when(eapWifiEntry.getTitle()).thenReturn(TEST_SSID);
when(eapWifiEntry.getSecurity()).thenReturn(WifiEntry.SECURITY_EAP);
// Return a different security state each time getAccessPoints is invoked
when(mWifiTracker.getAccessPoints())
.thenReturn(Lists.newArrayList(open))
.thenReturn(Lists.newArrayList(eap))
.thenReturn(Lists.newArrayList(wep));
final WifiEntry wepWifiEntry = mock(WifiEntry.class);
when(wepWifiEntry.getTitle()).thenReturn(TEST_SSID);
when(wepWifiEntry.getSecurity()).thenReturn(WifiEntry.SECURITY_WEP);
// Return a different security state each time getWifiEntries is invoked
when(mWifiTracker.getWifiEntries())
.thenReturn(Lists.newArrayList(openWifiEntry))
.thenReturn(Lists.newArrayList(eapWifiEntry))
.thenReturn(Lists.newArrayList(wepWifiEntry));
launchActivity();
ThreadUtils.postOnMainThread(() -> mWifiListener.onWifiEntriesChanged());
mDevice.waitForIdle();
onView(withText(TEST_SSID)).check(matches(isDisplayed()));
ThreadUtils.postOnMainThread(() -> mWifiListener.onAccessPointsChanged());
ThreadUtils.postOnMainThread(() -> mWifiListener.onWifiEntriesChanged());
mDevice.waitForIdle();
onView(withText(TEST_SSID)).check(matches(isDisplayed()));
ThreadUtils.postOnMainThread(() -> mWifiListener.onAccessPointsChanged());
ThreadUtils.postOnMainThread(() -> mWifiListener.onWifiEntriesChanged());
mDevice.waitForIdle();
onView(withText(TEST_SSID)).check(matches(isDisplayed()));
}
@Test
public void wrongPasswordSavedNetwork() {
setWifiState(WifiManager.WIFI_STATE_ENABLED);
// Set up an AccessPoint that is disabled due to incorrect password.
WifiConfiguration config = new WifiConfiguration();
config.SSID = TEST_SSID;
config.BSSID = TEST_BSSID;
config.networkId = TEST_NETWORK_ID;
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
NetworkSelectionStatus selectionStatus = new NetworkSelectionStatus.Builder()
.setNetworkSelectionDisableReason(
NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD)
.setNetworkSelectionStatus(
NetworkSelectionStatus.NETWORK_SELECTION_TEMPORARY_DISABLED)
.build();
config.setNetworkSelectionStatus(selectionStatus);
WifiInfo wifiInfo = new WifiInfo.Builder()
.setSsid(TEST_UNQUOTED_SSID.getBytes(StandardCharsets.UTF_8))
.setBssid(TEST_BSSID)
.setRssi(TEST_RSSI)
.setNetworkId(TEST_NETWORK_ID)
.build();
AccessPoint accessPoint = new AccessPoint(mContext, config);
accessPoint.update(config, wifiInfo, null);
// Make sure we've set up our access point correctly.
assertThat(accessPoint.getSsidStr()).isEqualTo(TEST_UNQUOTED_SSID);
assertThat(accessPoint.getBssid()).isEqualTo(TEST_BSSID);
assertThat(accessPoint.isActive()).isFalse();
assertThat(accessPoint.getConfig()).isNotNull();
NetworkSelectionStatus networkStatus = accessPoint.getConfig().getNetworkSelectionStatus();
assertThat(networkStatus).isNotNull();
assertThat(networkStatus.getNetworkSelectionStatus())
.isEqualTo(NetworkSelectionStatus.NETWORK_SELECTION_TEMPORARY_DISABLED);
assertThat(networkStatus.getNetworkSelectionDisableReason()).isEqualTo(
NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD);
when(mWifiTracker.getAccessPoints()).thenReturn(Lists.newArrayList(accessPoint));
launchActivity(WifiSettings.EXTRA_START_CONNECT_SSID, accessPoint.getSsidStr());
// Make sure that the password dialog is visible.
onView(withText(resourceId(STRING, WIFI_PASSWORD))).check(matches(isDisplayed()));
onView(withText(resourceId(STRING, WIFI_SHOW_PASSWORD))).check(matches(isDisplayed()));
onView(withId(resourceId(ID, PASSWORD_LAYOUT))).check(matches(isDisplayed()));
onView(withId(resourceId(ID, PASSWORD))).check(matches(isDisplayed()));
}
}