diff options
author | Joe LaPenna <jlapenna@google.com> | 2017-04-17 18:53:36 +0000 |
---|---|---|
committer | android-build-merger <android-build-merger@google.com> | 2017-04-17 18:53:36 +0000 |
commit | 2218ce64d8b89e589208ea847251e8e12085a32a (patch) | |
tree | 492ae94a1f2ea77bf2551d9b221279876d05b526 | |
parent | 569d8792466fae368bf56b75b8506f1933ca2522 (diff) | |
parent | 724e94175de75a1293e91c8ebb317bd34d6499f1 (diff) | |
download | NetworkRecommendation-2218ce64d8b89e589208ea847251e8e12085a32a.tar.gz |
Update netrec components to latest spec.
am: 724e94175d
Change-Id: I2f7b46e2ee6233cf84d41f6cf5e4dea47aca3fa9
32 files changed, 288 insertions, 3370 deletions
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg index 744e98e..c0da365 100644 --- a/PREUPLOAD.cfg +++ b/PREUPLOAD.cfg @@ -1,6 +1,5 @@ [Hook Scripts] google_java_format = true -robotest_hook = make -C ../../.. -j32 RunNetworkRecommendationRoboTests [Builtin Hooks] commit_msg_bug_field = true diff --git a/robotests/Android.mk b/robotests/Android.mk deleted file mode 100644 index 3ed28c0..0000000 --- a/robotests/Android.mk +++ /dev/null @@ -1,43 +0,0 @@ -############################################# -# Add app-specific Robolectric test target. # -############################################# -LOCAL_PATH:= $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_SRC_FILES := $(call all-java-files-under, src) - -# Include the testing libraries (JUnit4 + Robolectric libs). -LOCAL_STATIC_JAVA_LIBRARIES := \ - platform-system-robolectric \ - truth-prebuilt - -LOCAL_JAVA_LIBRARIES := \ - junit \ - platform-robolectric-prebuilt \ - sdk_vcurrent - -# TODO: Remove the use of LOCAL_INSTRUMENTATION_FOR and use a different build flag. -LOCAL_INSTRUMENTATION_FOR := NetworkRecommendation -LOCAL_MODULE := NetworkRecommendationRoboTests - -LOCAL_MODULE_TAGS := optional - -include $(BUILD_STATIC_JAVA_LIBRARY) - -############################################################# -# Add Robolectric runner target to run the previous target. # -############################################################# -include $(CLEAR_VARS) - -LOCAL_MODULE := RunNetworkRecommendationRoboTests - -LOCAL_SDK_VERSION := current - -LOCAL_STATIC_JAVA_LIBRARIES := \ - NetworkRecommendationRoboTests - -LOCAL_TEST_PACKAGE := NetworkRecommendation - -LOCAL_ROBOTEST_FAILURE_FATAL := true - -include prebuilts/misc/common/robolectric/run_robotests.mk diff --git a/robotests/src/android/net/RecommendationRequest.java b/robotests/src/android/net/RecommendationRequest.java deleted file mode 100644 index 9f97c5a..0000000 --- a/robotests/src/android/net/RecommendationRequest.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (C) 2016 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 android.net; - - -import android.annotation.SystemApi; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiConfiguration; -import android.os.Parcel; -import android.os.Parcelable; - -import com.android.internal.annotations.VisibleForTesting; - -/** - * A request for a network recommendation. - * - * @see {@link NetworkScoreManager#requestRecommendation(RecommendationRequest)}. - * @hide - */ -@SystemApi -public final class RecommendationRequest implements Parcelable { - private final ScanResult[] mScanResults; - private final WifiConfiguration mDefaultConfig; - private WifiConfiguration mConnectedConfig; - private WifiConfiguration[] mConnectableConfigs; - private final int mLastSelectedNetworkId; - private final long mLastSelectedNetworkTimestamp; - - /** - * Builder class for constructing {@link RecommendationRequest} instances. - * @hide - */ - @SystemApi - public static final class Builder { - private ScanResult[] mScanResults; - private WifiConfiguration mDefaultConfig; - private WifiConfiguration mConnectedConfig; - private WifiConfiguration[] mConnectableConfigs; - private int mLastSelectedNetworkId = -1; - private long mLastSelectedTimestamp; - - public Builder setScanResults(ScanResult[] scanResults) { - mScanResults = scanResults; - return this; - } - - /** - * @param config the {@link WifiConfiguration} to return if no recommendation is available. - * @return this - */ - public Builder setDefaultWifiConfig(WifiConfiguration config) { - this.mDefaultConfig = config; - return this; - } - - /** - * @param config the {@link WifiConfiguration} of the connected network at the time the - * this request was made. - * @return this - */ - public Builder setConnectedWifiConfig(WifiConfiguration config) { - this.mConnectedConfig = config; - return this; - } - - /** - * @param connectableConfigs the set of saved {@link WifiConfiguration}s that can be - * connected to based on the current set of {@link ScanResult}s. - * @return this - */ - public Builder setConnectableConfigs(WifiConfiguration[] connectableConfigs) { - this.mConnectableConfigs = connectableConfigs; - return this; - } - - /** - * @param networkId The {@link WifiConfiguration#networkId} of the last user selected - * network. - * @param timestamp The {@link android.os.SystemClock#elapsedRealtime()} when the user - * selected {@code networkId}. - * @return this - */ - public Builder setLastSelectedNetwork(int networkId, long timestamp) { - this.mLastSelectedNetworkId = networkId; - this.mLastSelectedTimestamp = timestamp; - return this; - } - - /** - * @return a new {@link RecommendationRequest} instance - */ - public RecommendationRequest build() { - return new RecommendationRequest(mScanResults, mDefaultConfig, mConnectedConfig, - mConnectableConfigs, mLastSelectedNetworkId, mLastSelectedTimestamp); - } - } - - /** - * @return the array of {@link ScanResult}s the recommendation must be constrained to i.e. if a - * non-null wifi config recommendation is returned then it must be able to connect to - * one of the networks in the results list. - * - * If the array is {@code null} or empty then there is no constraint. - */ - public ScanResult[] getScanResults() { - return mScanResults; - } - - /** - * @return the {@link WifiConfiguration} to return if no recommendation is available. - */ - public WifiConfiguration getDefaultWifiConfig() { - return mDefaultConfig; - } - - /** - * @return the {@link WifiConfiguration} of the connected network at the time the this request - * was made. - */ - public WifiConfiguration getConnectedConfig() { - return mConnectedConfig; - } - - /** - * @return the set of saved {@link WifiConfiguration}s that can be connected to based on the - * current set of {@link ScanResult}s. - */ - public WifiConfiguration[] getConnectableConfigs() { - return mConnectableConfigs; - } - - /** - * @param connectedConfig the {@link WifiConfiguration} of the connected network at the time - * the this request was made. - */ - public void setConnectedConfig(WifiConfiguration connectedConfig) { - mConnectedConfig = connectedConfig; - } - - /** - * @param connectableConfigs the set of saved {@link WifiConfiguration}s that can be connected - * to based on the current set of {@link ScanResult}s. - */ - public void setConnectableConfigs(WifiConfiguration[] connectableConfigs) { - mConnectableConfigs = connectableConfigs; - } - - /** - * @return The {@link WifiConfiguration#networkId} of the last user selected network. - * {@code -1} if not set. - */ - public int getLastSelectedNetworkId() { - return mLastSelectedNetworkId; - } - - /** - * @return The {@link android.os.SystemClock#elapsedRealtime()} when the user selected - * {@link #getLastSelectedNetworkId()}. {@code 0} if not set. - */ - public long getLastSelectedNetworkTimestamp() { - return mLastSelectedNetworkTimestamp; - } - - @VisibleForTesting - RecommendationRequest(ScanResult[] scanResults, - WifiConfiguration defaultWifiConfig, - WifiConfiguration connectedWifiConfig, - WifiConfiguration[] connectableConfigs, - int lastSelectedNetworkId, - long lastSelectedNetworkTimestamp) { - mScanResults = scanResults; - mDefaultConfig = defaultWifiConfig; - mConnectedConfig = connectedWifiConfig; - mConnectableConfigs = connectableConfigs; - mLastSelectedNetworkId = lastSelectedNetworkId; - mLastSelectedNetworkTimestamp = lastSelectedNetworkTimestamp; - } - - protected RecommendationRequest(Parcel in) { - final int resultCount = in.readInt(); - if (resultCount > 0) { - mScanResults = new ScanResult[resultCount]; - final ClassLoader classLoader = ScanResult.class.getClassLoader(); - for (int i = 0; i < resultCount; i++) { - mScanResults[i] = in.readParcelable(classLoader); - } - } else { - mScanResults = null; - } - - mDefaultConfig = in.readParcelable(WifiConfiguration.class.getClassLoader()); - mConnectedConfig = in.readParcelable(WifiConfiguration.class.getClassLoader()); - - final int configCount = in.readInt(); - if (configCount > 0) { - mConnectableConfigs = new WifiConfiguration[configCount]; - final ClassLoader classLoader = WifiConfiguration.class.getClassLoader(); - for (int i = 0; i < configCount; i++) { - mConnectableConfigs[i] = in.readParcelable(classLoader); - } - } else { - mConnectableConfigs = null; - } - - mLastSelectedNetworkId = in.readInt(); - mLastSelectedNetworkTimestamp = in.readLong(); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - if (mScanResults != null) { - dest.writeInt(mScanResults.length); - for (int i = 0; i < mScanResults.length; i++) { - dest.writeParcelable(mScanResults[i], flags); - } - } else { - dest.writeInt(0); - } - - dest.writeParcelable(mDefaultConfig, flags); - dest.writeParcelable(mConnectedConfig, flags); - - if (mConnectableConfigs != null) { - dest.writeInt(mConnectableConfigs.length); - for (int i = 0; i < mConnectableConfigs.length; i++) { - dest.writeParcelable(mConnectableConfigs[i], flags); - } - } else { - dest.writeInt(0); - } - - dest.writeInt(mLastSelectedNetworkId); - dest.writeLong(mLastSelectedNetworkTimestamp); - } - - public static final Creator<RecommendationRequest> CREATOR = - new Creator<RecommendationRequest>() { - @Override - public RecommendationRequest createFromParcel(Parcel in) { - return new RecommendationRequest(in); - } - - @Override - public RecommendationRequest[] newArray(int size) { - return new RecommendationRequest[size]; - } - }; -} diff --git a/robotests/src/android/net/RecommendationResult.java b/robotests/src/android/net/RecommendationResult.java deleted file mode 100644 index 70cf09c..0000000 --- a/robotests/src/android/net/RecommendationResult.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2016 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 android.net; - -import android.annotation.NonNull; -import android.annotation.Nullable; -import android.annotation.SystemApi; -import android.net.wifi.WifiConfiguration; -import android.os.Parcel; -import android.os.Parcelable; - -import com.android.internal.annotations.VisibleForTesting; -import com.android.internal.util.Preconditions; - -/** - * The result of a network recommendation. - * - * @see {@link NetworkScoreManager#requestRecommendation(RecommendationRequest)}. - * @hide - */ -@SystemApi -public final class RecommendationResult implements Parcelable { - private final WifiConfiguration mWifiConfiguration; - - /** - * Create a {@link RecommendationResult} that indicates that no network connection should be - * attempted at this time. - * - * @return a {@link RecommendationResult} - */ - public static RecommendationResult createDoNotConnectRecommendation() { - return new RecommendationResult((WifiConfiguration) null); - } - - /** - * Create a {@link RecommendationResult} that indicates that a connection attempt should be - * made for the given Wi-Fi network. - * - * @param wifiConfiguration {@link WifiConfiguration} with at least SSID and BSSID set. - * @return a {@link RecommendationResult} - */ - public static RecommendationResult createConnectRecommendation( - @NonNull WifiConfiguration wifiConfiguration) { - Preconditions.checkNotNull(wifiConfiguration, "wifiConfiguration must not be null"); - Preconditions.checkNotNull(wifiConfiguration.SSID, "SSID must not be null"); - Preconditions.checkNotNull(wifiConfiguration.BSSID, "BSSID must not be null"); - return new RecommendationResult(wifiConfiguration); - } - - private RecommendationResult(@Nullable WifiConfiguration wifiConfiguration) { - mWifiConfiguration = wifiConfiguration; - } - - private RecommendationResult(Parcel in) { - mWifiConfiguration = in.readParcelable(WifiConfiguration.class.getClassLoader()); - } - - /** - * @return {@code true} if a network recommendation exists. {@code false} indicates that - * no connection should be attempted at this time. - */ - public boolean hasRecommendation() { - return mWifiConfiguration != null; - } - - /** - * @return The recommended {@link WifiConfiguration} to connect to. A {@code null} value - * is returned if {@link #hasRecommendation} returns {@code false}. - */ - @Nullable public WifiConfiguration getWifiConfiguration() { - return mWifiConfiguration; - } - - @Override - public String toString() { - return "RecommendationResult{" + - "mWifiConfiguration=" + mWifiConfiguration + - "}"; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel out, int flags) { - out.writeParcelable(mWifiConfiguration, flags); - } - - public static final Creator<RecommendationResult> CREATOR = - new Creator<RecommendationResult>() { - @Override - public RecommendationResult createFromParcel(Parcel in) { - return new RecommendationResult(in); - } - - @Override - public RecommendationResult[] newArray(int size) { - return new RecommendationResult[size]; - } - }; -} diff --git a/robotests/src/com/android/networkrecommendation/BroadcastIntentTestHelper.java b/robotests/src/com/android/networkrecommendation/BroadcastIntentTestHelper.java deleted file mode 100644 index fd674b8..0000000 --- a/robotests/src/com/android/networkrecommendation/BroadcastIntentTestHelper.java +++ /dev/null @@ -1,63 +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.networkrecommendation; - -import android.content.Context; -import android.content.Intent; -import android.net.NetworkInfo; -import android.net.wifi.WifiManager; -import android.os.PowerManager; - -/** Convenience methods for sending Intent broadcasts. */ -public class BroadcastIntentTestHelper { - - private final Context mContext; - - public BroadcastIntentTestHelper(Context context) { - mContext = context; - } - - public void sendPowerSaveModeChanged() { - Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); - mContext.sendBroadcast(intent); - } - - public void sendWifiStateChanged() { - Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION); - mContext.sendBroadcast(intent); - } - - public void sendNetworkStateChanged(NetworkInfo networkInfo) { - Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION); - intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, networkInfo); - mContext.sendBroadcast(intent); - } - - public void sendScanResultsAvailable() { - Intent intent = new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); - mContext.sendBroadcast(intent); - } - - public void sendWifiApStateChanged() { - Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); - mContext.sendBroadcast(intent); - } - - public void sendConfiguredNetworksChanged() { - Intent intent = new Intent(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); - mContext.sendBroadcast(intent); - } -} diff --git a/robotests/src/com/android/networkrecommendation/ExampleTest.java b/robotests/src/com/android/networkrecommendation/ExampleTest.java deleted file mode 100644 index 10e0ccb..0000000 --- a/robotests/src/com/android/networkrecommendation/ExampleTest.java +++ /dev/null @@ -1,67 +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.networkrecommendation; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertTrue; - -import static org.mockito.Mockito.verify; - -import android.app.job.JobScheduler; -import android.content.Context; -import android.content.Intent; -import android.net.RecommendationRequest; - -import com.android.networkrecommendation.shadows.RecommendationRequestShadow; - -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.annotation.Config; - -@RunWith(RobolectricTestRunner.class) -@Config(manifest="packages/services/NetworkRecommendation/AndroidManifest.xml", sdk=23, - shadows={RecommendationRequestShadow.class}) -public class ExampleTest { - @Mock private Context mMockContext; - @Mock private JobScheduler mJobScheduler; - @Mock private Intent mMockIntent; - @Mock private RecommendationRequest request; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void buildRecommendation() { - new RecommendationRequest.Builder().build(); - } - - @Test - public void build() { - new Example().buildRecommendationRequest(); - } - - @Test - public void reflect() { - new Example().reflectRecommendationRequest(); - } -} diff --git a/robotests/src/com/android/networkrecommendation/PlatformTestObjectFactory.java b/robotests/src/com/android/networkrecommendation/PlatformTestObjectFactory.java deleted file mode 100644 index fcc9355..0000000 --- a/robotests/src/com/android/networkrecommendation/PlatformTestObjectFactory.java +++ /dev/null @@ -1,55 +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.networkrecommendation; - -import android.net.NetworkKey; -import android.net.WifiKey; -import android.net.wifi.ScanResult; - -/** Creates platform objects which can be used for testing. */ -public class PlatformTestObjectFactory { - - private PlatformTestObjectFactory() {} // do not instantiate - - /** Use reflection to create a ScanResult. */ - public static ScanResult createScanResult( - String unquotedSsid, String bssid, int level, boolean open) { - try { - ScanResult scanResult = ScanResult.class.getConstructor().newInstance(); - scanResult.capabilities = open ? "[ESS]" : "[WEP]"; - scanResult.SSID = unquotedSsid; - scanResult.BSSID = bssid; - scanResult.level = level; - return scanResult; - } catch (Exception e) { - return null; - } - } - - /** Use reflection to create an open network ScanResult. */ - public static ScanResult createOpenNetworkScanResult(String ssid, String bssid) { - return createScanResult(ssid, bssid, 1, true); - } - - /** Use reflection to create a closed network ScanResult. */ - public static ScanResult createClosedNetworkScanResult(String unquotedSsid, String bssid) { - return createScanResult(unquotedSsid, bssid, 1, false); - } - /** Create a NetworkKey based on the given Wifi SSID/BSSID. */ - public static NetworkKey createNetworkKey(String ssid, String bssid) { - return new NetworkKey(new WifiKey(ssid, bssid)); - } -} diff --git a/robotests/src/com/android/networkrecommendation/TestData.java b/robotests/src/com/android/networkrecommendation/TestData.java deleted file mode 100644 index 803f3b6..0000000 --- a/robotests/src/com/android/networkrecommendation/TestData.java +++ /dev/null @@ -1,48 +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.networkrecommendation; - -import static com.android.networkrecommendation.PlatformTestObjectFactory.createNetworkKey; - -import android.net.NetworkKey; -import com.android.networkrecommendation.util.SsidUtil; - -/** - * Stock objects which can be re-used in multiple tests. - * - * <p>Objects here should be kept simple and generic; test-specific variants should be created - * inside tests as opposed to here. - */ -public class TestData { - - // SSID and BSSID values - public static final String UNQUOTED_SSID_1 = "ssid1"; - public static final String UNQUOTED_SSID_2 = "ssid2"; - public static final String UNQUOTED_SSID_3 = "ssid3"; - public static final String SSID_1 = SsidUtil.quoteSsid(UNQUOTED_SSID_1); - public static final String SSID_2 = SsidUtil.quoteSsid(UNQUOTED_SSID_2); - public static final String SSID_3 = SsidUtil.quoteSsid(UNQUOTED_SSID_3); - public static final String BSSID_1 = "01:01:01:01:01:01"; - public static final String BSSID_2 = "02:02:02:02:02:02"; - public static final String BSSID_3 = "03:03:03:03:03:03"; - - // Platform objects. - public static final NetworkKey NETWORK_KEY1 = createNetworkKey(SSID_1, BSSID_1); - public static final NetworkKey NETWORK_KEY2 = createNetworkKey(SSID_2, BSSID_2); - - // Can't instantiate. - private TestData() {} -} diff --git a/robotests/src/com/android/networkrecommendation/notify/WifiNotificationControllerTest.java b/robotests/src/com/android/networkrecommendation/notify/WifiNotificationControllerTest.java deleted file mode 100644 index 3f4828f..0000000 --- a/robotests/src/com/android/networkrecommendation/notify/WifiNotificationControllerTest.java +++ /dev/null @@ -1,469 +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.networkrecommendation.notify; - -import static com.android.networkrecommendation.PlatformTestObjectFactory.createOpenNetworkScanResult; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.anyInt; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.app.Notification; -import android.app.NotificationManager; -import android.content.ContentResolver; -import android.content.Intent; -import android.net.NetworkInfo; -import android.net.NetworkInfo.DetailedState; -import android.net.NetworkInfo.State; -import android.net.RecommendationRequest; -import android.net.RecommendationResult; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiManager; -import android.os.Handler; -import android.provider.Settings; -import com.android.networkrecommendation.BroadcastIntentTestHelper; -import com.android.networkrecommendation.SynchronousNetworkRecommendationProvider; -import com.android.networkrecommendation.TestData; -import com.android.networkrecommendation.util.RoboCompatUtil; -import com.google.common.collect.Lists; -import java.io.FileDescriptor; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -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.ShadowApplication; -import org.robolectric.shadows.ShadowLooper; -import org.robolectric.shadows.ShadowSettings; - -/** - * Instrumentation tests for {@link com.android.networkrecommendation.WifiNotificationController}. - */ -@RunWith(RobolectricTestRunner.class) -@Config(manifest = "packages/services/NetworkRecommendation/AndroidManifest.xml", sdk = 23) -public class WifiNotificationControllerTest { - - @Mock private WifiManager mWifiManager; - @Mock private NotificationManager mNotificationManager; - @Mock private WifiNotificationHelper mWifiNotificationHelper; - @Mock private SynchronousNetworkRecommendationProvider mNetworkRecommendationProvider; - @Mock private NetworkInfo mNetworkInfo; - @Mock private RoboCompatUtil mRoboCompatUtil; - @Captor private ArgumentCaptor<RecommendationRequest> mRecommendationRequestCaptor; - private ContentResolver mContentResolver; - private Handler mHandler; - private WifiNotificationController mWifiNotificationController; - private BroadcastIntentTestHelper mBroadcastIntentTestHelper; - - /** Initialize objects before each test run. */ - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - - // Needed for the NotificationEnabledSettingObserver. - mContentResolver = RuntimeEnvironment.application.getContentResolver(); - ShadowSettings.ShadowGlobal.putInt( - mContentResolver, Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1); - mHandler = new Handler(ShadowLooper.getMainLooper()); - - RoboCompatUtil.setInstanceForTesting(mRoboCompatUtil); - - mWifiNotificationController = - new WifiNotificationController( - RuntimeEnvironment.application, - mContentResolver, - mHandler, - mNetworkRecommendationProvider, - mWifiManager, - mNotificationManager, - mWifiNotificationHelper); - mWifiNotificationController.start(); - - when(mNetworkInfo.getState()).thenReturn(State.UNKNOWN); - mBroadcastIntentTestHelper = new BroadcastIntentTestHelper(RuntimeEnvironment.application); - } - - private void setOpenAccessPoints() { - List<ScanResult> scanResults = - Lists.newArrayList( - createOpenNetworkScanResult(TestData.UNQUOTED_SSID_1, TestData.BSSID_1), - createOpenNetworkScanResult(TestData.UNQUOTED_SSID_2, TestData.BSSID_2), - createOpenNetworkScanResult(TestData.UNQUOTED_SSID_3, TestData.BSSID_3)); - assertFalse(scanResults.isEmpty()); - when(mWifiManager.getScanResults()).thenReturn(scanResults); - } - - private static WifiConfiguration createFakeConfig() { - WifiConfiguration config = new WifiConfiguration(); - config.SSID = TestData.SSID_1; - config.BSSID = TestData.BSSID_1; - config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); - return config; - } - - /** - * When the NetworkRecommendationService associated with this WifiNotificationController is - * unbound, this WifiWakeupController should no longer function. - */ - @Test - public void wifiNotificationControllerStopped() { - mWifiNotificationController.stop(); - - assertFalse( - ShadowApplication.getInstance() - .hasReceiverForIntent( - new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))); - } - - /** Verifies that a notification is displayed (and retracted) given system events. */ - @Test - public void verifyNotificationDisplayedWhenNetworkRecommended() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createConnectRecommendation(createFakeConfig())); - - // The notification should not be displayed after only two scan results. - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - verify(mNotificationManager, never()) - .notify(anyString(), anyInt(), any(Notification.class)); - - verify(mWifiManager, times(2)).getScanResults(); - - // Changing to and from "SCANNING" state should not affect the counter. - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.SCANNING); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - - verify(mNotificationManager, never()) - .notify(anyString(), anyInt(), any(Notification.class)); - - // The third scan result notification will trigger the notification. - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiNotificationHelper).createMainNotification(any(WifiConfiguration.class)); - verify(mNotificationManager).notify(anyString(), anyInt(), any(Notification.class)); - verify(mNotificationManager, never()).cancel(anyString(), anyInt()); - } - - /** Verifies that a notification is not displayed for bad networks. */ - @Test - public void verifyNotificationNotDisplayedWhenNoNetworkRecommended() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - // Recommendation result with no WifiConfiguration returned. - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createDoNotConnectRecommendation()); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - verify(mNotificationManager, never()) - .notify(anyString(), anyInt(), any(Notification.class)); - } - - /** - * Verifies the notifications flow (Connect -> connecting -> connected) when user clicks on - * Connect button. - */ - @Test - public void verifyNotificationsFlowOnConnectToNetwork() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createConnectRecommendation(createFakeConfig())); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - verify(mWifiNotificationHelper).createMainNotification(any(WifiConfiguration.class)); - verify(mNotificationManager).notify(anyString(), anyInt(), any(Notification.class)); - - // Send connect intent, should attempt to connect to Wi-Fi - Intent intent = - new Intent(WifiNotificationController.ACTION_CONNECT_TO_RECOMMENDED_NETWORK); - ShadowApplication.getInstance().sendBroadcast(intent); - verify(mRoboCompatUtil).connectToWifi(any(WifiManager.class), any(WifiConfiguration.class)); - verify(mWifiNotificationHelper).createConnectingNotification(any(WifiConfiguration.class)); - - // Show connecting notification. - verify(mNotificationManager, times(2)) - .notify(anyString(), anyInt(), any(Notification.class)); - - // Verify show connected notification. - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.CONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - verify(mWifiNotificationHelper).createConnectedNotification(any(WifiConfiguration.class)); - verify(mNotificationManager, times(3)) - .notify(anyString(), anyInt(), any(Notification.class)); - - // Dismissed the connected notification. - ShadowLooper.runMainLooperToNextTask(); - verify(mNotificationManager).cancel(anyString(), anyInt()); - } - - /** Verifies the Failure to Connect notification after attempting to connect. */ - @Test - public void verifyNotificationsFlowOnFailedToConnectToNetwork() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createConnectRecommendation(createFakeConfig())); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - verify(mWifiNotificationHelper).createMainNotification(any(WifiConfiguration.class)); - verify(mNotificationManager).notify(anyString(), anyInt(), any(Notification.class)); - - // Send connect intent, should attempt to connect to Wi-Fi - Intent intent = - new Intent(WifiNotificationController.ACTION_CONNECT_TO_RECOMMENDED_NETWORK); - ShadowApplication.getInstance().sendBroadcast(intent); - verify(mRoboCompatUtil).connectToWifi(any(WifiManager.class), any(WifiConfiguration.class)); - verify(mWifiNotificationHelper).createConnectingNotification(any(WifiConfiguration.class)); - - // Show connecting notification. - verify(mNotificationManager, times(2)) - .notify(anyString(), anyInt(), any(Notification.class)); - - // Show failed to connect notification. - ShadowLooper.runMainLooperToNextTask(); - verify(mWifiNotificationHelper).createFailedToConnectNotification(); - - // Dismissed the cancel notification. - ShadowLooper.runMainLooperToNextTask(); - verify(mNotificationManager).cancel(anyString(), anyInt()); - } - - /** Verifies the flow where notification is dismissed. */ - @Test - public void verifyNotificationsFlowOnDismissMainNotification() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createConnectRecommendation(createFakeConfig())); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - // Show main notification - verify(mWifiNotificationHelper).createMainNotification(any(WifiConfiguration.class)); - verify(mNotificationManager).notify(anyString(), anyInt(), any(Notification.class)); - - // Send dismiss intent - Intent intent = new Intent(WifiNotificationController.ACTION_NOTIFICATION_DELETED); - ShadowApplication.getInstance().sendBroadcast(intent); - } - - /** Verifies the flow where "Settings" button on notification is clicked. */ - @Test - public void verifyNotificationsFlowOnClickSettingsFromMainNotification() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createConnectRecommendation(createFakeConfig())); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - // Show main notification - verify(mWifiNotificationHelper).createMainNotification(any(WifiConfiguration.class)); - verify(mNotificationManager).notify(anyString(), anyInt(), any(Notification.class)); - - // Send click settings intent - Intent intent = new Intent(WifiNotificationController.ACTION_PICK_WIFI_NETWORK); - ShadowApplication.getInstance().sendBroadcast(intent); - verify(mNotificationManager).cancel(anyString(), anyInt()); - } - - /** Verifies the flow when notification is reset on captive portal check. */ - @Test - public void verifyNotificationsFlowResetNotificationOnCaptivePortalCheck() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createConnectRecommendation(createFakeConfig())); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - // Show main notification - verify(mWifiNotificationHelper).createMainNotification(any(WifiConfiguration.class)); - verify(mNotificationManager).notify(anyString(), anyInt(), any(Notification.class)); - - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.CAPTIVE_PORTAL_CHECK); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - verify(mNotificationManager).cancel(anyString(), anyInt()); - } - - /** Verifies saved networks are skipped when getting network recommendations */ - @Test - public void verifyNotificationsFlowSkipSavedNetworks() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - - // First scan result and saved WifiConfiguration should be equal - when(mWifiManager.getScanResults()) - .thenReturn( - Lists.newArrayList( - createOpenNetworkScanResult( - TestData.UNQUOTED_SSID_1, TestData.BSSID_1))); - when(mWifiManager.getConfiguredNetworks()) - .thenReturn(Lists.newArrayList(createFakeConfig())); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mNetworkRecommendationProvider) - .requestRecommendation(mRecommendationRequestCaptor.capture()); - - assertEquals(0, mRecommendationRequestCaptor.getValue().getScanResults().length); - } - - /** - * Test that recommendations are not requested for new scan results when user has clicked on - * connect and a notification is showing. - */ - @Test - public void verifyNotificationsFlowSkipNewScanResultsWhenConnectionAttempted() - throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createConnectRecommendation(createFakeConfig())); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - verify(mNetworkRecommendationProvider, times(3)).requestRecommendation(any()); - - // Show main notification - verify(mWifiNotificationHelper).createMainNotification(any(WifiConfiguration.class)); - verify(mNotificationManager).notify(anyString(), anyInt(), any(Notification.class)); - - // Send connect intent, should attempt to connect to Wi-Fi - Intent intent = - new Intent(WifiNotificationController.ACTION_CONNECT_TO_RECOMMENDED_NETWORK); - ShadowApplication.getInstance().sendBroadcast(intent); - verify(mRoboCompatUtil).connectToWifi(any(WifiManager.class), any(WifiConfiguration.class)); - verify(mWifiNotificationHelper).createConnectingNotification(any(WifiConfiguration.class)); - verify(mNotificationManager, times(2)) - .notify(anyString(), anyInt(), any(Notification.class)); - - // No new recommendation requests made - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - verify(mNetworkRecommendationProvider, times(3)).requestRecommendation(any()); - } - - /** Test that the main notification updates when new scan results are available. */ - @Test - public void verifyNotificationsFlowUpdateMainNotificationOnNewScanResults() throws Exception { - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - when(mNetworkInfo.getDetailedState()).thenReturn(DetailedState.DISCONNECTED); - mBroadcastIntentTestHelper.sendNetworkStateChanged(mNetworkInfo); - setOpenAccessPoints(); - - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createConnectRecommendation(createFakeConfig())); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - verify(mNetworkRecommendationProvider, times(3)).requestRecommendation(any()); - - // Show main notification - verify(mWifiNotificationHelper).createMainNotification(any(WifiConfiguration.class)); - verify(mNotificationManager).notify(anyString(), anyInt(), any(Notification.class)); - - // Update main notification. - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - verify(mNetworkRecommendationProvider, times(4)).requestRecommendation(any()); - verify(mNotificationManager, times(2)) - .notify(anyString(), anyInt(), any(Notification.class)); - } - - /** Test dump() does not crash. */ - @Test - public void testDump() { - StringWriter stringWriter = new StringWriter(); - mWifiNotificationController.dump( - new FileDescriptor(), new PrintWriter(stringWriter), new String[0]); - } -} diff --git a/robotests/src/com/android/networkrecommendation/notify/WifiNotificationHelperTest.java b/robotests/src/com/android/networkrecommendation/notify/WifiNotificationHelperTest.java deleted file mode 100644 index 4a37e6c..0000000 --- a/robotests/src/com/android/networkrecommendation/notify/WifiNotificationHelperTest.java +++ /dev/null @@ -1,97 +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.networkrecommendation.notify; - -import static org.junit.Assert.assertNotNull; - -import android.app.Notification; -import android.content.Context; -import android.net.wifi.WifiConfiguration; -import com.android.networkrecommendation.SynchronousNetworkRecommendationProvider; -import com.android.networkrecommendation.TestData; -import com.android.networkrecommendation.shadows.BitmapGetPixelsShadow; -import com.android.networkrecommendation.shadows.ShadowNotificationChannelUtil; -import com.android.networkrecommendation.config.Flag; -import com.android.networkrecommendation.util.RoboCompatUtil; -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; - -/** Unit tests for {@link WifiNotificationHelper} */ -@RunWith(RobolectricTestRunner.class) -@Config(manifest = "packages/services/NetworkRecommendation/AndroidManifest.xml", sdk = 23, -shadows={BitmapGetPixelsShadow.class, ShadowNotificationChannelUtil.class}) -public class WifiNotificationHelperTest { - - private Context mContext; - - @Mock - private SynchronousNetworkRecommendationProvider mSynchronousNetworkRecommendationProvider; - - @Mock private RoboCompatUtil mRoboCompatUtil; - - private WifiNotificationHelper mWifiNotificationHelper; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - Flag.initForTest(); - RoboCompatUtil.setInstanceForTesting(mRoboCompatUtil); - mContext = RuntimeEnvironment.application; - - mWifiNotificationHelper = new WifiNotificationHelper(mContext); - } - - private static WifiConfiguration createFakeConfig() { - WifiConfiguration config = new WifiConfiguration(); - config.SSID = TestData.SSID_1; - config.BSSID = TestData.BSSID_1; - config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); - return config; - } - - private static void assertValidNotification(Notification notification) { - assertNotNull(notification); - assertNotNull(notification.getSmallIcon()); - } - - @Test - public void createMainNotification() { - assertValidNotification(mWifiNotificationHelper.createMainNotification(createFakeConfig())); - } - - @Test - public void createConnectingNotification() { - assertValidNotification( - mWifiNotificationHelper.createConnectingNotification(createFakeConfig())); - } - - @Test - public void createConnectedNotification() { - assertValidNotification( - mWifiNotificationHelper.createConnectedNotification(createFakeConfig())); - } - - @Test - public void createFailedToConnectNotification() { - assertValidNotification(mWifiNotificationHelper.createFailedToConnectNotification()); - } -} diff --git a/robotests/src/com/android/networkrecommendation/shadows/BitmapGetPixelsShadow.java b/robotests/src/com/android/networkrecommendation/shadows/BitmapGetPixelsShadow.java deleted file mode 100644 index c1a8c23..0000000 --- a/robotests/src/com/android/networkrecommendation/shadows/BitmapGetPixelsShadow.java +++ /dev/null @@ -1,29 +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.networkrecommendation.shadows; - -import android.annotation.ColorInt; -import android.graphics.Bitmap; - -import org.robolectric.annotation.Implements; -import org.robolectric.shadows.ShadowBitmap; - -@Implements(Bitmap.class) -public class BitmapGetPixelsShadow extends ShadowBitmap { - public void getPixels(@ColorInt int[] pixels, int offset, int stride, - int x, int y, int width, int height) { - } -} diff --git a/robotests/src/com/android/networkrecommendation/shadows/RecommendationRequestShadow.java b/robotests/src/com/android/networkrecommendation/shadows/RecommendationRequestShadow.java deleted file mode 100644 index efdad3e..0000000 --- a/robotests/src/com/android/networkrecommendation/shadows/RecommendationRequestShadow.java +++ /dev/null @@ -1,24 +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.networkrecommendation.shadows; - -import android.net.RecommendationRequest; - -import org.robolectric.annotation.Implements; - -@Implements(RecommendationRequest.class) -public class RecommendationRequestShadow { -} diff --git a/robotests/src/com/android/networkrecommendation/shadows/ShadowNotificationChannelUtil.java b/robotests/src/com/android/networkrecommendation/shadows/ShadowNotificationChannelUtil.java deleted file mode 100644 index c8e6d26..0000000 --- a/robotests/src/com/android/networkrecommendation/shadows/ShadowNotificationChannelUtil.java +++ /dev/null @@ -1,42 +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.networkrecommendation.shadows; - -import android.app.Notification.Builder; -import android.app.NotificationManager; -import android.content.Context; -import com.android.networkrecommendation.util.NotificationChannelUtil; -import org.robolectric.annotation.Implementation; -import org.robolectric.annotation.Implements; - -/** - * A temporary shadow which is only useful until NotificationChannel and NotificationChannelGroup - * classes is available to Robolectric tests. TODO(b/35959851): remove this class. - */ -@Implements(NotificationChannelUtil.class) -public class ShadowNotificationChannelUtil { - - @Implementation - public static void configureNotificationChannels( - NotificationManager notificationManager, Context context) { - // Do nothing - } - - @Implementation - public static Builder setChannel(Builder notificationBuilder, String channelId) { - return notificationBuilder; - } -} diff --git a/robotests/src/com/android/networkrecommendation/util/ScanResultUtilTest.java b/robotests/src/com/android/networkrecommendation/util/ScanResultUtilTest.java deleted file mode 100644 index a55a598..0000000 --- a/robotests/src/com/android/networkrecommendation/util/ScanResultUtilTest.java +++ /dev/null @@ -1,101 +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.networkrecommendation.util; - -import static com.android.networkrecommendation.PlatformTestObjectFactory.createOpenNetworkScanResult; -import static com.android.networkrecommendation.util.SsidUtil.quoteSsid; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import android.net.NetworkKey; -import android.net.WifiKey; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiConfiguration.KeyMgmt; -import com.android.networkrecommendation.config.Flag; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; - -/** Unit tests for {@link ScanResultUtil}. */ -@RunWith(RobolectricTestRunner.class) -@Config(manifest = "packages/services/NetworkRecommendation/AndroidManifest.xml", sdk = 23) -public class ScanResultUtilTest { - - @Before - public void setUp() { - Flag.initForTest(); - } - - @Test - public void testCreateNetworkKey() { - ScanResult scanResult = createOpenNetworkScanResult("testSSID", "00:00:00:00:00:00"); - NetworkKey networkKey = ScanResultUtil.createNetworkKey(scanResult); - - assertEquals(quoteSsid(scanResult.SSID), networkKey.wifiKey.ssid); - assertEquals(scanResult.BSSID, networkKey.wifiKey.bssid); - } - - @Test - public void testCreateWifiKey_validScanResult() { - ScanResult scanResult = createOpenNetworkScanResult("testSSID", "00:00:00:00:00:00"); - WifiKey wifiKey = ScanResultUtil.createWifiKey(scanResult); - - assertEquals(quoteSsid(scanResult.SSID), wifiKey.ssid); - assertEquals(scanResult.BSSID, wifiKey.bssid); - } - - @Test - public void testCreateWifiKey_invalidScanResultReturnsNull() { - ScanResult scanResult1 = createOpenNetworkScanResult(null, "00:00:00:00:00:00"); - - assertNull(ScanResultUtil.createWifiKey(scanResult1)); - - ScanResult scanResult2 = createOpenNetworkScanResult("testSSID", null); - - assertNull(ScanResultUtil.createWifiKey(scanResult2)); - - ScanResult scanResult3 = createOpenNetworkScanResult("testSSID", "invalidBSSID"); - - assertNull(ScanResultUtil.createWifiKey(scanResult3)); - } - - @Test - public void testDoesScanResultMatchWithNetwork_matching() { - WifiConfiguration config = new WifiConfiguration(); - config.SSID = quoteSsid("testSSID"); - config.BSSID = "00:00:00:00:00:00"; - config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); - ScanResult scanResult = createOpenNetworkScanResult(config.SSID, config.BSSID); - - assertTrue(ScanResultUtil.doesScanResultMatchWithNetwork(scanResult, config)); - } - - @Test - public void testDoesScanResultMatchWithNetwork_onlyOneOpenNetworkDoesNotMatch() { - WifiConfiguration config = new WifiConfiguration(); - config.SSID = quoteSsid("testSSID"); - config.BSSID = "00:00:00:00:00:00"; - config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); - ScanResult scanResult = createOpenNetworkScanResult(config.SSID, config.BSSID); - - assertFalse(ScanResultUtil.doesScanResultMatchWithNetwork(scanResult, config)); - } -} diff --git a/robotests/src/com/android/networkrecommendation/util/SsidUtilTest.java b/robotests/src/com/android/networkrecommendation/util/SsidUtilTest.java deleted file mode 100644 index 1c1bd07..0000000 --- a/robotests/src/com/android/networkrecommendation/util/SsidUtilTest.java +++ /dev/null @@ -1,82 +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.networkrecommendation.util; - -import static com.android.networkrecommendation.TestData.BSSID_1; -import static com.android.networkrecommendation.TestData.SSID_1; -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.android.networkrecommendation.config.Flag; -import com.android.networkrecommendation.config.G; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; - -/** Tests for {@link SsidUtil}. */ -@RunWith(RobolectricTestRunner.class) -@Config(manifest = "packages/services/NetworkRecommendation/AndroidManifest.xml", sdk = 23) -public class SsidUtilTest { - - @Rule public ExpectedException thrownException = ExpectedException.none(); - - private static final String QUOTED_SSID = "\"foo\""; - private static final String UNQUOTED_SSID = "foo"; - - @Before - public void setUp() { - Flag.initForTest(); - } - - @Test - public void testQuote() { - assertEquals(QUOTED_SSID, SsidUtil.quoteSsid(UNQUOTED_SSID)); - assertEquals(QUOTED_SSID, SsidUtil.quoteSsid(QUOTED_SSID)); - assertEquals(QUOTED_SSID, SsidUtil.quoteSsid(SsidUtil.quoteSsid(UNQUOTED_SSID))); - assertNull(SsidUtil.quoteSsid(null)); - } - - @Test - public void testVerify() { - assertFalse(SsidUtil.isValidQuotedSsid(UNQUOTED_SSID)); - assertTrue(SsidUtil.isValidQuotedSsid(QUOTED_SSID)); - } - - @Test - public void testCheck() { - thrownException.expect(IllegalArgumentException.class); - SsidUtil.checkIsValidQuotedSsid(UNQUOTED_SSID); - } - - @Test - public void testRedactedId() { - G.Netrec.enableSensitiveLogging.override(false); - assertThat(SsidUtil.getRedactedId(SSID_1, BSSID_1)).doesNotContain(SSID_1); - } - - @Test - public void testRedactedId_sensitiveEnabled() { - G.Netrec.enableSensitiveLogging.override(true); - assertEquals("\"ssid1\"/01:01:01:01:01:01", SsidUtil.getRedactedId(SSID_1, BSSID_1)); - } -} diff --git a/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupControllerTest.java b/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupControllerTest.java deleted file mode 100644 index 01e7db1..0000000 --- a/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupControllerTest.java +++ /dev/null @@ -1,606 +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.networkrecommendation.wakeup; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyList; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -import android.app.NotificationManager; -import android.content.ContentResolver; -import android.content.Intent; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiConfiguration.Status; -import android.net.wifi.WifiManager; -import android.os.Handler; -import android.os.PowerManager; -import android.provider.Settings; -import com.android.networkrecommendation.BroadcastIntentTestHelper; -import com.android.networkrecommendation.config.Flag; -import com.android.networkrecommendation.config.PreferenceFile; -import com.android.networkrecommendation.config.Preferences; -import com.android.networkrecommendation.config.WideAreaNetworks; -import com.android.networkrecommendation.scoring.util.HashUtil; -import com.android.networkrecommendation.util.RoboCompatUtil; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import java.io.FileDescriptor; -import java.io.PrintWriter; -import java.io.StringWriter; -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.ShadowApplication; -import org.robolectric.shadows.ShadowLooper; - -/** Unit tests for {@link WifiWakeupController}. */ -@RunWith(RobolectricTestRunner.class) -@Config(manifest = "packages/services/NetworkRecommendation/AndroidManifest.xml", sdk = 23) -public class WifiWakeupControllerTest { - private static final ScanResult OPEN_SCAN_RESULT = buildScanResult("ssid"); - private static final ScanResult SAVED_SCAN_RESULT = buildScanResult("ssid1"); - private static final ScanResult SAVED_SCAN_RESULT2 = buildScanResult("ssid2"); - private static final ScanResult SAVED_SCAN_RESULT_EXTERNAL = buildScanResult("ssid3"); - private static final ScanResult SAVED_SCAN_RESULT_WIDE_AREA = buildScanResult("xfinitywifi"); - - private static ScanResult buildScanResult(String ssid) { - try { - ScanResult scanResult = ScanResult.class.getConstructor().newInstance(); - scanResult.SSID = ssid; - return scanResult; - } catch (Exception e) { - return null; - } - } - - private ContentResolver mContentResolver; - @Mock private NotificationManager mNotificationManager; - @Mock private WifiWakeupNetworkSelector mWifiWakeupNetworkSelector; - @Mock private WifiWakeupHelper mWifiWakeupHelper; - @Mock private WifiManager mWifiManager; - @Mock private RoboCompatUtil mRoboCompatUtil; - @Mock private PowerManager mPowerManager; - - private WifiConfiguration mSavedWifiConfiguration; - private WifiConfiguration mSavedWifiConfiguration2; - private WifiConfiguration mSavedWifiConfigurationExternal; - private WifiConfiguration mSavedWifiConfigurationWideArea; - - private WifiWakeupController mWifiWakeupController; - private BroadcastIntentTestHelper mBroadcastIntentTestHelper; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - Flag.initForTest(); - RoboCompatUtil.setInstanceForTesting(mRoboCompatUtil); - PreferenceFile.init(RuntimeEnvironment.application); - - mSavedWifiConfiguration = new WifiConfiguration(); - mSavedWifiConfiguration.SSID = "\"" + SAVED_SCAN_RESULT.SSID + "\""; - mSavedWifiConfiguration.status = WifiConfiguration.Status.CURRENT; - mSavedWifiConfiguration2 = new WifiConfiguration(); - mSavedWifiConfiguration2.SSID = "\"" + SAVED_SCAN_RESULT2.SSID + "\""; - mSavedWifiConfiguration2.status = WifiConfiguration.Status.ENABLED; - mSavedWifiConfigurationExternal = new WifiConfiguration(); - mSavedWifiConfigurationExternal.SSID = "\"" + SAVED_SCAN_RESULT_EXTERNAL.SSID + "\""; - // TODO(netrec): why is this needed when this field is accessible when compiling the main apk? - // is robo_experimental behind backend_experimental? - when(mRoboCompatUtil.useExternalScores(mSavedWifiConfigurationExternal)).thenReturn(true); - mSavedWifiConfigurationExternal.status = WifiConfiguration.Status.ENABLED; - mSavedWifiConfigurationWideArea = new WifiConfiguration(); - mSavedWifiConfigurationWideArea.SSID = "\"" + SAVED_SCAN_RESULT_WIDE_AREA.SSID + "\""; - mSavedWifiConfigurationWideArea.status = WifiConfiguration.Status.ENABLED; - assertTrue(WideAreaNetworks.contains(SAVED_SCAN_RESULT_WIDE_AREA.SSID)); - - mContentResolver = RuntimeEnvironment.application.getContentResolver(); - Settings.Global.putInt(mContentResolver, Settings.Global.WIFI_WAKEUP_ENABLED, 1); - Settings.Global.putInt(mContentResolver, Settings.Global.AIRPLANE_MODE_ON, 0); - when(mWifiManager.getWifiApState()).thenReturn(WifiManager.WIFI_AP_STATE_DISABLED); - ShadowLooper.resetThreadLoopers(); - Preferences.savedSsidsOnDisable.remove(); - - mWifiWakeupController = - new WifiWakeupController( - RuntimeEnvironment.application, - mContentResolver, - new Handler(ShadowLooper.getMainLooper()), - mWifiManager, - mPowerManager, - mWifiWakeupNetworkSelector, - mWifiWakeupHelper); - mWifiWakeupController.start(); - mBroadcastIntentTestHelper = new BroadcastIntentTestHelper(RuntimeEnvironment.application); - } - - /** - * When the NetworkRecommendationService associated with this WifiWakeupController is unbound, - * this WifiWakeupController should no longer function. - */ - @Test - public void wifiWakeupControllerStopped() { - mWifiWakeupController.stop(); - - assertFalse( - ShadowApplication.getInstance() - .hasReceiverForIntent( - new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))); - } - - /** - * When {@link Settings.Global.WIFI_WAKEUP_ENABLED} is disabled, scan results should not be - * processed. - */ - @Test - public void wifiWakeupControllerStarted_settingDisabled() { - Settings.Global.putInt(mContentResolver, Settings.Global.WIFI_WAKEUP_ENABLED, 0); - when(mWifiManager.getConfiguredNetworks()) - .thenReturn(Lists.newArrayList(mSavedWifiConfiguration, mSavedWifiConfiguration2)); - when(mWifiManager.getScanResults()) - .thenReturn( - Lists.newArrayList(SAVED_SCAN_RESULT), - Lists.newArrayList(SAVED_SCAN_RESULT2)); - when(mWifiWakeupNetworkSelector.selectNetwork(anyMap(), anyList())) - .thenReturn(mSavedWifiConfiguration2); - when(mWifiManager.getWifiState()) - .thenReturn(WifiManager.WIFI_STATE_ENABLED, WifiManager.WIFI_STATE_DISABLED); - - mWifiWakeupController.mContentObserver.onChange(true); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiManager, never()).setWifiEnabled(true); - - Settings.Global.putInt(mContentResolver, Settings.Global.WIFI_WAKEUP_ENABLED, 1); - mWifiWakeupController.mContentObserver.onChange(true); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiManager).setWifiEnabled(true); - verify(mWifiWakeupHelper).startWifiSession(mSavedWifiConfiguration2); - } - - /** - * When Wi-Fi is disabled and a saved network is in the scan list, and then this network is not - * in the scan list 3x, and then it is, Wi-Fi should be enabled. - */ - @Test - public void wifiEnabled_userDisabledWifiNearSavedNetwork_thenLeaves_thenMovesBack() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn(Lists.newArrayList(mSavedWifiConfiguration)); - when(mWifiManager.getScanResults()) - .thenReturn( - Lists.newArrayList(SAVED_SCAN_RESULT), - Lists.newArrayList(OPEN_SCAN_RESULT), - Lists.newArrayList(OPEN_SCAN_RESULT), - Lists.newArrayList(OPEN_SCAN_RESULT), - Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiWakeupNetworkSelector.selectNetwork(anyMap(), anyList())) - .thenReturn(mSavedWifiConfiguration); - when(mWifiManager.getWifiState()) - .thenReturn(WifiManager.WIFI_STATE_ENABLED, WifiManager.WIFI_STATE_DISABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiManager, never()).setWifiEnabled(true); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiManager).setWifiEnabled(true); - verify(mWifiWakeupHelper).startWifiSession(mSavedWifiConfiguration); - } - - /** - * When Wi-Fi is disabled and a saved network is in the scan list, and then another scan result - * comes in 3x with only a different saved network, Wi-Fi should be enabled. - */ - @Test - public void wifiEnabled_userDisabledWifiNearSavedNetwork_thenMovesToAnotherSavedNetwork() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn(Lists.newArrayList(mSavedWifiConfiguration, mSavedWifiConfiguration2)); - when(mWifiManager.getScanResults()) - .thenReturn( - Lists.newArrayList(SAVED_SCAN_RESULT), - Lists.newArrayList(SAVED_SCAN_RESULT2)); - when(mWifiWakeupNetworkSelector.selectNetwork(anyMap(), anyList())) - .thenReturn(mSavedWifiConfiguration2); - when(mWifiManager.getWifiState()) - .thenReturn(WifiManager.WIFI_STATE_ENABLED, WifiManager.WIFI_STATE_DISABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - - verify(mWifiManager, never()).setWifiEnabled(true); - - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiManager).setWifiEnabled(true); - verify(mWifiWakeupHelper).startWifiSession(mSavedWifiConfiguration2); - } - - /** - * If Wi-Fi is disabled when a saved network is in the scan list, and then scan results come in - * for a saved wide area network 3x, Wi-Fi should not be enabled. - */ - @Test - public void wifiNotEnabled_userDisablesWifiNearSavedNetwork_thenMovesToWideAreaNetwork() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, mSavedWifiConfigurationWideArea)); - when(mWifiManager.getScanResults()) - .thenReturn( - Lists.newArrayList(SAVED_SCAN_RESULT), - Lists.newArrayList(SAVED_SCAN_RESULT_WIDE_AREA)); - when(mWifiManager.getWifiState()) - .thenReturn(WifiManager.WIFI_STATE_ENABLED, WifiManager.WIFI_STATE_DISABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verifyZeroInteractions(mWifiWakeupNetworkSelector); - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * When Wi-Fi is enabled and a saved network is in the scan list, Wi-Fi should not be enabled. - */ - @Test - public void wifiNotEnabled_wifiAlreadyEnabled() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, mSavedWifiConfigurationExternal)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verifyZeroInteractions(mWifiWakeupNetworkSelector); - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * When Wi-Fi is disabled near a saved network, and WifiWakeupController stops and starts, Wi-Fi - * should not be enabled. - */ - @Test - public void userDisabledWifiNearSavedNetwork_controllerStopped_controllerStarted() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn(Lists.newArrayList(mSavedWifiConfiguration)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiWakeupNetworkSelector.selectNetwork(anyMap(), anyList())) - .thenReturn(mSavedWifiConfiguration); - when(mWifiManager.getWifiState()) - .thenReturn(WifiManager.WIFI_STATE_ENABLED, WifiManager.WIFI_STATE_DISABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mWifiWakeupController.stop(); - - assertEquals( - ImmutableSet.of(HashUtil.getSsidHash(SAVED_SCAN_RESULT.SSID)), - Preferences.savedSsidsOnDisable.get()); - - mWifiWakeupController = - new WifiWakeupController( - RuntimeEnvironment.application, - mContentResolver, - new Handler(ShadowLooper.getMainLooper()), - mWifiManager, - mPowerManager, - mWifiWakeupNetworkSelector, - mWifiWakeupHelper); - mWifiWakeupController.start(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * When Wi-Fi is disabled and a saved network is in the scan list, but {@link - * WifiWakeupNetworkSelector}, does not choose this network, Wi-Fi should not be enabled. - */ - @Test - public void wifiNotEnabled_userNearSavedNetworkButNotSelected() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, mSavedWifiConfigurationExternal)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiWakeupNetworkSelector.selectNetwork(anyMap(), anyList())).thenReturn(null); - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_DISABLED); - - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * If Wi-Fi is disabled and a saved network is in the scan list, Wi-Fi should not be enabled if - * the user has not enabled the wifi wakeup feature. - */ - @Test - public void wifiNotEnabled_userDisablesWifiWakeupFeature() { - Settings.Global.putInt(mContentResolver, Settings.Global.WIFI_WAKEUP_ENABLED, 0); - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, mSavedWifiConfigurationExternal)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_DISABLED); - - mWifiWakeupController.mContentObserver.onChange(true); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verifyZeroInteractions(mWifiWakeupNetworkSelector); - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * If Wi-Fi is disabled and a saved network is in the scan list, Wi-Fi should not be enabled if - * the user is in airplane mode. - */ - @Test - public void wifiNotEnabled_userIsInAirplaneMode() { - Settings.Global.putInt(mContentResolver, Settings.Global.AIRPLANE_MODE_ON, 1); - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, mSavedWifiConfigurationExternal)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_DISABLED); - - mWifiWakeupController.mContentObserver.onChange(true); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verifyZeroInteractions(mWifiWakeupNetworkSelector); - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * If Wi-Fi is disabled and a saved network is in the scan list, Wi-Fi should not be enabled if - * the wifi AP state is not disabled. - */ - @Test - public void wifiNotEnabled_wifiApStateIsNotDisabled() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, mSavedWifiConfigurationExternal)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_DISABLED); - when(mWifiManager.getWifiApState()).thenReturn(WifiManager.WIFI_AP_STATE_ENABLED); - - mWifiWakeupController.mContentObserver.onChange(true); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendWifiApStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verifyZeroInteractions(mWifiWakeupNetworkSelector); - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * If Wi-Fi is disabled and a saved network is in the scan list, Wi-Fi should not be enabled if - * power saving mode is on. - */ - @Test - public void wifiNotEnabled_userInPowerSaveMode() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, mSavedWifiConfigurationExternal)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_DISABLED); - when(mPowerManager.isPowerSaveMode()).thenReturn(true); - - mWifiWakeupController.mContentObserver.onChange(true); - mBroadcastIntentTestHelper.sendPowerSaveModeChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendWifiApStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verifyZeroInteractions(mWifiWakeupNetworkSelector); - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * If Wi-Fi is disabled when a saved network is the scan list, Wi-Fi should not be enabled no - * matter how many scans are performed that include the saved network. - */ - @Test - public void wifiNotEnabled_userDisablesWifiNearSavedNetwork_thenDoesNotLeave() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, mSavedWifiConfigurationExternal)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verifyZeroInteractions(mWifiWakeupNetworkSelector); - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * If Wi-Fi is disabled when a saved network is in the scan list, and then that saved network is - * removed, Wi-Fi is not enabled even if the user leaves range of that network and returns. - */ - @Test - public void wifiNotEnabled_userDisablesWifiNearSavedNetwork_thenRemovesNetwork_thenStays() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList(mSavedWifiConfiguration), - Lists.<WifiConfiguration>newArrayList()); - when(mWifiManager.getScanResults()) - .thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)) - .thenReturn(Lists.<ScanResult>newArrayList()) - .thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiWakeupNetworkSelector.selectNetwork(anyMap(), anyList())).thenReturn(null); - when(mWifiManager.getWifiState()) - .thenReturn(WifiManager.WIFI_STATE_ENABLED, WifiManager.WIFI_STATE_DISABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verify(mWifiManager, never()).setWifiEnabled(true); - } - - /** - * If Wi-Fi is disabled when 2 saved networks are in the scan list, and then a scan result comes - * in with only 1 saved network 3x, Wi-Fi should not be enabled. - */ - @Test - public void wifiNotEnabled_userDisablesWifiNear2SavedNetworks_thenLeavesRangeOfOneOfThem() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn(Lists.newArrayList(mSavedWifiConfiguration, mSavedWifiConfiguration2)); - when(mWifiManager.getScanResults()) - .thenReturn( - Lists.newArrayList(SAVED_SCAN_RESULT, SAVED_SCAN_RESULT2), - Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiManager.getWifiState()) - .thenReturn(WifiManager.WIFI_STATE_ENABLED, WifiManager.WIFI_STATE_DISABLED); - - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - - verifyZeroInteractions(mWifiWakeupNetworkSelector); - verify(mWifiManager, never()).setWifiEnabled(true); - } - - @Test - public void logWifiEnabled_autopilotEnabledWifi() { - WifiConfiguration noInternetAccessNetwork = new WifiConfiguration(); - noInternetAccessNetwork.SSID = "Bof"; - when(mRoboCompatUtil.hasNoInternetAccess(noInternetAccessNetwork)).thenReturn(true); - - WifiConfiguration noInternetAccessExpectedNetwork = new WifiConfiguration(); - noInternetAccessExpectedNetwork.SSID = "fri"; - when(mRoboCompatUtil.isNoInternetAccessExpected(noInternetAccessExpectedNetwork)) - .thenReturn(true); - - WifiConfiguration disabledNetwork = new WifiConfiguration(); - disabledNetwork.SSID = "fleu"; - disabledNetwork.status = Status.DISABLED; - - WifiConfiguration noSsidNetwork = new WifiConfiguration(); - - when(mWifiManager.getConfiguredNetworks()) - .thenReturn( - Lists.newArrayList( - mSavedWifiConfiguration, - mSavedWifiConfiguration2, - mSavedWifiConfigurationExternal, - mSavedWifiConfigurationWideArea, - noInternetAccessNetwork, - noInternetAccessExpectedNetwork, - disabledNetwork, - noSsidNetwork)); - when(mWifiManager.getScanResults()).thenReturn(Lists.newArrayList(SAVED_SCAN_RESULT)); - when(mWifiWakeupNetworkSelector.selectNetwork(anyMap(), anyList())) - .thenReturn(mSavedWifiConfiguration); - when(mWifiManager.getWifiState()) - .thenReturn(WifiManager.WIFI_STATE_DISABLED, WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - mBroadcastIntentTestHelper.sendScanResultsAvailable(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - - verify(mWifiManager).setWifiEnabled(true); - } - - @Test - public void logWifiEnabled_userEnabledWifi() { - when(mWifiManager.getConfiguredNetworks()) - .thenReturn(Lists.newArrayList(mSavedWifiConfiguration, mSavedWifiConfiguration2)); - when(mWifiManager.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED); - - mBroadcastIntentTestHelper.sendConfiguredNetworksChanged(); - mBroadcastIntentTestHelper.sendWifiStateChanged(); - } - - /** Test dump() does not crash. */ - @Test - public void testDump() { - StringWriter stringWriter = new StringWriter(); - mWifiWakeupController.dump( - new FileDescriptor(), new PrintWriter(stringWriter), new String[0]); - } -} diff --git a/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupHelperTest.java b/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupHelperTest.java deleted file mode 100644 index 3840771..0000000 --- a/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupHelperTest.java +++ /dev/null @@ -1,187 +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.networkrecommendation.wakeup; - -import static com.android.networkrecommendation.TestData.SSID_1; -import static com.android.networkrecommendation.TestData.UNQUOTED_SSID_1; -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.app.Notification; -import android.app.NotificationManager; -import android.content.Context; -import android.content.Intent; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiManager; -import android.os.Handler; -import android.os.Looper; -import android.provider.Settings; -import android.util.ArraySet; -import com.android.networkrecommendation.config.Flag; -import com.android.networkrecommendation.config.PreferenceFile; -import com.android.networkrecommendation.config.Preferences; -import com.android.networkrecommendation.scoring.util.HashUtil; -import com.android.networkrecommendation.shadows.ShadowNotificationChannelUtil; -import java.util.Set; -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; -import org.robolectric.annotation.Config; -import org.robolectric.shadows.ShadowLooper; - -/** Unit tests for {@link WifiWakeupHelper} */ -@RunWith(RobolectricTestRunner.class) -@Config(manifest = "packages/services/NetworkRecommendation/AndroidManifest.xml", sdk = 23, -shadows={ShadowNotificationChannelUtil.class}) -public class WifiWakeupHelperTest { - - private Context mContext; - private WifiConfiguration mWifiConfiguration; - @Mock private NotificationManager mNotificationManager; - @Mock private WifiManager mWifiManager; - @Mock private WifiInfo mWifiInfo; - - private WifiWakeupHelper mWifiWakeupHelper; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - Flag.initForTest(); - mContext = RuntimeEnvironment.application; - PreferenceFile.init(mContext); - Preferences.ssidsForWakeupShown.remove(); - - mWifiConfiguration = new WifiConfiguration(); - mWifiConfiguration.SSID = SSID_1; - - when(mWifiManager.getConnectionInfo()).thenReturn(mWifiInfo); - - mWifiWakeupHelper = - new WifiWakeupHelper( - mContext, - mContext.getResources(), - new Handler(Looper.getMainLooper()), - mNotificationManager, - mWifiManager); - } - - @Test - public void notificationShowsOncePerSsid() { - mWifiWakeupHelper.startWifiSession(mWifiConfiguration); - ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); - - mWifiWakeupHelper.startWifiSession(mWifiConfiguration); - - verify(mNotificationManager, times(1)) - .notify(anyString(), anyInt(), any(Notification.class)); - Set<String> ssidSet = Preferences.ssidsForWakeupShown.get(); - assertEquals(1, ssidSet.size()); - assertTrue(ssidSet.contains(HashUtil.getSsidHash(UNQUOTED_SSID_1))); - } - - @Test - public void notificationCanceledWhenNeverConnected() { - mWifiWakeupHelper.startWifiSession(mWifiConfiguration); - ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); - - verify(mNotificationManager).cancel(anyString(), anyInt()); - } - - @Test - public void notificationCanceledWhenWifiDisabled() { - mWifiWakeupHelper.startWifiSession(mWifiConfiguration); - - when(mWifiInfo.getSSID()).thenReturn(UNQUOTED_SSID_1); - when(mWifiManager.isWifiEnabled()).thenReturn(true, false); - - mContext.sendBroadcast(new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION)); - mContext.sendBroadcast(new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION)); - - verify(mNotificationManager, times(1)) - .notify(anyString(), anyInt(), any(Notification.class)); - verify(mNotificationManager).cancel(anyString(), anyInt()); - } - - @Test - public void notificationCanceledWhenSsidChanged() throws Exception { - mWifiWakeupHelper.startWifiSession(mWifiConfiguration); - - when(mWifiInfo.getSSID()).thenReturn(UNQUOTED_SSID_1, "blah"); - when(mWifiManager.isWifiEnabled()).thenReturn(true); - - mContext.sendBroadcast(new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION)); - - verify(mNotificationManager, never()).cancel(anyString(), anyInt()); - - mContext.sendBroadcast(new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION)); - - verify(mNotificationManager).cancel(anyString(), anyInt()); - } - - @Test - public void sessionLoggedWithoutNotification() { - Set<String> ssidsShown = new ArraySet<>(); - ssidsShown.add(HashUtil.getSsidHash(mWifiConfiguration.SSID)); - Preferences.ssidsForWakeupShown.put(ssidsShown); - when(mWifiInfo.getSSID()).thenReturn(UNQUOTED_SSID_1, "blah"); - when(mWifiManager.isWifiEnabled()).thenReturn(true); - - mWifiWakeupHelper.startWifiSession(mWifiConfiguration); - mContext.sendBroadcast(new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION)); - mContext.sendBroadcast(new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION)); - - verify(mNotificationManager, never()) - .notify(anyString(), anyInt(), any(Notification.class)); - verify(mNotificationManager, never()).cancel(anyString(), anyInt()); - } - - @Test - public void tappingOnSettingsFromNotificationOpensSettingsActivity() { - mWifiWakeupHelper.startWifiSession(mWifiConfiguration); - - mContext.sendBroadcast(new Intent(WifiWakeupHelper.ACTION_WIFI_SETTINGS)); - - Intent intent = Shadows.shadowOf(RuntimeEnvironment.application).getNextStartedActivity(); - - assertThat(intent.getAction()).isEqualTo(Settings.ACTION_WIFI_SETTINGS); - } - - @Test - public void dismissingNotificationCancelsNotification() { - mWifiWakeupHelper.startWifiSession(mWifiConfiguration); - - mContext.sendBroadcast( - new Intent(WifiWakeupHelper.ACTION_DISMISS_WIFI_ENABLED_NOTIFICATION)); - - verify(mNotificationManager, times(1)) - .notify(anyString(), anyInt(), any(Notification.class)); - verify(mNotificationManager).cancel(anyString(), anyInt()); - } -} diff --git a/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupNetworkSelectorTest.java b/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupNetworkSelectorTest.java deleted file mode 100644 index f48e3e4..0000000 --- a/robotests/src/com/android/networkrecommendation/wakeup/WifiWakeupNetworkSelectorTest.java +++ /dev/null @@ -1,240 +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.networkrecommendation.wakeup; - -import static com.android.networkrecommendation.TestData.BSSID_3; -import static com.android.networkrecommendation.TestData.UNQUOTED_SSID_1; -import static com.android.networkrecommendation.TestData.UNQUOTED_SSID_2; -import static com.android.networkrecommendation.TestData.UNQUOTED_SSID_3; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.net.RecommendationRequest; -import android.net.RecommendationResult; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiConfiguration; -import android.util.ArrayMap; -import com.android.networkrecommendation.R; -import com.android.networkrecommendation.SynchronousNetworkRecommendationProvider; -import com.android.networkrecommendation.util.RoboCompatUtil; -import com.google.common.collect.Lists; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; -import org.robolectric.annotation.Config; - -/** Unit tests for {@link WifiWakeupNetworkSelector} */ -@RunWith(RobolectricTestRunner.class) -@Config(manifest = "packages/services/NetworkRecommendation/AndroidManifest.xml", sdk = 23) -public class WifiWakeupNetworkSelectorTest { - private static ScanResult buildScanResult(String ssid, int level, int frequency, String caps) { - try { - ScanResult scanResult = ScanResult.class.getConstructor().newInstance(); - scanResult.SSID = ssid; - scanResult.level = level; - scanResult.frequency = frequency; - scanResult.capabilities = caps; - return scanResult; - } catch (Exception e) { - return null; - } - } - - private static final int FREQUENCY_24 = 2450; - private static final int FREQUENCY_5 = 5000; - private static final String CAPABILITIES_NONE = ""; - private static final String CAPABILITIES_PSK = "PSK"; - - private WifiConfiguration mWifiConfigurationPsk; - private WifiConfiguration mWifiConfigurationNone; - private WifiConfiguration mWifiConfigurationPskExternal; - private ArrayMap<String, WifiConfiguration> mSavedWifiConfigurationMap; - private int mMinQualified24; - private int mMinQualified5; - - @Mock private RoboCompatUtil mRoboCompatUtil; - @Mock private SynchronousNetworkRecommendationProvider mNetworkRecommendationProvider; - @Captor private ArgumentCaptor<RecommendationRequest> mRecommendationRequestCaptor; - - private WifiWakeupNetworkSelector mWifiWakeupNetworkSelector; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - RoboCompatUtil.setInstanceForTesting(mRoboCompatUtil); - - mSavedWifiConfigurationMap = new ArrayMap<>(); - mWifiConfigurationPsk = new WifiConfiguration(); - mWifiConfigurationPsk.SSID = "\"" + UNQUOTED_SSID_1 + "\""; - mWifiConfigurationPsk.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); - mSavedWifiConfigurationMap.put(UNQUOTED_SSID_1, mWifiConfigurationPsk); - - mWifiConfigurationNone = new WifiConfiguration(); - mWifiConfigurationNone.SSID = "\"" + UNQUOTED_SSID_2 + "\""; - mWifiConfigurationNone.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); - mSavedWifiConfigurationMap.put(UNQUOTED_SSID_2, mWifiConfigurationNone); - - mWifiConfigurationPskExternal = new WifiConfiguration(); - mWifiConfigurationPskExternal.SSID = "\"" + UNQUOTED_SSID_3 + "\""; - mWifiConfigurationPskExternal.BSSID = BSSID_3; - mWifiConfigurationPskExternal.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); - when(mRoboCompatUtil.useExternalScores(mWifiConfigurationPskExternal)).thenReturn(true); - mSavedWifiConfigurationMap.put(UNQUOTED_SSID_3, mWifiConfigurationPskExternal); - - mMinQualified24 = - RuntimeEnvironment.application - .getResources() - .getInteger(R.integer.config_netrec_wifi_score_low_rssi_threshold_24GHz); - mMinQualified5 = - RuntimeEnvironment.application - .getResources() - .getInteger(R.integer.config_netrec_wifi_score_low_rssi_threshold_5GHz); - - mWifiWakeupNetworkSelector = - new WifiWakeupNetworkSelector( - RuntimeEnvironment.application.getResources(), - mNetworkRecommendationProvider); - } - - @Test - public void testSelectNetwork_noSavedNetworksInScanResults() { - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createDoNotConnectRecommendation()); - List<ScanResult> scanResults = - Lists.newArrayList( - buildScanResult("blah", mMinQualified5 + 1, FREQUENCY_5, CAPABILITIES_NONE), - buildScanResult( - "blahtoo", mMinQualified24 + 1, FREQUENCY_24, CAPABILITIES_NONE)); - - WifiConfiguration selectedNetwork = - mWifiWakeupNetworkSelector.selectNetwork(mSavedWifiConfigurationMap, scanResults); - - assertNull(selectedNetwork); - verify(mNetworkRecommendationProvider, never()) - .requestRecommendation(any(RecommendationRequest.class)); - } - - @Test - public void testSelectNetwork_noQualifiedSavedNetworks() { - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createDoNotConnectRecommendation()); - List<ScanResult> scanResults = - Lists.newArrayList( - buildScanResult( - UNQUOTED_SSID_2, - mMinQualified5 - 1, - FREQUENCY_5, - CAPABILITIES_NONE), - buildScanResult( - UNQUOTED_SSID_2, - mMinQualified24 - 1, - FREQUENCY_24, - CAPABILITIES_NONE)); - - WifiConfiguration selectedNetwork = - mWifiWakeupNetworkSelector.selectNetwork(mSavedWifiConfigurationMap, scanResults); - - assertNull(selectedNetwork); - verify(mNetworkRecommendationProvider, never()) - .requestRecommendation(any(RecommendationRequest.class)); - } - - @Test - public void testSelectNetwork_noMatchingScanResults() { - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn(RecommendationResult.createDoNotConnectRecommendation()); - List<ScanResult> scanResults = - Lists.newArrayList( - buildScanResult( - UNQUOTED_SSID_1, - mMinQualified5 + 1, - FREQUENCY_5, - CAPABILITIES_NONE), - buildScanResult( - UNQUOTED_SSID_1, - mMinQualified24 + 1, - FREQUENCY_24, - CAPABILITIES_NONE)); - - WifiConfiguration selectedNetwork = - mWifiWakeupNetworkSelector.selectNetwork(mSavedWifiConfigurationMap, scanResults); - - assertNull(selectedNetwork); - verify(mNetworkRecommendationProvider, never()) - .requestRecommendation(any(RecommendationRequest.class)); - } - - @Test - public void testSelectNetwork_secureNetworkOverUnsecure() { - List<ScanResult> scanResults = - Lists.newArrayList( - buildScanResult( - UNQUOTED_SSID_1, mMinQualified5 + 1, FREQUENCY_5, CAPABILITIES_PSK), - buildScanResult( - UNQUOTED_SSID_2, - mMinQualified5 + 1, - FREQUENCY_5, - CAPABILITIES_NONE)); - - WifiConfiguration selectedNetwork = - mWifiWakeupNetworkSelector.selectNetwork(mSavedWifiConfigurationMap, scanResults); - - assertEquals(mWifiConfigurationPsk.networkId, selectedNetwork.networkId); - verify(mNetworkRecommendationProvider, never()) - .requestRecommendation(any(RecommendationRequest.class)); - } - - @Test - public void testSelectNetwork_deferToProviderForOpenAndUseExternalScores() { - when(mNetworkRecommendationProvider.requestRecommendation(any(RecommendationRequest.class))) - .thenReturn( - RecommendationResult.createConnectRecommendation( - mWifiConfigurationPskExternal)); - List<ScanResult> scanResults = - Lists.newArrayList( - buildScanResult( - UNQUOTED_SSID_3, mMinQualified5 + 1, FREQUENCY_5, CAPABILITIES_PSK), - buildScanResult( - UNQUOTED_SSID_2, - mMinQualified5 + 1, - FREQUENCY_5, - CAPABILITIES_NONE)); - - WifiConfiguration selectedNetwork = - mWifiWakeupNetworkSelector.selectNetwork(mSavedWifiConfigurationMap, scanResults); - - assertEquals(mWifiConfigurationPskExternal, selectedNetwork); - verify(mNetworkRecommendationProvider) - .requestRecommendation(mRecommendationRequestCaptor.capture()); - - ScanResult[] openOrExternalScanResults = - mRecommendationRequestCaptor.getValue().getScanResults(); - assertEquals(2, openOrExternalScanResults.length); - assertEquals(UNQUOTED_SSID_3, openOrExternalScanResults[0].SSID); - assertEquals(UNQUOTED_SSID_2, openOrExternalScanResults[1].SSID); - } -} diff --git a/src/com/android/networkrecommendation/NetworkRecommendationService.java b/src/com/android/networkrecommendation/NetworkRecommendationService.java index 2207dda..d4923d0 100644 --- a/src/com/android/networkrecommendation/NetworkRecommendationService.java +++ b/src/com/android/networkrecommendation/NetworkRecommendationService.java @@ -28,6 +28,7 @@ import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.PowerManager; +import android.os.UserManager; import com.android.networkrecommendation.notify.WifiNotificationController; import com.android.networkrecommendation.notify.WifiNotificationHelper; @@ -69,19 +70,19 @@ public class NetworkRecommendationService extends Service { WifiManager wifiManager = getSystemService(WifiManager.class); PowerManager powerManager = getSystemService(PowerManager.class); + UserManager userManager = getSystemService(UserManager.class); Resources resources = getResources(); ContentResolver contentResolver = getContentResolver(); mWifiNotificationController = new WifiNotificationController( this, contentResolver, mControllerHandler, mProvider, - wifiManager, notificationManager, new WifiNotificationHelper(this)); + wifiManager, notificationManager, userManager, new WifiNotificationHelper(this)); WifiWakeupNetworkSelector wifiWakeupNetworkSelector = new WifiWakeupNetworkSelector(resources, mProvider); WifiWakeupHelper wifiWakeupHelper = new WifiWakeupHelper(this, resources, mControllerHandler, notificationManager, wifiManager); mWifiWakeupController = new WifiWakeupController(this, getContentResolver(), mControllerHandler, wifiManager, - getSystemService(PowerManager.class), wifiWakeupNetworkSelector, - wifiWakeupHelper); + powerManager, userManager, wifiWakeupNetworkSelector, wifiWakeupHelper); } @Override diff --git a/src/com/android/networkrecommendation/notify/WifiNotificationController.java b/src/com/android/networkrecommendation/notify/WifiNotificationController.java index a6a9e70..c134b47 100644 --- a/src/com/android/networkrecommendation/notify/WifiNotificationController.java +++ b/src/com/android/networkrecommendation/notify/WifiNotificationController.java @@ -33,6 +33,7 @@ import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Handler; +import android.os.UserManager; import android.provider.Settings; import android.support.annotation.IntDef; import android.support.annotation.Nullable; @@ -61,6 +62,9 @@ public class WifiNotificationController { /** Whether the user has set the setting to show the 'available networks' notification. */ private boolean mNotificationEnabled; + /** Whether the user has {@link UserManager#DISALLOW_CONFIG_WIFI} restriction. */ + private boolean mWifiConfigRestricted; + /** Observes the user setting to keep {@link #mNotificationEnabled} in sync. */ private final NotificationEnabledSettingObserver mNotificationEnabledSettingObserver; @@ -72,19 +76,21 @@ public class WifiNotificationController { /** These are all of the possible states for the open networks available notification. */ @IntDef({ - State.HIDDEN, - State.SHOWING_CONNECT_ACTIONS, - State.SHOWING_CONNECTING, - State.SHOWING_CONNECTED, - State.SHOWING_FAILURE + State.NO_RECOMMENDATION, + State.SHOWING_RECOMMENDATION_NOTIFICATION, + State.CONNECTING_IN_NOTIFICATION, + State.CONNECTING_IN_WIFI_PICKER, + State.CONNECTED, + State.CONNECT_FAILED }) @Retention(RetentionPolicy.SOURCE) public @interface State { - int HIDDEN = 0; - int SHOWING_CONNECT_ACTIONS = 1; - int SHOWING_CONNECTING = 2; - int SHOWING_CONNECTED = 3; - int SHOWING_FAILURE = 4; + int NO_RECOMMENDATION = 0; + int SHOWING_RECOMMENDATION_NOTIFICATION = 1; + int CONNECTING_IN_NOTIFICATION = 2; + int CONNECTING_IN_WIFI_PICKER = 3; + int CONNECTED = 4; + int CONNECT_FAILED = 5; } /** @@ -94,7 +100,7 @@ public class WifiNotificationController { private long mOpenNetworksLoggingRepeatTime; /** Current state of the notification. */ - @State private int mNotificationState = State.HIDDEN; + @State private int mState = State.NO_RECOMMENDATION; /** * The number of continuous scans that must occur before consider the supplicant in a scanning @@ -119,10 +125,11 @@ public class WifiNotificationController { /** Time in milliseconds to display the Failed To Connect notification. */ private static final int TIME_TO_SHOW_FAILED_MILLIS = 5000; - /** - * Try to connect to provided WifiConfiguration since user wants to connect to the recommended - * open access point. - */ + /** Try to connect to the recommended WifiConfiguration and also open the wifi picker. */ + static final String ACTION_CONNECT_TO_RECOMMENDED_NETWORK_AND_OPEN_SETTINGS = + "com.android.networkrecommendation.notify.CONNECT_TO_RECOMMENDED_NETWORK_AND_OPEN_SETTINGS"; + + /** Try to connect to the recommended WifiConfiguration. */ static final String ACTION_CONNECT_TO_RECOMMENDED_NETWORK = "com.android.networkrecommendation.notify.CONNECT_TO_RECOMMENDED_NETWORK"; @@ -130,6 +137,10 @@ public class WifiNotificationController { static final String ACTION_PICK_WIFI_NETWORK = "com.android.networkrecommendation.notify.ACTION_PICK_WIFI_NETWORK"; + /** Open wifi picker to see all networks after connect to the recommended network failed. */ + static final String ACTION_PICK_WIFI_NETWORK_AFTER_CONNECT_FAILURE = + "com.android.networkrecommendation.notify.ACTION_PICK_WIFI_NETWORK_AFTER_CONNECT_FAILURE"; + /** Handles behavior when notification is deleted. */ static final String ACTION_NOTIFICATION_DELETED = "com.android.networkrecommendation.notify.NOTIFICATION_DELETED"; @@ -148,6 +159,7 @@ public class WifiNotificationController { private final SynchronousNetworkRecommendationProvider mNetworkRecommendationProvider; private final WifiManager mWifiManager; private final NotificationManager mNotificationManager; + private final UserManager mUserManager; private final WifiNotificationHelper mWifiNotificationHelper; private NetworkInfo mNetworkInfo; private NetworkInfo.DetailedState mDetailedState; @@ -160,12 +172,14 @@ public class WifiNotificationController { SynchronousNetworkRecommendationProvider networkRecommendationProvider, WifiManager wifiManager, NotificationManager notificationManager, + UserManager userManager, WifiNotificationHelper helper) { mContext = context; mContentResolver = contentResolver; mNetworkRecommendationProvider = networkRecommendationProvider; mWifiManager = wifiManager; mNotificationManager = notificationManager; + mUserManager = userManager; mHandler = handler; mWifiNotificationHelper = helper; mStarted = new AtomicBoolean(false); @@ -193,13 +207,18 @@ public class WifiNotificationController { filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); + filter.addAction(RoboCompatUtil.ACTION_USER_RESTRICTIONS_CHANGED); + filter.addAction(ACTION_CONNECT_TO_RECOMMENDED_NETWORK_AND_OPEN_SETTINGS); filter.addAction(ACTION_CONNECT_TO_RECOMMENDED_NETWORK); filter.addAction(ACTION_NOTIFICATION_DELETED); filter.addAction(ACTION_PICK_WIFI_NETWORK); + filter.addAction(ACTION_PICK_WIFI_NETWORK_AFTER_CONNECT_FAILURE); mContext.registerReceiver( mBroadcastReceiver, filter, null /* broadcastPermission */, mHandler); mNotificationEnabledSettingObserver.register(); + + handleUserRestrictionsChanged(); } /** Stops {@link WifiNotificationController}. */ @@ -216,52 +235,45 @@ public class WifiNotificationController { @Override public void onReceive(Context context, Intent intent) { try { - if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { - mWifiState = mWifiManager.getWifiState(); - resetNotification(); - } else if (intent.getAction() - .equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { - mNetworkInfo = - intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); - NetworkInfo.DetailedState detailedState = - mNetworkInfo.getDetailedState(); - if (detailedState != NetworkInfo.DetailedState.SCANNING - && detailedState != mDetailedState) { - mDetailedState = detailedState; - switch (mDetailedState) { - case CONNECTED: - updateNotificationOnConnect(); - break; - case DISCONNECTED: - case CAPTIVE_PORTAL_CHECK: - resetNotification(); - break; - - // TODO: figure out if these are failure cases when connecting - case IDLE: - case SCANNING: - case CONNECTING: - case DISCONNECTING: - case AUTHENTICATING: - case OBTAINING_IPADDR: - case SUSPENDED: - case FAILED: - case BLOCKED: - case VERIFYING_POOR_LINK: - break; - } - } - } else if (intent.getAction() - .equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { - checkAndSetNotification(mNetworkInfo); - } else if (intent.getAction() - .equals(ACTION_CONNECT_TO_RECOMMENDED_NETWORK)) { - connectToRecommendedNetwork(); - } else if (intent.getAction().equals(ACTION_NOTIFICATION_DELETED)) { - handleNotificationDeleted(); - } else if (intent.getAction().equals(ACTION_PICK_WIFI_NETWORK)) { - openWifiPicker(); + switch (intent.getAction()) { + case WifiManager.WIFI_STATE_CHANGED_ACTION: + mWifiState = mWifiManager.getWifiState(); + resetNotification(); + break; + case WifiManager.NETWORK_STATE_CHANGED_ACTION: + handleNetworkStateChange(intent); + break; + case WifiManager.SCAN_RESULTS_AVAILABLE_ACTION: + checkAndSetNotification(mNetworkInfo); + break; + case RoboCompatUtil.ACTION_USER_RESTRICTIONS_CHANGED: + handleUserRestrictionsChanged(); + break; + case ACTION_CONNECT_TO_RECOMMENDED_NETWORK_AND_OPEN_SETTINGS: + connectToRecommendedNetwork(); + openWifiPicker(); + updateOnConnecting(false /* showNotification*/); + break; + case ACTION_CONNECT_TO_RECOMMENDED_NETWORK: + connectToRecommendedNetwork(); + updateOnConnecting(true /* showNotification*/); + break; + case ACTION_NOTIFICATION_DELETED: + handleNotificationDeleted(); + break; + case ACTION_PICK_WIFI_NETWORK: + openWifiPicker(); + break; + case ACTION_PICK_WIFI_NETWORK_AFTER_CONNECT_FAILURE: + openWifiPicker(); + break; + default: + Blog.e( + TAG, + "Unexpected broadcast. [action=%s]", + intent.getAction()); } + } catch (RuntimeException re) { // TODO(b/35044022) Remove try/catch after a couple of releases when we are confident // this is not going to throw. @@ -270,13 +282,50 @@ public class WifiNotificationController { } }; + private void handleNetworkStateChange(Intent intent) { + mNetworkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); + NetworkInfo.DetailedState detailedState = mNetworkInfo.getDetailedState(); + if (detailedState != NetworkInfo.DetailedState.SCANNING + && detailedState != mDetailedState) { + mDetailedState = detailedState; + switch (mDetailedState) { + case CONNECTED: + updateOnConnect(); + break; + case DISCONNECTED: + case CAPTIVE_PORTAL_CHECK: + resetNotification(); + break; + + // TODO: figure out if these are failure cases when connecting + case IDLE: + case SCANNING: + case CONNECTING: + case DISCONNECTING: + case AUTHENTICATING: + case OBTAINING_IPADDR: + case SUSPENDED: + case FAILED: + case BLOCKED: + case VERIFYING_POOR_LINK: + break; + } + } + } + + private void handleUserRestrictionsChanged() { + mWifiConfigRestricted = mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI); + Blog.v(TAG, "handleUserRestrictionsChanged: %b", mWifiConfigRestricted); + } + private void checkAndSetNotification(NetworkInfo networkInfo) { // TODO: unregister broadcast so we do not have to check here // If we shouldn't place a notification on available networks, then // don't bother doing any of the following if (!mNotificationEnabled + || mWifiConfigRestricted || mWifiState != WifiManager.WIFI_STATE_ENABLED - || mNotificationState > State.SHOWING_CONNECT_ACTIONS) { + || mState > State.SHOWING_RECOMMENDATION_NOTIFICATION) { return; } @@ -374,7 +423,7 @@ public class WifiNotificationController { // place than here) // Not enough time has passed to show the notification again - if (mNotificationState == State.HIDDEN + if (mState == State.NO_RECOMMENDATION && System.currentTimeMillis() < mNotificationRepeatTime) { return; } @@ -382,23 +431,22 @@ public class WifiNotificationController { mWifiNotificationHelper.createMainNotification(mRecommendedNetwork); mNotificationRepeatTime = System.currentTimeMillis() + mNotificationRepeatDelayMs; postNotification(notification); - if (mNotificationState != State.SHOWING_CONNECT_ACTIONS) { - mNotificationState = State.SHOWING_CONNECT_ACTIONS; + if (mState != State.SHOWING_RECOMMENDATION_NOTIFICATION) { + mState = State.SHOWING_RECOMMENDATION_NOTIFICATION; } } /** Opens activity to allow the user to select a wifi network. */ private void openWifiPicker() { + // Close notification drawer before opening the picker. + mContext.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); mContext.startActivity( new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); removeNotification(); } - /** - * Attempts to connect to recommended network and updates the notification to show Connecting - * state. TODO(33668991): work with UX to polish notification UI and figure out failure states - */ + /** Attempts to connect to recommended network the recommended network. */ private void connectToRecommendedNetwork() { if (mRecommendedNetwork == null) { return; @@ -407,63 +455,70 @@ public class WifiNotificationController { // Attempts to connect to recommended network. RoboCompatUtil.getInstance().connectToWifi(mWifiManager, mRecommendedNetwork); + } - // Update notification to connecting status. - Notification notification = - mWifiNotificationHelper.createConnectingNotification(mRecommendedNetwork); - postNotification(notification); - mNotificationState = State.SHOWING_CONNECTING; + private void updateOnConnecting(boolean showNotification) { + if (showNotification) { + // Update notification to connecting status. + Notification notification = + mWifiNotificationHelper.createConnectingNotification(mRecommendedNetwork); + postNotification(notification); + mState = State.CONNECTING_IN_NOTIFICATION; + } else { + mState = State.CONNECTING_IN_WIFI_PICKER; + } mHandler.postDelayed( () -> { - if (mNotificationState == State.SHOWING_CONNECTING) { - showFailedToConnectNotification(); - } + updateOnFailedToConnect(); }, TIME_TO_SHOW_CONNECTING_MILLIS); } /** * When detailed state changes to CONNECTED, show connected notification or reset notification. - * TODO: determine failure state where main notification shows but connected. */ - private void updateNotificationOnConnect() { - if (mNotificationState != State.SHOWING_CONNECTING) { - return; + private void updateOnConnect() { + if (mState == State.CONNECTING_IN_NOTIFICATION) { + Notification notification = + mWifiNotificationHelper.createConnectedNotification(mRecommendedNetwork); + postNotification(notification); + mState = State.CONNECTED; + mHandler.postDelayed( + () -> { + if (mState == State.CONNECTED) { + removeNotification(); + } + }, + TIME_TO_SHOW_CONNECTED_MILLIS); + } else if (mState == State.CONNECTING_IN_WIFI_PICKER) { + removeNotification(); } - - Notification notification = - mWifiNotificationHelper.createConnectedNotification(mRecommendedNetwork); - postNotification(notification); - mNotificationState = State.SHOWING_CONNECTED; - mHandler.postDelayed( - () -> { - if (mNotificationState == State.SHOWING_CONNECTED) { - removeNotification(); - } - }, - TIME_TO_SHOW_CONNECTED_MILLIS); } /** * Displays the Failed To Connect notification after the Connecting notification is shown for * {@link #TIME_TO_SHOW_CONNECTING_MILLIS} duration. */ - private void showFailedToConnectNotification() { - Notification notification = mWifiNotificationHelper.createFailedToConnectNotification(); - postNotification(notification); - mNotificationState = State.SHOWING_FAILURE; - mHandler.postDelayed( - () -> { - if (mNotificationState == State.SHOWING_FAILURE) { - removeNotification(); - } - }, - TIME_TO_SHOW_FAILED_MILLIS); + private void updateOnFailedToConnect() { + if (mState == State.CONNECTING_IN_NOTIFICATION) { + Notification notification = mWifiNotificationHelper.createFailedToConnectNotification(); + postNotification(notification); + mState = State.CONNECT_FAILED; + mHandler.postDelayed( + () -> { + if (mState == State.CONNECT_FAILED) { + removeNotification(); + } + }, + TIME_TO_SHOW_FAILED_MILLIS); + } else if (mState == State.CONNECTING_IN_WIFI_PICKER) { + removeNotification(); + } } /** Handles behavior when notification is dismissed. */ private void handleNotificationDeleted() { - mNotificationState = State.HIDDEN; + mState = State.NO_RECOMMENDATION; mRecommendedNetwork = null; } @@ -476,7 +531,7 @@ public class WifiNotificationController { * clears the current notification. */ private void resetNotification() { - if (mNotificationState != State.HIDDEN) { + if (mState != State.NO_RECOMMENDATION) { removeNotification(); } mRecommendedNetwork = null; @@ -487,14 +542,14 @@ public class WifiNotificationController { private void removeNotification() { mNotificationManager.cancel(NOTIFICATION_TAG, NOTIFICATION_ID); - mNotificationState = State.HIDDEN; + mState = State.NO_RECOMMENDATION; mRecommendedNetwork = null; } public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { pw.println("mNotificationEnabled " + mNotificationEnabled); pw.println("mNotificationRepeatTime " + mNotificationRepeatTime); - pw.println("mNotificationState " + mNotificationState); + pw.println("mState " + mState); pw.println("mNumScansSinceNetworkStateChange " + mNumScansSinceNetworkStateChange); } diff --git a/src/com/android/networkrecommendation/notify/WifiNotificationHelper.java b/src/com/android/networkrecommendation/notify/WifiNotificationHelper.java index c265e8f..b19f25c 100644 --- a/src/com/android/networkrecommendation/notify/WifiNotificationHelper.java +++ b/src/com/android/networkrecommendation/notify/WifiNotificationHelper.java @@ -39,7 +39,8 @@ public class WifiNotificationHelper { /** * Creates the main open networks notification with two actions. "Options" link to the Wi-Fi * picker activity, and "Connect" prompts {@link WifiNotificationController} to connect to the - * recommended network. + * recommended network. Tapping on the content body connects to the recommended network and + * opens the wifi picker */ public Notification createMainNotification(WifiConfiguration config) { PendingIntent allNetworksIntent = @@ -67,7 +68,16 @@ public class WifiNotificationHelper { mContext.getText(R.string.wifi_available_action_connect), connectIntent) .build(); + PendingIntent connectAndOpenPickerIntent = + PendingIntent.getBroadcast( + mContext, + 0, + new Intent( + WifiNotificationController + .ACTION_CONNECT_TO_RECOMMENDED_NETWORK_AND_OPEN_SETTINGS), + FLAG_UPDATE_CURRENT); return createNotificationBuilder(R.string.wifi_available_title, config.SSID) + .setContentIntent(connectAndOpenPickerIntent) .addAction(connectAction) .addAction(allNetworksAction) .build(); @@ -95,19 +105,21 @@ public class WifiNotificationHelper { /** * Creates the notification that indicates the controller failed to connect to the recommended - * network. + * network. Tapping this notification opens the wifi picker. */ public Notification createFailedToConnectNotification() { - PendingIntent allNetworksIntent = + PendingIntent openWifiPickerAfterFailure = PendingIntent.getBroadcast( mContext, 0, - new Intent(WifiNotificationController.ACTION_PICK_WIFI_NETWORK), + new Intent( + WifiNotificationController + .ACTION_PICK_WIFI_NETWORK_AFTER_CONNECT_FAILURE), FLAG_UPDATE_CURRENT); return createNotificationBuilder( R.string.wifi_available_title_failed, mContext.getString(R.string.wifi_available_content_failed)) - .setContentIntent(allNetworksIntent) + .setContentIntent(openWifiPickerAfterFailure) .setAutoCancel(true) .build(); } @@ -129,6 +141,7 @@ public class WifiNotificationHelper { .setContentTitle(title) .setColor(mContext.getColor(R.color.color_tint)) .setContentText(content) + .setShowWhen(false) .setLocalOnly(true) .addExtras(getOverrideLabelExtras()); return NotificationChannelUtil.setChannel(builder, CHANNEL_ID_NETWORK_AVAILABLE); diff --git a/src/com/android/networkrecommendation/scoring/util/NetworkUtil.java b/src/com/android/networkrecommendation/scoring/util/NetworkUtil.java index 55112a3..b27bbe6 100644 --- a/src/com/android/networkrecommendation/scoring/util/NetworkUtil.java +++ b/src/com/android/networkrecommendation/scoring/util/NetworkUtil.java @@ -18,10 +18,10 @@ package com.android.networkrecommendation.scoring.util; import static android.net.wifi.WifiConfiguration.KeyMgmt.IEEE8021X; import static android.net.wifi.WifiConfiguration.KeyMgmt.WPA_EAP; import static android.net.wifi.WifiConfiguration.KeyMgmt.WPA_PSK; +import static com.android.networkrecommendation.util.ScanResultUtil.isScanResultForOpenNetwork; import android.content.Context; import android.net.NetworkKey; -import android.net.WifiKey; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; @@ -30,8 +30,8 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import com.android.networkrecommendation.Constants; -import com.android.networkrecommendation.config.G; import com.android.networkrecommendation.util.Blog; +import com.android.networkrecommendation.util.ScanResultUtil; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -95,36 +95,14 @@ public final class NetworkUtil { Map<NetworkKey, Boolean> openKeys = new HashMap<>(); for (int i = 0; i < scanResults.size(); i++) { ScanResult scanResult = scanResults.get(i); - try { - openKeys.put( - new NetworkKey( - new WifiKey("\"" + scanResult.SSID + "\"", scanResult.BSSID)), - isOpenNetwork(scanResult)); - } catch (IllegalArgumentException iae) { - // WifiKey rejects some SSIDs that ScanResults considers valid, e.g. those - // containing a carriage return (as of L MR1). It's okay to just exclude those - // SSIDs from this list, because the platform uses the same WifiKey implementation, and so - // it would never be asking about such SSIDs in the first place. - Blog.v( - Constants.TAG, - "Couldn't make a wifi key from " - + Blog.pii(scanResult.SSID, G.Netrec.enableSensitiveLogging.get()) - + "/" - + Blog.pii(scanResult.BSSID, G.Netrec.enableSensitiveLogging.get()) - + ", skipping"); + NetworkKey networkKey = ScanResultUtil.createNetworkKey(scanResult); + if (networkKey != null) { + openKeys.put(networkKey, isScanResultForOpenNetwork(scanResult)); } } return openKeys; } - private static boolean isOpenNetwork(ScanResult result) { - return !TextUtils.isEmpty(result.SSID) - && !TextUtils.isEmpty(result.BSSID) - && !result.capabilities.contains("WEP") - && !result.capabilities.contains("PSK") - && !result.capabilities.contains("EAP"); - } - /** Returns true if the given config is for an "open" network. */ public static boolean isOpenNetwork(@NonNull WifiConfiguration config) { if (config.allowedKeyManagement.get(WPA_PSK) // covers WPA_PSK and WPA2_PSK diff --git a/src/com/android/networkrecommendation/scoring/util/Util.java b/src/com/android/networkrecommendation/scoring/util/Util.java index 3390531..4a8c80b 100644 --- a/src/com/android/networkrecommendation/scoring/util/Util.java +++ b/src/com/android/networkrecommendation/scoring/util/Util.java @@ -15,8 +15,12 @@ */ package com.android.networkrecommendation.scoring.util; +import static com.android.networkrecommendation.Constants.TAG; + import android.content.Context; import android.net.NetworkScoreManager; +import android.net.ScoredNetwork; +import com.android.networkrecommendation.util.Blog; /** Utility methods for the scorer. */ public final class Util { @@ -30,4 +34,38 @@ public final class Util { return packageName.equals(activeScorer); } + + /** Clear scores in the platform if we're the active scorer. */ + public static boolean safelyClearScores(Context context) { + try { + NetworkScoreManager scoreManager = + (NetworkScoreManager) context.getSystemService(Context.NETWORK_SCORE_SERVICE); + scoreManager.clearScores(); + return true; + } catch (SecurityException e) { + Blog.v( + TAG, + e, + "SecurityException trying to clear scores, probably just an unavoidable race condition. " + + "Ignoring."); + return false; + } + } + + /** Update scores in the platform if we're the active scorer. */ + public static boolean safelyUpdateScores(Context context, ScoredNetwork[] networkScores) { + try { + NetworkScoreManager scoreManager = + (NetworkScoreManager) context.getSystemService(Context.NETWORK_SCORE_SERVICE); + scoreManager.updateScores(networkScores); + return true; + } catch (SecurityException e) { + Blog.v( + TAG, + e, + "SecurityException trying to update scores, probably just an unavoidable race condition. " + + "Ignoring."); + return false; + } + } } diff --git a/src/com/android/networkrecommendation/util/RoboCompatUtil.java b/src/com/android/networkrecommendation/util/RoboCompatUtil.java index 24c6d03..7aa0d7b 100644 --- a/src/com/android/networkrecommendation/util/RoboCompatUtil.java +++ b/src/com/android/networkrecommendation/util/RoboCompatUtil.java @@ -23,6 +23,7 @@ import android.net.ScoredNetwork; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Bundle; +import android.os.UserManager; import android.support.annotation.VisibleForTesting; /** @@ -31,6 +32,13 @@ import android.support.annotation.VisibleForTesting; */ public class RoboCompatUtil { + /** + * {@link UserManager#ACTION_USER_RESTRICTIONS_CHANGED}. TODO: remove when string is available + * in experimental. + */ + public static final String ACTION_USER_RESTRICTIONS_CHANGED = + "android.os.action.USER_RESTRICTIONS_CHANGED"; + private static RoboCompatUtil mRoboCompatUtil; private RoboCompatUtil() {} diff --git a/src/com/android/networkrecommendation/util/SsidUtil.java b/src/com/android/networkrecommendation/util/SsidUtil.java index 52ed7de..b15ac5f 100644 --- a/src/com/android/networkrecommendation/util/SsidUtil.java +++ b/src/com/android/networkrecommendation/util/SsidUtil.java @@ -19,6 +19,7 @@ import static com.android.networkrecommendation.Constants.TAG; import android.net.WifiKey; import android.support.annotation.Nullable; +import android.text.TextUtils; import com.android.networkrecommendation.config.G; /** Utility methods for Wifi Network SSID and BSSID manipulation. */ @@ -31,7 +32,7 @@ public final class SsidUtil { /** Quote an SSID if it hasn't already been quoted. */ @Nullable - public static String quoteSsid(String ssid) { + public static String quoteSsid(@Nullable String ssid) { if (ssid == null) { return null; } @@ -41,6 +42,14 @@ public final class SsidUtil { return "\"" + ssid + "\""; } + /** Strip initial and final quotations marks from an SSID. */ + public static String unquoteSsid(@Nullable String ssid) { + if (ssid == null) { + return null; + } + return ssid.replaceAll("^\"", "").replaceAll("\"$", ""); + } + /** * Create a WifiKey for the given SSID/BSSID. Returns null if the key could not be created * (ssid/bssid are not valid patterns). @@ -77,6 +86,24 @@ public final class SsidUtil { } /** + * Returns true if the canonical version of two SSIDs (ignoring wrapping quotations) is equal. + */ + public static boolean areEqual(@Nullable String ssid1, @Nullable String ssid2) { + String quotedSsid1 = quoteSsid(ssid1); + String quotedSsid2 = quoteSsid(ssid2); + return TextUtils.equals(quotedSsid1, quotedSsid2); + } + + /** + * Returns a string version of the SSID for logging which is typically redacted. + * + * <p>The ID will only be returned verbatim if the enableSensitiveLogging flag is set. + */ + public static String getRedactedId(String ssid) { + return Blog.pii(String.format("%s", ssid), G.Netrec.enableSensitiveLogging.get()); + } + + /** * Returns a string version of the SSID/BSSID pair for logging which is typically redacted. * * <p>The IDs will only be returned verbatim if the enableSensitiveLogging flag is set. diff --git a/src/com/android/networkrecommendation/wakeup/WifiWakeupController.java b/src/com/android/networkrecommendation/wakeup/WifiWakeupController.java index a9aa61f..4c9b4c1 100644 --- a/src/com/android/networkrecommendation/wakeup/WifiWakeupController.java +++ b/src/com/android/networkrecommendation/wakeup/WifiWakeupController.java @@ -28,6 +28,7 @@ import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Handler; import android.os.PowerManager; +import android.os.UserManager; import android.provider.Settings; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; @@ -65,6 +66,7 @@ public class WifiWakeupController { private final ContentResolver mContentResolver; private final WifiManager mWifiManager; private final PowerManager mPowerManager; + private final UserManager mUserManager; private final WifiWakeupNetworkSelector mWifiWakeupNetworkSelector; private final Handler mHandler; private final WifiWakeupHelper mWifiWakeupHelper; @@ -82,6 +84,7 @@ public class WifiWakeupController { private boolean mAirplaneModeEnabled; private boolean mAutopilotEnabledWifi; private boolean mPowerSaverModeOn; + private boolean mWifiConfigRestricted; public WifiWakeupController( Context context, @@ -89,6 +92,7 @@ public class WifiWakeupController { Handler handler, WifiManager wifiManager, PowerManager powerManager, + UserManager userManager, WifiWakeupNetworkSelector wifiWakeupNetworkSelector, WifiWakeupHelper wifiWakeupHelper) { mContext = context; @@ -98,6 +102,7 @@ public class WifiWakeupController { mStarted = new AtomicBoolean(false); mWifiManager = wifiManager; mPowerManager = powerManager; + mUserManager = userManager; mWifiWakeupNetworkSelector = wifiWakeupNetworkSelector; mContentObserver = new ContentObserver(mHandler) { @@ -115,6 +120,11 @@ public class WifiWakeupController { Settings.Global.AIRPLANE_MODE_ON, 0) == 1; + Blog.d( + TAG, + "onChange: [mWifiWakeupEnabled=%b,mAirplaneModeEnabled=%b]", + mWifiWakeupEnabled, + mAirplaneModeEnabled); } }; } @@ -138,6 +148,9 @@ public class WifiWakeupController { } else if (PowerManager.ACTION_POWER_SAVE_MODE_CHANGED.equals( intent.getAction())) { handlePowerSaverModeChanged(); + } else if (RoboCompatUtil.ACTION_USER_RESTRICTIONS_CHANGED.equals( + intent.getAction())) { + handleUserRestrictionsChanged(); } } catch (RuntimeException re) { // TODO(b/35044022) Remove try/catch after a couple of releases when we are confident @@ -160,6 +173,7 @@ public class WifiWakeupController { filter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED); + filter.addAction(RoboCompatUtil.ACTION_USER_RESTRICTIONS_CHANGED); // TODO(b/33695273): conditionally register this receiver based on wifi enabled setting mContext.registerReceiver(mBroadcastReceiver, filter, null, mHandler); mContentResolver.registerContentObserver( @@ -172,6 +186,7 @@ public class WifiWakeupController { mContentObserver); mContentObserver.onChange(true); handlePowerSaverModeChanged(); + handleUserRestrictionsChanged(); handleWifiApStateChanged(); handleConfiguredNetworksChanged(); handleWifiStateChanged(true); @@ -198,6 +213,11 @@ public class WifiWakeupController { Blog.v(TAG, "handleWifiApStateChanged: %d", mWifiApState); } + private void handleUserRestrictionsChanged() { + mWifiConfigRestricted = mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI); + Blog.v(TAG, "handleUserRestrictionsChanged: %b", mWifiConfigRestricted); + } + private void handleConfiguredNetworksChanged() { List<WifiConfiguration> wifiConfigurations = mWifiManager.getConfiguredNetworks(); if (wifiConfigurations == null) { @@ -289,7 +309,7 @@ public class WifiWakeupController { } private void handleScanResultsAvailable() { - if (!mWifiWakeupEnabled) { + if (!mWifiWakeupEnabled || mWifiConfigRestricted) { return; } List<ScanResult> scanResults = mWifiManager.getScanResults(); diff --git a/src/com/android/networkrecommendation/wakeup/WifiWakeupHelper.java b/src/com/android/networkrecommendation/wakeup/WifiWakeupHelper.java index 4e56aa2..8b4da55 100644 --- a/src/com/android/networkrecommendation/wakeup/WifiWakeupHelper.java +++ b/src/com/android/networkrecommendation/wakeup/WifiWakeupHelper.java @@ -146,7 +146,7 @@ public class WifiWakeupHelper { if (hashedSsidSet.isEmpty()) { hashedSsidSet = new ArraySet<>(); } else if (hashedSsidSet.contains(hashedSsid)) { - Blog.d( + Blog.i( TAG, "Already showed Wi-Fi Enabled notification for ssid: %s", Blog.pii(wifiConfiguration.SSID, G.Netrec.enableSensitiveLogging.get())); @@ -175,13 +175,15 @@ public class WifiWakeupHelper { extras.putString( Notification.EXTRA_SUBSTITUTE_APP_NAME, mResources.getString(R.string.notification_channel_group_name)); + int smallIcon = R.drawable.ic_signal_wifi_statusbar_not_connected; Notification.Builder notificationBuilder = new Notification.Builder(mContext) .setContentTitle(title) - .setSmallIcon(R.drawable.ic_signal_wifi_statusbar_not_connected) + .setSmallIcon(smallIcon) .setColor(mContext.getColor(R.color.color_tint)) .setStyle(new Notification.BigTextStyle().bigText(summary)) .setAutoCancel(true) + .setShowWhen(false) .setDeleteIntent(deletePendingIntent) .setPriority(Notification.PRIORITY_LOW) .setVisibility(Notification.VISIBILITY_PUBLIC) diff --git a/tests/Android.mk b/tests/Android.mk deleted file mode 100644 index a19ec78..0000000 --- a/tests/Android.mk +++ /dev/null @@ -1,20 +0,0 @@ -LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_MODULE_TAGS := tests - -LOCAL_STATIC_JAVA_LIBRARIES := \ - android-support-test \ - guava \ - jsr305 \ - mockito-target - -LOCAL_SRC_FILES := $(call all-java-files-under, src) - -LOCAL_PACKAGE_NAME := NetworkRecommendationTests -LOCAL_COMPATIBILITY_SUITE := device-tests -LOCAL_CERTIFICATE := platform - -LOCAL_INSTRUMENTATION_FOR := NetworkRecommendation - -include $(BUILD_PACKAGE) diff --git a/tests/AndroidManifest.xml b/tests/AndroidManifest.xml deleted file mode 100644 index 3ebaaf3..0000000 --- a/tests/AndroidManifest.xml +++ /dev/null @@ -1,31 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright (C) 2016 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. ---> - -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.android.networkrecommendation.tests"> - - <uses-permission android:name="android.permission.BIND_NETWORK_RECOMMENDATION_SERVICE"/> - <uses-permission android:name="android.permission.REQUEST_NETWORK_SCORES"/> - - <application> - <uses-library android:name="android.test.runner" /> - </application> - - <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" - android:targetPackage="com.android.networkrecommendation" - android:label="Tests for NetworkRecommendation"> - </instrumentation> -</manifest> diff --git a/tests/src/com/android/networkrecommendation/DefaultNetworkRecommendationProviderTest.java b/tests/src/com/android/networkrecommendation/DefaultNetworkRecommendationProviderTest.java deleted file mode 100644 index dc6c673..0000000 --- a/tests/src/com/android/networkrecommendation/DefaultNetworkRecommendationProviderTest.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Copyright (C) 2016 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.networkrecommendation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import android.content.Context; -import android.net.NetworkKey; -import android.net.NetworkRecommendationProvider; -import android.net.NetworkScoreManager; -import android.net.RecommendationRequest; -import android.net.RecommendationResult; -import android.net.RssiCurve; -import android.net.ScoredNetwork; -import android.net.WifiKey; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiConfiguration; -import android.net.wifi.WifiSsid; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.os.SystemClock; -import android.support.test.runner.AndroidJUnit4; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.io.PrintWriter; -import java.io.StringWriter; - -/** - * Tests the recommendation provider directly, to test internals of the provider rather than the - * service's API. - */ -@RunWith(AndroidJUnit4.class) -public class DefaultNetworkRecommendationProviderTest { - - private static final String GOOD_METERED_NETWORK_STRING_UNQUOTED = "Metered"; - private static final String GOOD_METERED_NETWORK_STRING = "\"Metered\",aa:bb:cc:dd:ee:ff" + - "|10,-128,-128,-128,-128,-128,-128,-128,-128,20,20,20,20,-128|1|0|4K"; - private static final RssiCurve GOOD_METERED_NETWORK_CURVE = new RssiCurve( - DefaultNetworkRecommendationProvider.CONSTANT_CURVE_START, 10 /* bucketWidth */, - new byte[]{-128, -128, -128, -128, -128, -128, -128, -128, 20, 20, 20, 20, -128}, - 0 /* defaultActiveNetworkBoost */); - private static final ScoredNetwork GOOD_METERED_NETWORK = new ScoredNetwork( - new NetworkKey(new WifiKey("\"Metered\"", "aa:bb:cc:dd:ee:ff")), - GOOD_METERED_NETWORK_CURVE, true /* meteredHint */, new Bundle()); - - private static final String GOOD_CAPTIVE_NETWORK_STRING_UNQUOTED = "Captive"; - private static final String GOOD_CAPTIVE_NETWORK_STRING = - "\"Captive\",ff:ee:dd:cc:bb:aa" - + "|18,-128,-128,-128,-128,-128,-128,21,21,21,-128|0|1|HD"; - private static final RssiCurve GOOD_CAPTIVE_NETWORK_CURVE = new RssiCurve( - DefaultNetworkRecommendationProvider.CONSTANT_CURVE_START, 18 /* bucketWidth */, - new byte[]{-128, -128, -128, -128, -128, -128, 21, 21, 21, -128}, - 0 /* defaultActiveNetworkBoost */); - private static final ScoredNetwork GOOD_CAPTIVE_NETWORK; - static { - Bundle attributes = new Bundle(); - attributes.putBoolean(ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL, true); - GOOD_CAPTIVE_NETWORK = new ScoredNetwork( - new NetworkKey(new WifiKey("\"Captive\"", "ff:ee:dd:cc:bb:aa")), - GOOD_CAPTIVE_NETWORK_CURVE, false /* meteredHint */, attributes); - } - - private static final String ANY_NETWORK_STRING_UNQUOTED = "AnySsid"; - private static final String ANY_NETWORK_STRING = - "\"AnySsid\",00:00:00:00:00:00" - + "|18,-128,-128,-128,-128,-128,-128,22,22,22,-128|0|0|NONE"; - private static final RssiCurve ANY_NETWORK_CURVE = new RssiCurve( - DefaultNetworkRecommendationProvider.CONSTANT_CURVE_START, 18 /* bucketWidth */, - new byte[]{-128, -128, -128, -128, -128, -128, 22, 22, 22, -128}, - 0 /* defaultActiveNetworkBoost */); - private static final ScoredNetwork ANY_NETWORK = new ScoredNetwork( - new NetworkKey(new WifiKey("\"AnySsid\"", "ee:ee:ee:ee:ee:ee")), - ANY_NETWORK_CURVE, false /* meteredHint */, new Bundle()); - - private static final String ANY_NETWORK_SPECIFIC_STRING_UNQUOTED = "AnySsid"; - private static final String ANY_NETWORK_SPECIFIC_STRING = - "\"AnySsid\",ee:ee:ee:ee:ee:ee" - + "|18,-128,-128,-128,-128,-128,-128,23,23,23,-128|0|0|NONE"; - private static final RssiCurve ANY_NETWORK_SPECIFIC_CURVE = new RssiCurve( - DefaultNetworkRecommendationProvider.CONSTANT_CURVE_START, 18 /* bucketWidth */, - new byte[]{-128, -128, -128, -128, -128, -128, 23, 23, 23, -128}, - 0 /* defaultActiveNetworkBoost */); - private static final ScoredNetwork ANY_NETWORK_SPECIFIC = new ScoredNetwork( - new NetworkKey(new WifiKey("\"AnySsid\"", "ee:ee:ee:ee:ee:ee")), - ANY_NETWORK_SPECIFIC_CURVE, false /* meteredHint */, new Bundle()); - - private static final String BAD_NETWORK_STRING_UNQUOTED = "Bad"; - private static final String BAD_NETWORK_STRING = - "\"Bad\",aa:bb:cc:dd:ee:ff" - + "|10,-128,-128,-128,-128,-128,-128,-128,-128,-128,-128,-128,-128,-128" - + "|1|0|SD"; - private static final RssiCurve BAD_NETWORK_CURVE = - new RssiCurve( - DefaultNetworkRecommendationProvider.CONSTANT_CURVE_START, - 10 /* bucketWidth */, - new byte[] {-128, -128, -128, -128, -128, -128, - -128, -128, -128, -128, -128, -128, -128}, - 0 /* defaultActiveNetworkBoost */); - private static final ScoredNetwork BAD_NETWORK = - new ScoredNetwork( - new NetworkKey(new WifiKey("\"Bad\"", "aa:bb:cc:dd:ee:ff")), - BAD_NETWORK_CURVE, - true /* meteredHint */, - new Bundle()); - - @Mock - private NetworkRecommendationProvider.ResultCallback mCallback; - - @Mock - private NetworkScoreManager mNetworkScoreManager; - - @Mock - private Context mContext; - - private DefaultNetworkRecommendationProvider.ScoreStorage mStorage; - private DefaultNetworkRecommendationProvider mProvider; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - mStorage = new DefaultNetworkRecommendationProvider.ScoreStorage(); - final Handler handler = new Handler(Looper.getMainLooper()); - mProvider = new DefaultNetworkRecommendationProvider(mContext, - handler::post, mNetworkScoreManager, mStorage); - } - - @Test - public void basicRecommendation() throws Exception { - - ScanResult[] scanResults = new ScanResult[6]; - for (int i = 0; i < 3; i++) { - scanResults[i] = TestUtil.createMockScanResult(i); - } - - // For now we add directly to storage, but when we start calling - // networkScoreManager.updateScores, we'll have to adjust this test. - mProvider.addScoreForTest(GOOD_METERED_NETWORK); - { - ScanResult scanResult = new ScanResult(); - scanResult.level = 115; - scanResult.SSID = GOOD_METERED_NETWORK_STRING_UNQUOTED; - scanResult.wifiSsid = WifiSsid.createFromAsciiEncoded( - GOOD_METERED_NETWORK_STRING_UNQUOTED); - scanResult.BSSID = GOOD_METERED_NETWORK.networkKey.wifiKey.bssid; - scanResult.capabilities = "[ESS]"; - scanResult.timestamp = SystemClock.elapsedRealtime() * 1000; - scanResults[3] = scanResult; - } - - for (int i = 4; i < 6; i++) { - scanResults[i] = TestUtil.createMockScanResult(i); - } - - RecommendationRequest request = new RecommendationRequest.Builder() - .setScanResults(scanResults) - .build(); - - RecommendationResult result = verifyAndCaptureResult(request); - assertEquals(GOOD_METERED_NETWORK.networkKey.wifiKey.ssid, - result.getWifiConfiguration().SSID); - } - - @Test - public void recommendation_noScans_returnsCurrentConfig() throws Exception { - ScanResult[] scanResults = new ScanResult[0]; - - WifiConfiguration expectedConfig = new WifiConfiguration(); - expectedConfig.SSID = "ssid"; - expectedConfig.BSSID = "bssid"; - RecommendationRequest request = new RecommendationRequest.Builder() - .setScanResults(scanResults) - .setDefaultWifiConfig(expectedConfig) - .build(); - - RecommendationResult result = verifyAndCaptureResult(request); - assertEquals(expectedConfig, result.getWifiConfiguration()); - } - - @Test - public void recommendation_noScans_noCurrentConfig_returnsEmpty() throws Exception { - ScanResult[] scanResults = new ScanResult[0]; - - RecommendationRequest request = new RecommendationRequest.Builder() - .setScanResults(scanResults) - .build(); - - RecommendationResult result = verifyAndCaptureResult(request); - assertNull(result.getWifiConfiguration()); - } - - @Test - public void scoreNetworks() throws Exception { - NetworkKey[] keys = - new NetworkKey[]{GOOD_METERED_NETWORK.networkKey, GOOD_CAPTIVE_NETWORK.networkKey}; - mProvider.onRequestScores(keys); - - verify(mNetworkScoreManager).updateScores(Mockito.any()); - } - - @Test - public void scoreNetworks_empty() throws Exception { - NetworkKey[] keys = new NetworkKey[]{}; - mProvider.onRequestScores(keys); - - verify(mNetworkScoreManager, times(0)).updateScores(Mockito.any()); - } - - @Test - public void dumpAddScores_goodMetered() { - String[] args = {"netrec", "addScore", GOOD_METERED_NETWORK_STRING}; - mProvider.dump(null /* fd */, new PrintWriter(new StringWriter()), args); - - ScoredNetwork[] scoredNetworks = verifyAndCaptureScoredNetworks(); - assertEquals(1, scoredNetworks.length); - ScoredNetwork score = scoredNetworks[0]; - - assertEquals(GOOD_METERED_NETWORK.networkKey.wifiKey.ssid, score.networkKey.wifiKey.ssid); - assertEquals(GOOD_METERED_NETWORK.networkKey.wifiKey.bssid, score.networkKey.wifiKey.bssid); - - assertEquals(GOOD_METERED_NETWORK.meteredHint, score.meteredHint); - assertEquals( - GOOD_METERED_NETWORK.attributes.getBoolean( - ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL), - score.attributes.getBoolean(ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL)); - - assertEquals("Network curve does not match", GOOD_METERED_NETWORK_CURVE, score.rssiCurve); - assertEquals( - "Badge curve does not match", - DefaultNetworkRecommendationProvider.BADGE_CURVE_4K, - (RssiCurve) score.attributes.getParcelable( - ScoredNetwork.ATTRIBUTES_KEY_BADGING_CURVE)); - } - - @Test - public void dumpAddScores_bad() { - String[] args = {"netrec", "addScore", BAD_NETWORK_STRING}; - mProvider.dump(null /* fd */, new PrintWriter(new StringWriter()), args); - - ScoredNetwork[] scoredNetworks = verifyAndCaptureScoredNetworks(); - assertEquals(1, scoredNetworks.length); - ScoredNetwork score = scoredNetworks[0]; - - assertEquals(BAD_NETWORK.networkKey.wifiKey.ssid, score.networkKey.wifiKey.ssid); - assertEquals(BAD_NETWORK.networkKey.wifiKey.bssid, score.networkKey.wifiKey.bssid); - - assertEquals(BAD_NETWORK.meteredHint, score.meteredHint); - assertEquals( - BAD_NETWORK.attributes.getBoolean(ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL), - score.attributes.getBoolean(ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL)); - - assertEquals("Network curve does not match", BAD_NETWORK_CURVE, score.rssiCurve); - assertEquals( - "Badge curve does not match", - DefaultNetworkRecommendationProvider.BADGE_CURVE_SD, - (RssiCurve) score.attributes.getParcelable( - ScoredNetwork.ATTRIBUTES_KEY_BADGING_CURVE)); - } - - @Test - public void dumpAddScores_goodCaptivePortal() { - String[] args = {"addScore", GOOD_CAPTIVE_NETWORK_STRING}; - mProvider.dump(null /* fd */, new PrintWriter(new StringWriter()), args); - - ScoredNetwork[] scoredNetworks = verifyAndCaptureScoredNetworks(); - assertEquals(1, scoredNetworks.length); - ScoredNetwork score = scoredNetworks[0]; - - assertEquals(GOOD_CAPTIVE_NETWORK.networkKey.wifiKey.ssid, score.networkKey.wifiKey.ssid); - assertEquals(GOOD_CAPTIVE_NETWORK.networkKey.wifiKey.bssid, score.networkKey.wifiKey.bssid); - - assertEquals(GOOD_CAPTIVE_NETWORK.meteredHint, score.meteredHint); - - assertEquals( - GOOD_CAPTIVE_NETWORK.attributes.getBoolean( - ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL), - score.attributes.getBoolean(ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL)); - assertEquals("Network curve does not match.", GOOD_CAPTIVE_NETWORK_CURVE, score.rssiCurve); - assertEquals( - "Badge curve does not match", - DefaultNetworkRecommendationProvider.BADGE_CURVE_HD, - (RssiCurve) score.attributes.getParcelable( - ScoredNetwork.ATTRIBUTES_KEY_BADGING_CURVE)); - } - - @Test - public void dumpAddScores_anySsid() { - String[] args = {"addScore", ANY_NETWORK_STRING}; - mProvider.dump(null /* fd */, new PrintWriter(new StringWriter()), args); - - // We don't update the platform with the any bssid score, but we do store it. - verify(mNetworkScoreManager, times(0)).updateScores(Mockito.any()); - - // We do store and serve the score, though: - ScoredNetwork score = mStorage.get(ANY_NETWORK.networkKey); - assertNotNull(score); - - assertEquals(ANY_NETWORK.networkKey, score.networkKey); - assertEquals(ANY_NETWORK.meteredHint, score.meteredHint); - assertEquals( - ANY_NETWORK.attributes.getBoolean( - ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL), - score.attributes.getBoolean(ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL)); - assertEquals("Network curve does not match", ANY_NETWORK_CURVE, score.rssiCurve); - assertNull( - "Badge curve should not be set.", - (RssiCurve) score.attributes.getParcelable( - ScoredNetwork.ATTRIBUTES_KEY_BADGING_CURVE)); - } - - @Test - public void dumpAddScores_anySsid_useMoreSpecific() { - mProvider.dump(null /* fd */, new PrintWriter(new StringWriter()), - new String[] {"addScore", ANY_NETWORK_STRING}); - verify(mNetworkScoreManager, times(0)).updateScores(Mockito.any()); - - mProvider.dump(null /* fd */, new PrintWriter(new StringWriter()), - new String[] {"addScore", ANY_NETWORK_SPECIFIC_STRING}); - verify(mNetworkScoreManager).updateScores(Mockito.any()); - - // We don't update the platform with the any bssid score, but we do store it. - ScoredNetwork score = mStorage.get(ANY_NETWORK.networkKey); - assertNotNull(score); - - assertEquals(ANY_NETWORK_SPECIFIC.networkKey, score.networkKey); - assertEquals(ANY_NETWORK_SPECIFIC.meteredHint, score.meteredHint); - assertEquals( - ANY_NETWORK_SPECIFIC.attributes.getBoolean( - ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL), - score.attributes.getBoolean(ScoredNetwork.ATTRIBUTES_KEY_HAS_CAPTIVE_PORTAL)); - assertEquals("Network curve does not match", ANY_NETWORK_SPECIFIC_CURVE, score.rssiCurve); - assertNull( - "Badge curve should not be set.", - (RssiCurve) score.attributes.getParcelable( - ScoredNetwork.ATTRIBUTES_KEY_BADGING_CURVE)); - - } - - private RecommendationResult verifyAndCaptureResult( - RecommendationRequest request) { - mProvider.onRequestRecommendation(request, mCallback); - - ArgumentCaptor<RecommendationResult> resultCaptor = - ArgumentCaptor.forClass(RecommendationResult.class); - verify(mCallback).onResult(resultCaptor.capture()); - - return resultCaptor.getValue(); - } - - private ScoredNetwork[] verifyAndCaptureScoredNetworks() { - ArgumentCaptor<ScoredNetwork[]> resultCaptor = ArgumentCaptor.forClass( - ScoredNetwork[].class); - verify(mNetworkScoreManager).updateScores(resultCaptor.capture()); - return resultCaptor.getValue(); - } -} diff --git a/tests/src/com/android/networkrecommendation/NetworkRecommendationServiceTest.java b/tests/src/com/android/networkrecommendation/NetworkRecommendationServiceTest.java deleted file mode 100644 index 644cb93..0000000 --- a/tests/src/com/android/networkrecommendation/NetworkRecommendationServiceTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2016 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.networkrecommendation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import android.content.Intent; -import android.net.INetworkRecommendationProvider; -import android.net.NetworkKey; -import android.net.NetworkRecommendationProvider; -import android.net.NetworkScoreManager; -import android.net.RecommendationRequest; -import android.net.RecommendationResult; -import android.net.WifiKey; -import android.net.wifi.ScanResult; -import android.os.Bundle; -import android.os.IBinder; -import android.os.IRemoteCallback; -import android.os.RemoteException; -import android.os.SystemClock; -import android.support.test.InstrumentationRegistry; -import android.support.test.rule.ServiceTestRule; -import android.support.test.runner.AndroidJUnit4; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.android.networkrecommendation.config.PreferenceFile; - -@RunWith(AndroidJUnit4.class) -public class NetworkRecommendationServiceTest { - - private static final int RESULT_LATCH_TIMEOUT_MILLIS = 2000; - private static final int WAIT_FOR_BIND_TIMEOUT_MILLIS = 2000; - private static final int SEQUENCE_ID = 11; - - @Rule - public final ServiceTestRule serviceRule = new ServiceTestRule(); - - private INetworkRecommendationProvider bind() throws TimeoutException { - PreferenceFile.init(InstrumentationRegistry.getTargetContext()); - Intent bindIntent = new Intent(InstrumentationRegistry.getTargetContext(), - NetworkRecommendationService.class); - bindIntent.setAction(NetworkScoreManager.ACTION_RECOMMEND_NETWORKS); - - // https://code.google.com/p/android/issues/detail?id=200071 - // bindService can occasionally returns null. - IBinder binder = null; - boolean interrupted = false; - try { - long startTime = SystemClock.elapsedRealtime(); - long currentTime = startTime; - while (currentTime < startTime + WAIT_FOR_BIND_TIMEOUT_MILLIS) { - binder = serviceRule.bindService(bindIntent); - if (binder != null) { - return INetworkRecommendationProvider.Stub.asInterface(binder); - } - try { - Thread.sleep(100); - } catch (InterruptedException e) { - interrupted = true; - currentTime = SystemClock.elapsedRealtime(); - } - } - throw new TimeoutException("Unable to bind to service."); - } finally { - if (interrupted) { - Thread.currentThread().interrupt(); - } - } - } - - /** - * Assert that when we make a request we get a response with the proper sequence. - * <p /> - * We do not assert the config given to us, because we're simply verifying the behavior of - * this service interacting with the provider. For recommendation tests, see - * {@link DefaultNetworkRecommendationProviderTest}. - */ - @Test - public void requestRecommendation() throws Exception { - INetworkRecommendationProvider service = bind(); - - ScanResult[] scanResults = new ScanResult[5]; - for (int i = 0; i < 5; i++) { - scanResults[i] = TestUtil.createMockScanResult(i); - } - - RecommendationRequest request = new RecommendationRequest.Builder() - .setScanResults(scanResults) - .build(); - - Result result = requestRecommendation(service, request, SEQUENCE_ID); - synchronized (result) { - assertEquals(result.sequence, SEQUENCE_ID); - } - } - - @Test - public void scoreNetworks() throws Exception { - INetworkRecommendationProvider service = bind(); - service.requestScores(new NetworkKey[]{new NetworkKey(new WifiKey("\"ProperlyQuoted\"", - "aa:bb:cc:dd:ee:ff"))}); - } - - @Test - public void scoreNetworks_empty() throws Exception { - INetworkRecommendationProvider service = bind(); - service.requestScores(new NetworkKey[]{}); - } - - @Test - public void scoreNetworks_invalid() throws Exception { - INetworkRecommendationProvider service = bind(); - try { - service.requestScores(new NetworkKey[]{ - new NetworkKey(new WifiKey("ImproperlyQuoted", "aa:bb:cc:dd:ee:ff"))}); - fail("An invalid SSID should throw an exception."); - } catch (IllegalArgumentException e) { - // Expected. - } - } - - /** - * Make a network recommendation request. Be sure to synchronize on the result to access its - * values properly. - */ - private Result requestRecommendation(INetworkRecommendationProvider service, - RecommendationRequest request, int seqId) throws RemoteException, InterruptedException { - final Result result = new Result(); - final CountDownLatch latch = new CountDownLatch(1); - IRemoteCallback callback = new IRemoteCallback.Stub() { - @Override - public void sendResult(Bundle data) throws RemoteException { - synchronized (result) { - result.sequence = data.getInt(NetworkRecommendationProvider.EXTRA_SEQUENCE); - result.recommendation = data.getParcelable( - NetworkRecommendationProvider.EXTRA_RECOMMENDATION_RESULT); - latch.countDown(); - } - } - }; - - service.requestRecommendation(request, callback, seqId); - latch.await(RESULT_LATCH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); - return result; - } - - private static class Result { - public int sequence; - public RecommendationResult recommendation; - } -} diff --git a/tests/src/com/android/networkrecommendation/TestUtil.java b/tests/src/com/android/networkrecommendation/TestUtil.java deleted file mode 100644 index 77d7aa7..0000000 --- a/tests/src/com/android/networkrecommendation/TestUtil.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2016 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.networkrecommendation; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.net.NetworkInfo; -import android.net.wifi.ScanResult; -import android.net.wifi.WifiManager; -import android.net.wifi.WifiSsid; -import android.os.SystemClock; - -/** - * Utils for wifi tests. - */ -public class TestUtil { - - /** Create a scan result with some basic properties. */ - public static ScanResult createMockScanResult(int i) { - ScanResult scanResult = new ScanResult(); - scanResult.level = i; - scanResult.SSID = "ssid-" + i; - scanResult.wifiSsid = WifiSsid.createFromAsciiEncoded("ssid-" + i); - scanResult.BSSID = "aa:bb:cc:dd:ee:0" + i; - scanResult.capabilities = "[ESS]"; - scanResult.timestamp = SystemClock.elapsedRealtime() * 1000; - return scanResult; - } - - /** Send {@link WifiManager#NETWORK_STATE_CHANGED_ACTION} broadcast. */ - public static void sendNetworkStateChanged(BroadcastReceiver broadcastReceiver, - Context context, NetworkInfo.DetailedState detailedState) { - Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION); - NetworkInfo networkInfo = new NetworkInfo(0, 0, "", ""); - networkInfo.setDetailedState(detailedState, "", ""); - intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, networkInfo); - broadcastReceiver.onReceive(context, intent); - } - - /** Send {@link WifiManager#WIFI_AP_STATE_CHANGED_ACTION} broadcast. */ - public static void sendWifiApStateChanged(BroadcastReceiver broadcastReceiver, - Context context) { - Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); - broadcastReceiver.onReceive(context, intent); - } - - /** Send {@link WifiManager#SCAN_RESULTS_AVAILABLE_ACTION} broadcast. */ - public static void sendScanResultsAvailable(BroadcastReceiver broadcastReceiver, - Context context) { - Intent intent = new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); - broadcastReceiver.onReceive(context, intent); - } - - /** Send {@link WifiManager#CONFIGURED_NETWORKS_CHANGED_ACTION} broadcast. */ - public static void sendConfiguredNetworksChanged(BroadcastReceiver broadcastReceiver, - Context context) { - Intent intent = new Intent(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); - broadcastReceiver.onReceive(context, intent); - } - - /** Send {@link WifiManager#WIFI_STATE_CHANGED_ACTION} broadcast. */ - public static void sendWifiStateChanged(BroadcastReceiver broadcastReceiver, Context context) { - Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION); - broadcastReceiver.onReceive(context, intent); - } -} |