1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server.wifi.p2p; 18 19 import static android.net.NetworkInfo.DetailedState.FAILED; 20 import static android.net.NetworkInfo.DetailedState.IDLE; 21 import static android.net.wifi.WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE; 22 23 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession; 24 import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_P2P_DEVICE_NAME; 25 import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_P2P_PENDING_FACTORY_RESET; 26 import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_VERBOSE_LOGGING_ENABLED; 27 28 import static org.junit.Assert.assertEquals; 29 import static org.junit.Assert.assertNotEquals; 30 import static org.junit.Assert.assertNotNull; 31 import static org.junit.Assert.assertNull; 32 import static org.junit.Assert.assertThrows; 33 import static org.junit.Assert.assertTrue; 34 import static org.junit.Assume.assumeFalse; 35 import static org.junit.Assume.assumeTrue; 36 import static org.mockito.ArgumentMatchers.argThat; 37 import static org.mockito.Matchers.any; 38 import static org.mockito.Matchers.anyBoolean; 39 import static org.mockito.Matchers.anyInt; 40 import static org.mockito.Matchers.anyLong; 41 import static org.mockito.Matchers.anyString; 42 import static org.mockito.Matchers.eq; 43 import static org.mockito.Matchers.isNull; 44 import static org.mockito.Mockito.atLeastOnce; 45 import static org.mockito.Mockito.doAnswer; 46 import static org.mockito.Mockito.doNothing; 47 import static org.mockito.Mockito.doThrow; 48 import static org.mockito.Mockito.inOrder; 49 import static org.mockito.Mockito.lenient; 50 import static org.mockito.Mockito.mock; 51 import static org.mockito.Mockito.never; 52 import static org.mockito.Mockito.reset; 53 import static org.mockito.Mockito.spy; 54 import static org.mockito.Mockito.times; 55 import static org.mockito.Mockito.verify; 56 import static org.mockito.Mockito.when; 57 58 import android.annotation.Nullable; 59 import android.app.AlarmManager; 60 import android.app.AlertDialog; 61 import android.app.BroadcastOptions; 62 import android.app.test.MockAnswerUtil; 63 import android.app.test.MockAnswerUtil.AnswerWithArguments; 64 import android.content.AttributionSource; 65 import android.content.BroadcastReceiver; 66 import android.content.Context; 67 import android.content.DialogInterface; 68 import android.content.Intent; 69 import android.content.IntentFilter; 70 import android.content.pm.PackageManager; 71 import android.content.res.Configuration; 72 import android.content.res.Resources; 73 import android.location.LocationManager; 74 import android.net.ConnectivityManager; 75 import android.net.InetAddresses; 76 import android.net.MacAddress; 77 import android.net.NetworkInfo; 78 import android.net.TetheringManager; 79 import android.net.wifi.CoexUnsafeChannel; 80 import android.net.wifi.ScanResult; 81 import android.net.wifi.WifiConfiguration; 82 import android.net.wifi.WifiInfo; 83 import android.net.wifi.WifiManager; 84 import android.net.wifi.WifiScanner; 85 import android.net.wifi.WpsInfo; 86 import android.net.wifi.p2p.WifiP2pConfig; 87 import android.net.wifi.p2p.WifiP2pDevice; 88 import android.net.wifi.p2p.WifiP2pDeviceList; 89 import android.net.wifi.p2p.WifiP2pGroup; 90 import android.net.wifi.p2p.WifiP2pGroupList; 91 import android.net.wifi.p2p.WifiP2pInfo; 92 import android.net.wifi.p2p.WifiP2pManager; 93 import android.net.wifi.p2p.WifiP2pProvDiscEvent; 94 import android.net.wifi.p2p.WifiP2pWfdInfo; 95 import android.net.wifi.p2p.nsd.WifiP2pServiceInfo; 96 import android.net.wifi.p2p.nsd.WifiP2pServiceRequest; 97 import android.os.Binder; 98 import android.os.Build; 99 import android.os.Bundle; 100 import android.os.Handler; 101 import android.os.HandlerThread; 102 import android.os.Message; 103 import android.os.Messenger; 104 import android.os.Process; 105 import android.os.UserHandle; 106 import android.os.UserManager; 107 import android.os.WorkSource; 108 import android.os.test.TestLooper; 109 import android.provider.Settings; 110 import android.view.Display; 111 import android.view.LayoutInflater; 112 import android.view.View; 113 import android.view.ViewGroup; 114 import android.view.Window; 115 import android.widget.TextView; 116 117 import androidx.test.filters.SmallTest; 118 119 import com.android.internal.util.AsyncChannel; 120 import com.android.internal.util.State; 121 import com.android.internal.util.StateMachine; 122 import com.android.modules.utils.build.SdkLevel; 123 import com.android.server.wifi.Clock; 124 import com.android.server.wifi.FakeWifiLog; 125 import com.android.server.wifi.FrameworkFacade; 126 import com.android.server.wifi.HalDeviceManager; 127 import com.android.server.wifi.InterfaceConflictManager; 128 import com.android.server.wifi.WifiBaseTest; 129 import com.android.server.wifi.WifiDialogManager; 130 import com.android.server.wifi.WifiGlobals; 131 import com.android.server.wifi.WifiInjector; 132 import com.android.server.wifi.WifiSettingsConfigStore; 133 import com.android.server.wifi.coex.CoexManager; 134 import com.android.server.wifi.proto.nano.WifiMetricsProto; 135 import com.android.server.wifi.proto.nano.WifiMetricsProto.P2pConnectionEvent; 136 import com.android.server.wifi.util.NetdWrapper; 137 import com.android.server.wifi.util.StringUtil; 138 import com.android.server.wifi.util.WaitingState; 139 import com.android.server.wifi.util.WifiPermissionsUtil; 140 import com.android.server.wifi.util.WifiPermissionsWrapper; 141 import com.android.wifi.resources.R; 142 143 import org.junit.After; 144 import org.junit.Before; 145 import org.junit.Test; 146 import org.mockito.ArgumentCaptor; 147 import org.mockito.ArgumentMatcher; 148 import org.mockito.InOrder; 149 import org.mockito.Mock; 150 import org.mockito.MockitoAnnotations; 151 import org.mockito.MockitoSession; 152 import org.mockito.Spy; 153 154 import java.net.InetAddress; 155 import java.net.NetworkInterface; 156 import java.util.ArrayList; 157 import java.util.Arrays; 158 import java.util.Collections; 159 import java.util.HashSet; 160 import java.util.List; 161 162 /** 163 * Unit test harness for WifiP2pServiceImpl. 164 */ 165 @SmallTest 166 public class WifiP2pServiceImplTest extends WifiBaseTest { 167 private static final String TAG = "WifiP2pServiceImplTest"; 168 private static final String IFACE_NAME_P2P = "mockP2p0"; 169 private static final String P2P_GO_IP = "192.168.49.1"; 170 private static final long STATE_CHANGE_WAITING_TIME = 1000; 171 private static final String thisDeviceMac = "11:22:33:44:55:66"; 172 private static final String thisDeviceName = "thisDeviceName"; 173 private static final String ANONYMIZED_DEVICE_ADDRESS = "02:00:00:00:00:00"; 174 private static final String TEST_PACKAGE_NAME = "com.p2p.test"; 175 private static final String TEST_ANDROID_ID = "314Deadbeef"; 176 private static final String[] TEST_REQUIRED_PERMISSIONS_T = 177 new String[] { 178 android.Manifest.permission.NEARBY_WIFI_DEVICES, 179 android.Manifest.permission.ACCESS_WIFI_STATE 180 }; 181 private static final String[] TEST_EXCLUDED_PERMISSIONS_T = 182 new String[] { 183 android.Manifest.permission.ACCESS_FINE_LOCATION 184 }; 185 private static final int TEST_GROUP_FREQUENCY = 5180; 186 private static final int P2P_INVITATION_RECEIVED_TIMEOUT_MS = 5180; 187 188 private ArgumentCaptor<BroadcastReceiver> mBcastRxCaptor = ArgumentCaptor.forClass( 189 BroadcastReceiver.class); 190 private ArgumentCaptor<WorkSource> mWsCaptor = ArgumentCaptor.forClass(WorkSource.class); 191 private Binder mClient1; 192 private Binder mClient2; 193 194 private BroadcastReceiver mLocationModeReceiver; 195 private BroadcastReceiver mWifiStateChangedReceiver; 196 private BroadcastReceiver mTetherStateReceiver; 197 private BroadcastReceiver mUserRestrictionReceiver; 198 private Handler mClientHandler; 199 private Messenger mP2pStateMachineMessenger; 200 private Messenger mClientMessenger; 201 private WifiP2pServiceImpl mWifiP2pServiceImpl; 202 private TestLooper mClientHanderLooper; 203 private TestLooper mLooper; 204 private MacAddress mTestWifiP2pPeerAddress; 205 private WifiP2pConfig mTestWifiP2pPeerConfig; 206 private WifiP2pConfig mTestWifiP2pFastConnectionConfig; 207 private WifiP2pGroup mTestWifiP2pNewPersistentGoGroup; 208 private WifiP2pGroup mTestWifiP2pGroup; 209 private WifiP2pDevice mTestWifiP2pDevice; 210 private WifiP2pGroupList mGroups = new WifiP2pGroupList(null, null); 211 private WifiP2pDevice mTestThisDevice; 212 private ArgumentCaptor<Message> mMessageCaptor = ArgumentCaptor.forClass(Message.class); 213 private MockitoSession mStaticMockSession = null; 214 private Bundle mAttribution = new Bundle(); 215 216 @Mock Bundle mBundle; 217 @Mock Context mContext; 218 @Mock FrameworkFacade mFrameworkFacade; 219 @Mock HandlerThread mHandlerThread; 220 @Mock NetdWrapper mNetdWrapper; 221 @Mock PackageManager mPackageManager; 222 @Mock Resources mResources; 223 @Mock Configuration mConfiguration; 224 @Mock NetworkInterface mP2pNetworkInterface; 225 @Mock WifiInjector mWifiInjector; 226 @Mock BroadcastOptions mBroadcastOptions; 227 @Mock WifiManager mMockWifiManager; 228 @Mock WifiPermissionsUtil mWifiPermissionsUtil; 229 @Mock WifiSettingsConfigStore mWifiSettingsConfigStore; 230 @Mock WifiPermissionsWrapper mWifiPermissionsWrapper; 231 @Mock WifiP2pNative mWifiNative; 232 @Mock WifiP2pServiceInfo mTestWifiP2pServiceInfo; 233 @Mock WifiP2pServiceRequest mTestWifiP2pServiceRequest; 234 @Mock UserManager mUserManager; 235 @Mock WifiP2pMetrics mWifiP2pMetrics; 236 @Mock WifiManager mWifiManager; 237 @Mock WifiInfo mWifiInfo; 238 @Mock CoexManager mCoexManager; 239 @Spy FakeWifiLog mLog; 240 @Spy MockWifiP2pMonitor mWifiMonitor; 241 @Mock WifiGlobals mWifiGlobals; 242 @Mock AlarmManager mAlarmManager; 243 @Mock WifiDialogManager mWifiDialogManager; 244 @Mock WifiDialogManager.DialogHandle mDialogHandle; 245 @Mock InterfaceConflictManager mInterfaceConflictManager; 246 @Mock Clock mClock; 247 @Mock LayoutInflater mLayoutInflater; 248 @Mock View mView; 249 @Mock AlertDialog.Builder mAlertDialogBuilder; 250 @Mock AlertDialog mAlertDialog; 251 @Mock AsyncChannel mAsyncChannel; 252 CoexManager.CoexListener mCoexListener; 253 generatorTestData()254 private void generatorTestData() { 255 mTestWifiP2pGroup = new WifiP2pGroup(); 256 mTestWifiP2pGroup.setNetworkName("TestGroupName"); 257 mTestWifiP2pDevice = spy(new WifiP2pDevice()); 258 mTestWifiP2pDevice.deviceName = "TestDeviceName"; 259 mTestWifiP2pDevice.deviceAddress = "aa:bb:cc:dd:ee:ff"; 260 261 mTestWifiP2pPeerAddress = MacAddress.fromString(mTestWifiP2pDevice.deviceAddress); 262 263 // for general connect command 264 mTestWifiP2pPeerConfig = new WifiP2pConfig(); 265 mTestWifiP2pPeerConfig.deviceAddress = mTestWifiP2pDevice.deviceAddress; 266 267 // for fast-connection connect command 268 mTestWifiP2pFastConnectionConfig = new WifiP2pConfig.Builder() 269 .setNetworkName("DIRECT-XY-HELLO") 270 .setPassphrase("DEADBEEF") 271 .build(); 272 273 // for general group started event 274 mTestWifiP2pNewPersistentGoGroup = new WifiP2pGroup(); 275 mTestWifiP2pNewPersistentGoGroup.setNetworkId(WifiP2pGroup.NETWORK_ID_PERSISTENT); 276 mTestWifiP2pNewPersistentGoGroup.setNetworkName("DIRECT-xy-NEW"); 277 mTestWifiP2pNewPersistentGoGroup.setOwner(new WifiP2pDevice(thisDeviceMac)); 278 mTestWifiP2pNewPersistentGoGroup.setIsGroupOwner(true); 279 mTestWifiP2pNewPersistentGoGroup.setInterface(IFACE_NAME_P2P); 280 281 mGroups.clear(); 282 WifiP2pGroup group1 = new WifiP2pGroup(); 283 group1.setNetworkId(0); 284 group1.setNetworkName(mTestWifiP2pGroup.getNetworkName()); 285 group1.setOwner(mTestWifiP2pDevice); 286 group1.setIsGroupOwner(false); 287 mGroups.add(group1); 288 289 WifiP2pGroup group2 = new WifiP2pGroup(); 290 group2.setNetworkId(1); 291 group2.setNetworkName("DIRECT-ab-Hello"); 292 group2.setOwner(new WifiP2pDevice("12:34:56:78:90:ab")); 293 group2.setIsGroupOwner(false); 294 mGroups.add(group2); 295 296 WifiP2pGroup group3 = new WifiP2pGroup(); 297 group3.setNetworkId(2); 298 group3.setNetworkName("DIRECT-cd-OWNER"); 299 group3.setOwner(new WifiP2pDevice(thisDeviceMac)); 300 group3.setIsGroupOwner(true); 301 mGroups.add(group3); 302 303 mTestThisDevice = new WifiP2pDevice(); 304 mTestThisDevice.deviceName = thisDeviceName; 305 mTestThisDevice.deviceAddress = thisDeviceMac; 306 mTestThisDevice.primaryDeviceType = "10-0050F204-5"; 307 } 308 309 /** 310 * Simulate Location Mode change: Changes the location manager return values and dispatches a 311 * broadcast. 312 * 313 * @param isLocationModeEnabled whether the location mode is enabled., 314 */ simulateLocationModeChange(boolean isLocationModeEnabled)315 private void simulateLocationModeChange(boolean isLocationModeEnabled) { 316 when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(isLocationModeEnabled); 317 318 Intent intent = new Intent(LocationManager.MODE_CHANGED_ACTION); 319 mLocationModeReceiver.onReceive(mContext, intent); 320 } 321 322 /** 323 * Simulate Wi-Fi state change: broadcast state change and modify the API return value. 324 * 325 * @param isWifiOn whether the wifi mode is enabled. 326 */ simulateWifiStateChange(boolean isWifiOn)327 private void simulateWifiStateChange(boolean isWifiOn) { 328 when(mMockWifiManager.getWifiState()).thenReturn( 329 isWifiOn ? WifiManager.WIFI_STATE_ENABLED : WifiManager.WIFI_STATE_DISABLED); 330 331 Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION); 332 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, 333 isWifiOn ? WifiManager.WIFI_STATE_ENABLED : WifiManager.WIFI_STATE_DISABLED); 334 mWifiStateChangedReceiver.onReceive(mContext, intent); 335 } 336 337 /** 338 * Simulate tethering flow is completed 339 */ simulateTetherReady()340 private void simulateTetherReady() { 341 ArrayList<String> availableList = new ArrayList<>(); 342 ArrayList<String> localOnlyList = new ArrayList<>(); 343 localOnlyList.add(IFACE_NAME_P2P); 344 ArrayList<String> tetherList = new ArrayList<>(); 345 ArrayList<String> erroredList = new ArrayList<>(); 346 347 Intent intent = new Intent(TetheringManager.ACTION_TETHER_STATE_CHANGED); 348 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 349 intent.putStringArrayListExtra(TetheringManager.EXTRA_AVAILABLE_TETHER, availableList); 350 intent.putStringArrayListExtra(TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY, localOnlyList); 351 intent.putStringArrayListExtra(TetheringManager.EXTRA_ACTIVE_TETHER, tetherList); 352 intent.putStringArrayListExtra(TetheringManager.EXTRA_ERRORED_TETHER, erroredList); 353 mTetherStateReceiver.onReceive(mContext, intent); 354 mLooper.dispatchAll(); 355 } 356 357 /** 358 * Mock send WifiP2pManager.UPDATE_CHANNEL_INFO 359 * 360 * @param pkgName package name used for p2p channel init 361 * @param featureId The feature in the package 362 * @param binder client binder used for p2p channel init 363 * @param replyMessenger for checking replied message. 364 */ sendChannelInfoUpdateMsg(String pkgName, @Nullable String featureId, Binder binder, Messenger replyMessenger)365 private void sendChannelInfoUpdateMsg(String pkgName, @Nullable String featureId, 366 Binder binder, Messenger replyMessenger) throws Exception { 367 Message msg = Message.obtain(); 368 msg.what = WifiP2pManager.UPDATE_CHANNEL_INFO; 369 Bundle bundle = new Bundle(); 370 bundle.putString(WifiP2pManager.CALLING_PACKAGE, pkgName); 371 bundle.putString(WifiP2pManager.CALLING_FEATURE_ID, featureId); 372 bundle.putBinder(WifiP2pManager.CALLING_BINDER, binder); 373 if (SdkLevel.isAtLeastS()) { 374 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 375 } 376 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, bundle); 377 msg.replyTo = replyMessenger; 378 mP2pStateMachineMessenger.send(Message.obtain(msg)); 379 mLooper.dispatchAll(); 380 } 381 382 /** 383 * Mock send WifiP2pManager.ADD_LOCAL_SERVICE with mTestWifiP2pServiceInfo 384 * 385 * @param replyMessenger for checking replied message. 386 */ sendAddLocalServiceMsg(Messenger replyMessenger)387 private void sendAddLocalServiceMsg(Messenger replyMessenger) throws Exception { 388 Message msg = Message.obtain(); 389 Bundle extras = new Bundle(); 390 extras.putParcelable(WifiP2pManager.EXTRA_PARAM_KEY_SERVICE_INFO, mTestWifiP2pServiceInfo); 391 msg.what = WifiP2pManager.ADD_LOCAL_SERVICE; 392 if (SdkLevel.isAtLeastS()) { 393 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 394 } 395 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 396 msg.replyTo = replyMessenger; 397 mP2pStateMachineMessenger.send(Message.obtain(msg)); 398 mLooper.dispatchAll(); 399 } 400 401 /** 402 * Mock send WifiP2pManager.CONNECT with ConfigValidAsGroup 403 * 404 * @param replyMessenger for checking replied message. 405 */ sendConnectMsgWithConfigValidAsGroup(Messenger replyMessenger)406 private void sendConnectMsgWithConfigValidAsGroup(Messenger replyMessenger) throws Exception { 407 sendConnectMsg(replyMessenger, mTestWifiP2pFastConnectionConfig); 408 } 409 410 /** 411 * Mock send WifiP2pManager.CREATE_GROUP with ConfigValidAsGroup 412 * 413 * @param replyMessenger for checking replied message. 414 */ sendCreateGroupMsgWithConfigValidAsGroup(Messenger replyMessenger)415 private void sendCreateGroupMsgWithConfigValidAsGroup(Messenger replyMessenger) 416 throws Exception { 417 sendCreateGroupMsg(replyMessenger, 0, mTestWifiP2pFastConnectionConfig); 418 } 419 420 /** 421 * Mock send WifiP2pManager.DISCOVER_PEERS 422 * 423 * @param replyMessenger for checking replied message. 424 */ sendDiscoverPeersMsg(Messenger replyMessenger)425 private void sendDiscoverPeersMsg(Messenger replyMessenger) throws Exception { 426 sendDiscoverPeersMsg( 427 replyMessenger, WifiP2pManager.WIFI_P2P_SCAN_FULL, 428 WifiP2pManager.WIFI_P2P_SCAN_FREQ_UNSPECIFIED); 429 } 430 431 /** 432 * Mock send WifiP2pManager.DISCOVER_PEERS 433 * 434 * @param replyMessenger for checking replied message. 435 * @param type indicates what channels to scan. 436 * @param frequencyMhz is the frequency to be scanned. 437 */ sendDiscoverPeersMsg( Messenger replyMessenger, @WifiP2pManager.WifiP2pScanType int type, int frequencyMhz)438 private void sendDiscoverPeersMsg( 439 Messenger replyMessenger, @WifiP2pManager.WifiP2pScanType int type, 440 int frequencyMhz) throws Exception { 441 Message msg = Message.obtain(); 442 Bundle extras = new Bundle(); 443 extras.putInt(WifiP2pManager.EXTRA_PARAM_KEY_PEER_DISCOVERY_FREQ, frequencyMhz); 444 msg.what = WifiP2pManager.DISCOVER_PEERS; 445 msg.arg1 = type; 446 if (SdkLevel.isAtLeastS()) { 447 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 448 } 449 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 450 msg.replyTo = replyMessenger; 451 mP2pStateMachineMessenger.send(Message.obtain(msg)); 452 mLooper.dispatchAll(); 453 } 454 455 /** 456 * Mock send WifiP2pManager.ADD_SERVICE_REQUEST with mocked mTestWifiP2pServiceRequest 457 * 458 * @param replyMessenger for checking replied message. 459 */ sendAddServiceRequestMsg(Messenger replyMessenger)460 private void sendAddServiceRequestMsg(Messenger replyMessenger) throws Exception { 461 Message msg = Message.obtain(); 462 msg.what = WifiP2pManager.ADD_SERVICE_REQUEST; 463 msg.replyTo = replyMessenger; 464 msg.obj = mTestWifiP2pServiceRequest; 465 mP2pStateMachineMessenger.send(Message.obtain(msg)); 466 mLooper.dispatchAll(); 467 } 468 469 /** 470 * Mock send WifiP2pManager.DISCOVER_SERVICES 471 * 472 * @param replyMessenger for checking replied message. 473 */ sendDiscoverServiceMsg(Messenger replyMessenger)474 private void sendDiscoverServiceMsg(Messenger replyMessenger) throws Exception { 475 Message msg = Message.obtain(); 476 Bundle extras = new Bundle(); 477 msg.what = WifiP2pManager.DISCOVER_SERVICES; 478 if (SdkLevel.isAtLeastS()) { 479 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 480 } 481 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 482 msg.replyTo = replyMessenger; 483 mP2pStateMachineMessenger.send(Message.obtain(msg)); 484 mLooper.dispatchAll(); 485 } 486 487 /** 488 * Mock send WifiP2pManager.REQUEST_PEERS 489 * 490 * @param replyMessenger for checking replied message. 491 */ sendRequestPeersMsg(Messenger replyMessenger)492 private void sendRequestPeersMsg(Messenger replyMessenger) throws Exception { 493 Message msg = Message.obtain(); 494 Bundle extras = new Bundle(); 495 msg.what = WifiP2pManager.REQUEST_PEERS; 496 if (SdkLevel.isAtLeastS()) { 497 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 498 } 499 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 500 msg.replyTo = replyMessenger; 501 mP2pStateMachineMessenger.send(Message.obtain(msg)); 502 mLooper.dispatchAll(); 503 } 504 sendNegotiationRequestEvent(WifiP2pConfig config)505 private void sendNegotiationRequestEvent(WifiP2pConfig config) throws Exception { 506 Message msg = Message.obtain(); 507 msg.what = WifiP2pMonitor.P2P_GO_NEGOTIATION_REQUEST_EVENT; 508 msg.obj = config; 509 mP2pStateMachineMessenger.send(Message.obtain(msg)); 510 mLooper.dispatchAll(); 511 } 512 513 /** 514 * Mock send WifiP2pManager.REQUEST_GROUP_INFO 515 * 516 * @param replyMessenger for checking replied message. 517 */ sendRequestGroupInfoMsg(Messenger replyMessenger)518 private void sendRequestGroupInfoMsg(Messenger replyMessenger) throws Exception { 519 Message msg = Message.obtain(); 520 Bundle extras = new Bundle(); 521 msg.what = WifiP2pManager.REQUEST_GROUP_INFO; 522 if (SdkLevel.isAtLeastS()) { 523 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 524 } 525 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 526 msg.replyTo = replyMessenger; 527 mP2pStateMachineMessenger.send(Message.obtain(msg)); 528 mLooper.dispatchAll(); 529 } 530 531 /** 532 * Mock send WifiP2pManager.DELETE_PERSISTENT_GROUP. 533 * 534 * @param replyMessenger for checking replied message. 535 * @param netId is the network id of the p2p group. 536 */ sendDeletePersistentGroupMsg(Messenger replyMessenger, int netId)537 private void sendDeletePersistentGroupMsg(Messenger replyMessenger, 538 int netId) throws Exception { 539 Message msg = Message.obtain(); 540 msg.what = WifiP2pManager.DELETE_PERSISTENT_GROUP; 541 msg.arg1 = netId; 542 msg.replyTo = replyMessenger; 543 mP2pStateMachineMessenger.send(Message.obtain(msg)); 544 mLooper.dispatchAll(); 545 } 546 547 /** 548 * Send WifiP2pMonitor.P2P_GROUP_STARTED_EVENT. 549 * 550 * @param group the started group. 551 */ sendGroupStartedMsg(WifiP2pGroup group)552 private void sendGroupStartedMsg(WifiP2pGroup group) throws Exception { 553 if (group.getNetworkId() == WifiP2pGroup.NETWORK_ID_PERSISTENT) { 554 mGroups.add(group); 555 } 556 557 Message msg = Message.obtain(); 558 msg.what = WifiP2pMonitor.P2P_GROUP_STARTED_EVENT; 559 msg.obj = group; 560 mP2pStateMachineMessenger.send(Message.obtain(msg)); 561 mLooper.dispatchAll(); 562 } 563 564 /** 565 * Send WifiP2pMonitor.P2P_GROUP_REMOVED_EVENT. 566 */ sendGroupRemovedMsg()567 private void sendGroupRemovedMsg() throws Exception { 568 Message msg = Message.obtain(); 569 msg.what = WifiP2pMonitor.P2P_GROUP_REMOVED_EVENT; 570 mP2pStateMachineMessenger.send(Message.obtain(msg)); 571 mLooper.dispatchAll(); 572 } 573 574 /** 575 * Send WifiP2pMonitor.P2P_DEVICE_FOUND_EVENT. 576 * 577 * @param device the found device. 578 */ sendDeviceFoundEventMsg(WifiP2pDevice device)579 private void sendDeviceFoundEventMsg(WifiP2pDevice device) throws Exception { 580 Message msg = Message.obtain(); 581 msg.what = WifiP2pMonitor.P2P_DEVICE_FOUND_EVENT; 582 msg.obj = device; 583 mP2pStateMachineMessenger.send(Message.obtain(msg)); 584 mLooper.dispatchAll(); 585 } 586 587 /** 588 * Send WifiP2pMonitor.P2P_INVITATION_RESULT_EVENT. 589 * 590 * @param status invitation result. 591 */ sendInvitationResultMsg( WifiP2pServiceImpl.P2pStatus status)592 private void sendInvitationResultMsg( 593 WifiP2pServiceImpl.P2pStatus status) throws Exception { 594 Message msg = Message.obtain(); 595 msg.what = WifiP2pMonitor.P2P_INVITATION_RESULT_EVENT; 596 msg.obj = status; 597 mP2pStateMachineMessenger.send(Message.obtain(msg)); 598 mLooper.dispatchAll(); 599 } 600 601 /** 602 * Mock send WifiP2pManager.SET_CHANNEL 603 * 604 * @param replyMessenger for checking replied message. 605 * @param p2pChannels stores the listen and operating channels. 606 */ sendSetChannelMsg(Messenger replyMessenger, Bundle p2pChannels)607 private void sendSetChannelMsg(Messenger replyMessenger, 608 Bundle p2pChannels) throws Exception { 609 Message msg = Message.obtain(); 610 msg.what = WifiP2pManager.SET_CHANNEL; 611 msg.replyTo = replyMessenger; 612 msg.obj = p2pChannels; 613 mP2pStateMachineMessenger.send(Message.obtain(msg)); 614 mLooper.dispatchAll(); 615 } 616 617 /** 618 * Mock send WifiP2pManager.START_WPS 619 * 620 * @param replyMessenger for checking replied message. 621 * @param wps is the WPS configuration. 622 */ sendStartWpsMsg(Messenger replyMessenger, WpsInfo wps)623 private void sendStartWpsMsg(Messenger replyMessenger, WpsInfo wps) throws Exception { 624 Message msg = Message.obtain(); 625 msg.what = WifiP2pManager.START_WPS; 626 msg.replyTo = replyMessenger; 627 msg.obj = wps; 628 mP2pStateMachineMessenger.send(Message.obtain(msg)); 629 mLooper.dispatchAll(); 630 } 631 632 /** 633 * Mock send WifiP2pManager.SET_DEVICE_NAME 634 * 635 * @param replyMessenger for checking replied message. 636 * @param dev is the P2p device configuration. 637 */ sendSetDeviceNameMsg( Messenger replyMessenger, WifiP2pDevice dev)638 private void sendSetDeviceNameMsg( 639 Messenger replyMessenger, WifiP2pDevice dev) throws Exception { 640 Message msg = Message.obtain(); 641 msg.what = WifiP2pManager.SET_DEVICE_NAME; 642 msg.replyTo = replyMessenger; 643 msg.obj = dev; 644 mP2pStateMachineMessenger.send(Message.obtain(msg)); 645 mLooper.dispatchAll(); 646 } 647 648 /** 649 * Mock send WifiP2pManager.SET_WFD_INFO 650 * 651 * @param replyMessenger for checking replied message. 652 * @param wfdInfo is the P2p device's wfd information. 653 */ sendSetWfdInfoMsg( Messenger replyMessenger, WifiP2pWfdInfo wfdInfo)654 private void sendSetWfdInfoMsg( 655 Messenger replyMessenger, WifiP2pWfdInfo wfdInfo) throws Exception { 656 Message msg = Message.obtain(); 657 msg.what = WifiP2pManager.SET_WFD_INFO; 658 msg.replyTo = replyMessenger; 659 msg.obj = wfdInfo; 660 mP2pStateMachineMessenger.send(Message.obtain(msg)); 661 mLooper.dispatchAll(); 662 } 663 664 /** 665 * Mock send WifiP2pManager.SET_ONGOING_PEER_CONFIG 666 * 667 * @param replyMessenger for checking replied message. 668 * @param config used for change an ongoing peer connection. 669 */ sendSetOngoingPeerConfigMsg( Messenger replyMessenger, WifiP2pConfig config)670 private void sendSetOngoingPeerConfigMsg( 671 Messenger replyMessenger, WifiP2pConfig config) throws Exception { 672 Message msg = Message.obtain(); 673 msg.what = WifiP2pManager.SET_ONGOING_PEER_CONFIG; 674 msg.replyTo = replyMessenger; 675 msg.obj = config; 676 mP2pStateMachineMessenger.send(Message.obtain(msg)); 677 mLooper.dispatchAll(); 678 } 679 680 /** 681 * Mock send WifiP2pManager.REMOVE_LOCAL_SERVICE. 682 * 683 * @param replyMessenger for checking replied message. 684 * @param servInfo is the local service information. 685 */ sendRemoveLocalServiceMsg(Messenger replyMessenger, WifiP2pServiceInfo servInfo)686 private void sendRemoveLocalServiceMsg(Messenger replyMessenger, 687 WifiP2pServiceInfo servInfo) throws Exception { 688 Message msg = Message.obtain(); 689 msg.what = WifiP2pManager.REMOVE_LOCAL_SERVICE; 690 msg.obj = servInfo; 691 msg.replyTo = replyMessenger; 692 mP2pStateMachineMessenger.send(Message.obtain(msg)); 693 mLooper.dispatchAll(); 694 } 695 696 /** 697 * Mock send WifiP2pManager.REMOVE_SERVICE_REQUEST. 698 * 699 * @param replyMessenger for checking replied message. 700 * @param req is the service discovery request. 701 */ sendRemoveServiceRequestMsg(Messenger replyMessenger, WifiP2pServiceRequest req)702 private void sendRemoveServiceRequestMsg(Messenger replyMessenger, 703 WifiP2pServiceRequest req) throws Exception { 704 Message msg = Message.obtain(); 705 msg.what = WifiP2pManager.REMOVE_SERVICE_REQUEST; 706 msg.obj = req; 707 msg.replyTo = replyMessenger; 708 mP2pStateMachineMessenger.send(Message.obtain(msg)); 709 mLooper.dispatchAll(); 710 } 711 712 /** 713 * Send Connect API msg. 714 * 715 * @param replyMessenger for checking replied message. 716 * @param config options as described in {@link WifiP2pConfig} class. 717 */ sendConnectMsg(Messenger replyMessenger, WifiP2pConfig config)718 private void sendConnectMsg(Messenger replyMessenger, 719 WifiP2pConfig config) throws Exception { 720 Message msg = Message.obtain(); 721 Bundle extras = new Bundle(); 722 extras.putParcelable(WifiP2pManager.EXTRA_PARAM_KEY_CONFIG, config); 723 msg.what = WifiP2pManager.CONNECT; 724 if (SdkLevel.isAtLeastS()) { 725 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 726 } 727 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 728 msg.replyTo = replyMessenger; 729 mP2pStateMachineMessenger.send(Message.obtain(msg)); 730 mLooper.dispatchAll(); 731 } 732 733 734 /** 735 * Send Set Ongoing Peer Config API msg. 736 * 737 * @param replyMessenger for checking replied message. 738 * @param config options as described in {@link WifiP2pConfig} class. 739 */ sendSetOngoingPeerMsg(Messenger replyMessenger, WifiP2pConfig config)740 private void sendSetOngoingPeerMsg(Messenger replyMessenger, 741 WifiP2pConfig config) throws Exception { 742 Message msg = Message.obtain(); 743 msg.what = WifiP2pManager.SET_ONGOING_PEER_CONFIG; 744 msg.obj = config; 745 msg.replyTo = replyMessenger; 746 mP2pStateMachineMessenger.send(Message.obtain(msg)); 747 mLooper.dispatchAll(); 748 } 749 750 /** 751 * Send CreateGroup API msg. 752 * 753 * @param replyMessenger for checking replied message. 754 * @param config options as described in {@link WifiP2pConfig} class. 755 */ sendCreateGroupMsg(Messenger replyMessenger, int netId, WifiP2pConfig config)756 private void sendCreateGroupMsg(Messenger replyMessenger, 757 int netId, 758 WifiP2pConfig config) throws Exception { 759 Message msg = Message.obtain(); 760 Bundle extras = new Bundle(); 761 extras.putParcelable(WifiP2pManager.EXTRA_PARAM_KEY_CONFIG, config); 762 msg.what = WifiP2pManager.CREATE_GROUP; 763 msg.arg1 = netId; 764 if (SdkLevel.isAtLeastS()) { 765 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 766 } 767 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 768 msg.replyTo = replyMessenger; 769 mP2pStateMachineMessenger.send(Message.obtain(msg)); 770 mLooper.dispatchAll(); 771 } 772 773 /** 774 * Send SetVendorElements API msg. 775 * 776 * @param replyMessenger For checking replied message. 777 * @param ies The list of information elements. 778 */ sendSetVendorElementsMsg(Messenger replyMessenger, ArrayList<ScanResult.InformationElement> ies)779 private void sendSetVendorElementsMsg(Messenger replyMessenger, 780 ArrayList<ScanResult.InformationElement> ies) throws Exception { 781 Message msg = Message.obtain(); 782 Bundle extras = new Bundle(); 783 extras.putParcelableArrayList(WifiP2pManager.EXTRA_PARAM_KEY_INFORMATION_ELEMENT_LIST, 784 ies); 785 msg.what = WifiP2pManager.SET_VENDOR_ELEMENTS; 786 if (SdkLevel.isAtLeastS()) { 787 msg.obj = mContext.getAttributionSource(); 788 } 789 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 790 msg.replyTo = replyMessenger; 791 mP2pStateMachineMessenger.send(Message.obtain(msg)); 792 mLooper.dispatchAll(); 793 } 794 795 /** 796 * Send AddExternalApprover API msg. 797 * 798 * @param replyMessenger For checking replied message. 799 * @param devAddr the peer address. 800 * @param binder the application binder. 801 */ sendAddExternalApproverMsg(Messenger replyMessenger, MacAddress devAddr, Binder binder)802 private void sendAddExternalApproverMsg(Messenger replyMessenger, 803 MacAddress devAddr, Binder binder) throws Exception { 804 Message msg = Message.obtain(); 805 Bundle extras = new Bundle(); 806 if (null != devAddr) { 807 extras.putParcelable(WifiP2pManager.EXTRA_PARAM_KEY_PEER_ADDRESS, devAddr); 808 } 809 if (null != binder) { 810 extras.putBinder(WifiP2pManager.CALLING_BINDER, binder); 811 } 812 msg.what = WifiP2pManager.ADD_EXTERNAL_APPROVER; 813 if (SdkLevel.isAtLeastS()) { 814 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 815 } 816 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 817 msg.replyTo = replyMessenger; 818 mP2pStateMachineMessenger.send(Message.obtain(msg)); 819 mLooper.dispatchAll(); 820 } 821 822 /** 823 * Send RemoveExternalApprover API msg. 824 * 825 * @param replyMessenger For checking replied message. 826 * @param devAddr the peer address. 827 */ sendRemoveExternalApproverMsg(Messenger replyMessenger, MacAddress devAddr, Binder binder)828 private void sendRemoveExternalApproverMsg(Messenger replyMessenger, 829 MacAddress devAddr, Binder binder) throws Exception { 830 Message msg = Message.obtain(); 831 Bundle extras = new Bundle(); 832 if (null != devAddr) { 833 extras.putParcelable(WifiP2pManager.EXTRA_PARAM_KEY_PEER_ADDRESS, devAddr); 834 } 835 if (null != binder) { 836 extras.putBinder(WifiP2pManager.CALLING_BINDER, binder); 837 } 838 msg.what = WifiP2pManager.REMOVE_EXTERNAL_APPROVER; 839 if (SdkLevel.isAtLeastS()) { 840 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 841 } 842 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 843 msg.replyTo = replyMessenger; 844 mP2pStateMachineMessenger.send(Message.obtain(msg)); 845 mLooper.dispatchAll(); 846 } 847 848 /** 849 * Send SetConnectionRequestResult API msg. 850 * 851 * @param replyMessenger For checking replied message. 852 * @param devAddr the peer address. 853 * @param result the decision for the incoming request. 854 */ sendSetConnectionRequestResultMsg(Messenger replyMessenger, MacAddress devAddr, int result, Binder binder)855 private void sendSetConnectionRequestResultMsg(Messenger replyMessenger, 856 MacAddress devAddr, int result, Binder binder) throws Exception { 857 Message msg = Message.obtain(); 858 Bundle extras = new Bundle(); 859 if (null != devAddr) { 860 extras.putParcelable(WifiP2pManager.EXTRA_PARAM_KEY_PEER_ADDRESS, devAddr); 861 } 862 if (null != binder) { 863 extras.putBinder(WifiP2pManager.CALLING_BINDER, binder); 864 } 865 msg.what = WifiP2pManager.SET_CONNECTION_REQUEST_RESULT; 866 if (SdkLevel.isAtLeastS()) { 867 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 868 } 869 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 870 msg.arg1 = result; 871 msg.replyTo = replyMessenger; 872 mP2pStateMachineMessenger.send(Message.obtain(msg)); 873 mLooper.dispatchAll(); 874 } 875 876 /** 877 * Send P2P_GO_NEGOTIATION_FAILURE_EVENT 878 * 879 * @param replyMessenger For checking replied message. 880 * @param status the P2pStatus. 881 */ sendGoNegotiationFailureEvent(Messenger replyMessenger, WifiP2pServiceImpl.P2pStatus status)882 private void sendGoNegotiationFailureEvent(Messenger replyMessenger, 883 WifiP2pServiceImpl.P2pStatus status) throws Exception { 884 Message msg = Message.obtain(); 885 msg.what = WifiP2pMonitor.P2P_GO_NEGOTIATION_FAILURE_EVENT; 886 msg.obj = status; 887 msg.replyTo = replyMessenger; 888 mP2pStateMachineMessenger.send(Message.obtain(msg)); 889 mLooper.dispatchAll(); 890 } 891 892 /** 893 * Send AsyncChannel.CMD_CHANNEL_HALF_CONNECTED 894 * 895 * @param replyMessenger For checking replied message. 896 * @param channel AsyncChannel of the connection 897 */ sendChannelHalfConnectedEvent(Messenger replyMessenger, AsyncChannel channel)898 private void sendChannelHalfConnectedEvent(Messenger replyMessenger, AsyncChannel channel) 899 throws Exception { 900 Message msg = Message.obtain(); 901 msg.what = AsyncChannel.CMD_CHANNEL_HALF_CONNECTED; 902 msg.arg1 = AsyncChannel.STATUS_SUCCESSFUL; 903 msg.obj = channel; 904 msg.replyTo = replyMessenger; 905 mP2pStateMachineMessenger.send(Message.obtain(msg)); 906 mLooper.dispatchAll(); 907 } 908 sendOngoingPeerConfig(Messenger replyMessenger, AsyncChannel channel)909 private void sendOngoingPeerConfig(Messenger replyMessenger, AsyncChannel channel) 910 throws Exception { 911 Message msg = Message.obtain(); 912 msg.what = WifiP2pManager.SET_ONGOING_PEER_CONFIG; 913 msg.arg1 = AsyncChannel.STATUS_SUCCESSFUL; 914 msg.obj = channel; 915 msg.replyTo = replyMessenger; 916 mP2pStateMachineMessenger.send(Message.obtain(msg)); 917 mLooper.dispatchAll(); 918 } 919 920 /** 921 * Send simple API msg. 922 * 923 * Mock the API msg without arguments. 924 * 925 * @param replyMessenger for checking replied message. 926 */ sendSimpleMsg(Messenger replyMessenger, int what)927 private void sendSimpleMsg(Messenger replyMessenger, 928 int what) throws Exception { 929 Message msg = Message.obtain(); 930 Bundle extras = new Bundle(); 931 msg.what = what; 932 if (SdkLevel.isAtLeastS()) { 933 msg.obj = new AttributionSource(1000, TEST_PACKAGE_NAME, null); 934 } 935 msg.getData().putBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE, extras); 936 if (replyMessenger != null) { 937 msg.replyTo = replyMessenger; 938 } 939 mP2pStateMachineMessenger.send(Message.obtain(msg)); 940 mLooper.dispatchAll(); 941 } 942 943 /** 944 * Send simple API msg. 945 * 946 * Mock the API msg with objects. 947 * 948 * @param replyMessenger for checking replied message. 949 */ sendSimpleMsg(Messenger replyMessenger, int what, Object obj)950 private void sendSimpleMsg(Messenger replyMessenger, 951 int what, Object obj) throws Exception { 952 Message msg = Message.obtain(); 953 msg.what = what; 954 msg.obj = obj; 955 if (replyMessenger != null) { 956 msg.replyTo = replyMessenger; 957 } 958 mP2pStateMachineMessenger.send(Message.obtain(msg)); 959 mLooper.dispatchAll(); 960 } 961 setTargetSdkGreaterThanT()962 private void setTargetSdkGreaterThanT() { 963 if (SdkLevel.isAtLeastT()) { 964 when(mWifiPermissionsUtil.isTargetSdkLessThan(any(), 965 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false); 966 } 967 } 968 969 /** 970 * Send simple API msg. 971 * 972 * Mock the API msg with int arg. 973 * 974 * @param replyMessenger for checking replied message. 975 */ sendSimpleMsg(Messenger replyMessenger, int what, int arg1)976 private void sendSimpleMsg(Messenger replyMessenger, 977 int what, int arg1) throws Exception { 978 Message msg = Message.obtain(); 979 msg.what = what; 980 msg.arg1 = arg1; 981 if (replyMessenger != null) { 982 msg.replyTo = replyMessenger; 983 } 984 mP2pStateMachineMessenger.send(Message.obtain(msg)); 985 mLooper.dispatchAll(); 986 } 987 988 /** 989 * Send simple API msg. 990 * 991 * Mock the API msg with int arg. 992 * 993 * @param replyMessenger for checking replied message. 994 */ sendSimpleMsg(Messenger replyMessenger, int what, int arg1, Object obj)995 private void sendSimpleMsg(Messenger replyMessenger, 996 int what, int arg1, Object obj) throws Exception { 997 Message msg = Message.obtain(); 998 msg.what = what; 999 msg.arg1 = arg1; 1000 msg.obj = obj; 1001 if (replyMessenger != null) { 1002 msg.replyTo = replyMessenger; 1003 } 1004 mP2pStateMachineMessenger.send(Message.obtain(msg)); 1005 mLooper.dispatchAll(); 1006 } 1007 1008 /** 1009 * force P2p State enter InactiveState to start others unit test 1010 * 1011 * @param clientBinder client binder to use for p2p channel init 1012 */ forceP2pEnabled(Binder clientBinder)1013 private void forceP2pEnabled(Binder clientBinder) throws Exception { 1014 simulateWifiStateChange(true); 1015 simulateLocationModeChange(true); 1016 checkIsP2pInitWhenClientConnected(true, clientBinder, 1017 new WorkSource(clientBinder.getCallingUid(), TEST_PACKAGE_NAME)); 1018 verify(mContext).sendBroadcastWithMultiplePermissions( 1019 argThat(new WifiP2pServiceImplTest 1020 .P2pConnectionChangedIntentMatcherForNetworkState(IDLE)), any()); 1021 verify(mContext, never()).sendBroadcastWithMultiplePermissions( 1022 argThat(new WifiP2pServiceImplTest 1023 .P2pConnectionChangedIntentMatcherForNetworkState(FAILED)), any()); 1024 if (SdkLevel.isAtLeastT()) { 1025 verify(mContext).sendBroadcast( 1026 argThat(new WifiP2pServiceImplTest 1027 .P2pConnectionChangedIntentMatcherForNetworkState(IDLE)), any(), any()); 1028 verify(mBroadcastOptions, atLeastOnce()) 1029 .setRequireAllOfPermissions(TEST_REQUIRED_PERMISSIONS_T); 1030 verify(mBroadcastOptions, atLeastOnce()) 1031 .setRequireNoneOfPermissions(TEST_EXCLUDED_PERMISSIONS_T); 1032 } 1033 } 1034 1035 /** 1036 * Check is P2p init as expected when client connected 1037 * 1038 * @param expectInit set true if p2p init should succeed as expected, set false when 1039 * expected init should not happen 1040 * @param expectReplace set true if p2p worksource replace should succeed as expected, set false 1041 * when replace should not happen 1042 * @param clientBinder client binder to use for p2p channel init 1043 * @param expectedRequestorWs Expected merged requestorWs 1044 */ checkIsP2pInitWhenClientConnected(boolean expectInit, Binder clientBinder, WorkSource expectedRequestorWs)1045 private void checkIsP2pInitWhenClientConnected(boolean expectInit, 1046 Binder clientBinder, WorkSource expectedRequestorWs) 1047 throws Exception { 1048 mWifiP2pServiceImpl.getMessenger(clientBinder, TEST_PACKAGE_NAME, null); 1049 if (expectInit) { 1050 // send a command to force P2P enabled. 1051 sendSimpleMsg(mClientMessenger, WifiP2pManager.DISCOVER_PEERS); 1052 } 1053 mLooper.dispatchAll(); 1054 reset(mClientHandler); 1055 if (expectInit) { 1056 verify(mWifiNative).setupInterface(any(), any(), eq(expectedRequestorWs)); 1057 verify(mNetdWrapper).setInterfaceUp(anyString()); 1058 verify(mWifiMonitor, atLeastOnce()).registerHandler(anyString(), anyInt(), any()); 1059 // Verify timer is scheduled 1060 verify(mAlarmManager, times(2)).setExact(anyInt(), anyLong(), 1061 eq(mWifiP2pServiceImpl.P2P_IDLE_SHUTDOWN_MESSAGE_TIMEOUT_TAG), any(), any()); 1062 } else { 1063 verify(mWifiNative, never()).setupInterface(any(), any(), any()); 1064 verify(mNetdWrapper, never()).setInterfaceUp(anyString()); 1065 verify(mWifiMonitor, never()).registerHandler(anyString(), anyInt(), any()); 1066 } 1067 } 1068 1069 /** 1070 * Check is P2p teardown as expected when client disconnected 1071 * 1072 * @param expectTearDown set true if p2p teardown should succeed as expected, 1073 * set false when expected teardown should not happen 1074 * @param expectReplace set true if p2p worksource replace should succeed as expected, set false 1075 * when replace should not happen 1076 * @param clientBinder client binder to use for p2p channel init 1077 * @param expectedRequestorWs Expected merged requestorWs 1078 */ checkIsP2pTearDownWhenClientDisconnected( boolean expectTearDown, Binder clientBinder, WorkSource expectedRequestorWs)1079 private void checkIsP2pTearDownWhenClientDisconnected( 1080 boolean expectTearDown, 1081 Binder clientBinder, WorkSource expectedRequestorWs) throws Exception { 1082 mWifiP2pServiceImpl.close(clientBinder); 1083 mLooper.dispatchAll(); 1084 if (expectTearDown) { 1085 verify(mWifiNative).teardownInterface(); 1086 verify(mWifiMonitor).stopMonitoring(anyString()); 1087 } else { 1088 verify(mWifiNative, never()).teardownInterface(); 1089 verify(mWifiMonitor, never()).stopMonitoring(anyString()); 1090 } 1091 } 1092 verifyDeviceChangedBroadcastIntent(Intent intent)1093 private void verifyDeviceChangedBroadcastIntent(Intent intent) { 1094 WifiP2pDevice device = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE); 1095 assertEquals(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION, intent.getAction()); 1096 assertEquals(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, intent.getFlags()); 1097 assertEquals(mTestThisDevice.deviceName, device.deviceName); 1098 assertEquals(ANONYMIZED_DEVICE_ADDRESS, device.deviceAddress); 1099 assertEquals(mTestThisDevice.primaryDeviceType, device.primaryDeviceType); 1100 assertEquals(mTestThisDevice.secondaryDeviceType, device.secondaryDeviceType); 1101 assertEquals(mTestThisDevice.wpsConfigMethodsSupported, device.wpsConfigMethodsSupported); 1102 assertEquals(mTestThisDevice.deviceCapability, device.deviceCapability); 1103 assertEquals(mTestThisDevice.groupCapability, device.groupCapability); 1104 assertEquals(mTestThisDevice.status, device.status); 1105 if (mTestThisDevice.wfdInfo != null) { 1106 assertEquals(mTestThisDevice.wfdInfo.isEnabled(), 1107 device.wfdInfo.isEnabled()); 1108 assertEquals(mTestThisDevice.wfdInfo.getDeviceInfoHex(), 1109 device.wfdInfo.getDeviceInfoHex()); 1110 assertEquals(mTestThisDevice.wfdInfo.getControlPort(), 1111 device.wfdInfo.getControlPort()); 1112 assertEquals(mTestThisDevice.wfdInfo.getMaxThroughput(), 1113 device.wfdInfo.getMaxThroughput()); 1114 } else { 1115 assertEquals(mTestThisDevice.wfdInfo, device.wfdInfo); 1116 } 1117 } 1118 1119 /** 1120 * Check the broadcast of WIFI_P2P_THIS_DEVICE_CHANGED_ACTION is sent as expected. 1121 */ checkSendThisDeviceChangedBroadcast()1122 private void checkSendThisDeviceChangedBroadcast() { 1123 ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); 1124 String[] permission_gold = new String[] { 1125 android.Manifest.permission.ACCESS_FINE_LOCATION, 1126 android.Manifest.permission.ACCESS_WIFI_STATE}; 1127 ArgumentCaptor<String []> permissionCaptor = ArgumentCaptor.forClass(String[].class); 1128 verify(mContext, atLeastOnce()).sendBroadcastWithMultiplePermissions( 1129 intentCaptor.capture(), permissionCaptor.capture()); 1130 String [] permission = permissionCaptor.getValue(); 1131 Arrays.sort(permission); 1132 Arrays.sort(permission_gold); 1133 assertEquals(permission_gold, permission); 1134 verifyDeviceChangedBroadcastIntent(intentCaptor.getValue()); 1135 if (SdkLevel.isAtLeastT()) { 1136 // verify the same broadcast is also sent to apps with NEARBY_WIFI_DEVICES permission 1137 // but without ACCESS_FINE_LOCATION. 1138 verify(mContext, atLeastOnce()).sendBroadcast( 1139 intentCaptor.capture(), any(), any()); 1140 verify(mBroadcastOptions, atLeastOnce()) 1141 .setRequireAllOfPermissions(TEST_REQUIRED_PERMISSIONS_T); 1142 verify(mBroadcastOptions, atLeastOnce()) 1143 .setRequireNoneOfPermissions(TEST_EXCLUDED_PERMISSIONS_T); 1144 verifyDeviceChangedBroadcastIntent(intentCaptor.getValue()); 1145 } 1146 } 1147 1148 /** 1149 * Check the broadcast of ACTION_WIFI_P2P_PERSISTENT_GROUPS_CHANGED is sent as expected. 1150 */ checkSendP2pPersistentGroupsChangedBroadcast()1151 private void checkSendP2pPersistentGroupsChangedBroadcast() { 1152 ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); 1153 verify(mContext, atLeastOnce()).sendStickyBroadcastAsUser( 1154 intentCaptor.capture(), eq(UserHandle.ALL)); 1155 Intent intent = intentCaptor.getValue(); 1156 assertEquals(WifiP2pManager.ACTION_WIFI_P2P_PERSISTENT_GROUPS_CHANGED, intent.getAction()); 1157 assertEquals(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, intent.getFlags()); 1158 } 1159 1160 private class P2pConnectionChangedIntentMatcherForNetworkState 1161 implements ArgumentMatcher<Intent> { 1162 private final NetworkInfo.DetailedState mState; P2pConnectionChangedIntentMatcherForNetworkState(NetworkInfo.DetailedState state)1163 P2pConnectionChangedIntentMatcherForNetworkState(NetworkInfo.DetailedState state) { 1164 mState = state; 1165 } 1166 @Override matches(Intent intent)1167 public boolean matches(Intent intent) { 1168 if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION != intent.getAction()) { 1169 return false; 1170 } 1171 NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); 1172 return networkInfo.getDetailedState() == mState; 1173 } 1174 } 1175 1176 /** 1177 * Set up the instance of WifiP2pServiceImpl for testing. 1178 * 1179 * @param supported defines the p2p is supported or not in this instance. 1180 */ setUpWifiP2pServiceImpl(boolean supported)1181 private void setUpWifiP2pServiceImpl(boolean supported) throws Exception { 1182 reset(mContext, mFrameworkFacade, mHandlerThread, mPackageManager, mResources, 1183 mWifiInjector, mWifiNative); 1184 1185 generatorTestData(); 1186 mClientHanderLooper = new TestLooper(); 1187 mClientHandler = spy(new Handler(mClientHanderLooper.getLooper())); 1188 mClientMessenger = new Messenger(mClientHandler); 1189 mLooper = new TestLooper(); 1190 1191 when(mContext.getSystemService(Context.ALARM_SERVICE)) 1192 .thenReturn(mAlarmManager); 1193 when(mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 1194 .thenReturn(mLayoutInflater); 1195 when(mContext.getPackageManager()).thenReturn(mPackageManager); 1196 when(mContext.getResources()).thenReturn(mResources); 1197 when(mContext.getSystemService(WifiManager.class)).thenReturn(mWifiManager); 1198 if (SdkLevel.isAtLeastS()) { 1199 when(mContext.getAttributionSource()).thenReturn( 1200 new AttributionSource(1000, TEST_PACKAGE_NAME, null)); 1201 } 1202 when(mWifiManager.getConnectionInfo()).thenReturn(mWifiInfo); 1203 when(mWifiSettingsConfigStore.get(eq(WIFI_P2P_DEVICE_NAME))).thenReturn(thisDeviceName); 1204 when(mWifiSettingsConfigStore.get(eq(WIFI_P2P_PENDING_FACTORY_RESET))).thenReturn(false); 1205 when(mHandlerThread.getLooper()).thenReturn(mLooper.getLooper()); 1206 if (supported) { 1207 when(mPackageManager.hasSystemFeature(eq(PackageManager.FEATURE_WIFI_DIRECT))) 1208 .thenReturn(true); 1209 } else { 1210 when(mPackageManager.hasSystemFeature(eq(PackageManager.FEATURE_WIFI_DIRECT))) 1211 .thenReturn(false); 1212 } 1213 when(mResources.getString(R.string.config_wifi_p2p_device_type)) 1214 .thenReturn("10-0050F204-5"); 1215 when(mResources.getInteger(R.integer.config_p2pInvitationReceivedDialogTimeoutMs)) 1216 .thenReturn(P2P_INVITATION_RECEIVED_TIMEOUT_MS); 1217 when(mResources.getConfiguration()).thenReturn(mConfiguration); 1218 when(mWifiInjector.getFrameworkFacade()).thenReturn(mFrameworkFacade); 1219 when(mWifiInjector.getUserManager()).thenReturn(mUserManager); 1220 when(mWifiInjector.getWifiP2pMetrics()).thenReturn(mWifiP2pMetrics); 1221 when(mWifiInjector.getWifiP2pMonitor()).thenReturn(mWifiMonitor); 1222 when(mWifiInjector.getWifiP2pNative()).thenReturn(mWifiNative); 1223 when(mWifiInjector.getWifiP2pServiceHandlerThread()).thenReturn(mHandlerThread); 1224 when(mWifiInjector.getWifiPermissionsUtil()).thenReturn(mWifiPermissionsUtil); 1225 when(mWifiInjector.getSettingsConfigStore()).thenReturn(mWifiSettingsConfigStore); 1226 when(mWifiInjector.getCoexManager()).thenReturn(mCoexManager); 1227 when(mWifiInjector.getWifiGlobals()).thenReturn(mWifiGlobals); 1228 when(mWifiInjector.makeBroadcastOptions()).thenReturn(mBroadcastOptions); 1229 when(mWifiInjector.getWifiDialogManager()).thenReturn(mWifiDialogManager); 1230 when(mWifiDialogManager.createP2pInvitationReceivedDialog(any(), anyBoolean(), any(), 1231 anyInt(), any(), any())).thenReturn(mDialogHandle); 1232 when(mWifiDialogManager.createP2pInvitationSentDialog(any(), any(), anyInt())) 1233 .thenReturn(mDialogHandle); 1234 when(mWifiInjector.getClock()).thenReturn(mClock); 1235 when(mWifiInjector.getInterfaceConflictManager()).thenReturn(mInterfaceConflictManager); 1236 // enable all permissions, disable specific permissions in tests 1237 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 1238 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(true); 1239 when(mWifiPermissionsUtil.checkReadWifiCredentialPermission(anyInt())).thenReturn(true); 1240 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true); 1241 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(anyString(), anyString(), anyInt(), 1242 anyBoolean())).thenReturn(true); 1243 when(mInterfaceConflictManager.manageInterfaceConflictForStateMachine(any(), any(), any(), 1244 any(), any(), eq(HalDeviceManager.HDM_CREATE_IFACE_P2P), any())).thenReturn( 1245 InterfaceConflictManager.ICM_EXECUTE_COMMAND); 1246 // Mock target SDK to less than T by default to keep existing tests working. 1247 if (SdkLevel.isAtLeastT()) { 1248 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 1249 .thenReturn(true); 1250 when(mWifiPermissionsUtil.isTargetSdkLessThan(any(), 1251 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(true); 1252 } 1253 when(mWifiNative.setupInterface(any(), any(), any())).thenReturn(IFACE_NAME_P2P); 1254 when(mWifiNative.p2pGetDeviceAddress()).thenReturn(thisDeviceMac); 1255 when(mUserManager.getUserRestrictions()).thenReturn(mBundle); 1256 when(mFrameworkFacade.makeAlertDialogBuilder(any())).thenReturn(mAlertDialogBuilder); 1257 when(mAlertDialogBuilder.setTitle(any())).thenReturn(mAlertDialogBuilder); 1258 when(mAlertDialogBuilder.setView(any())).thenReturn(mAlertDialogBuilder); 1259 when(mAlertDialogBuilder.setMessage(any())).thenReturn(mAlertDialogBuilder); 1260 when(mAlertDialogBuilder.setPositiveButton(any(), any())).thenReturn(mAlertDialogBuilder); 1261 when(mAlertDialogBuilder.setNegativeButton(any(), any())).thenReturn(mAlertDialogBuilder); 1262 when(mAlertDialogBuilder.setOnCancelListener(any())).thenReturn(mAlertDialogBuilder); 1263 when(mAlertDialogBuilder.setPositiveButton(any(), any())).thenReturn(mAlertDialogBuilder); 1264 when(mAlertDialogBuilder.create()).thenReturn(mAlertDialog); 1265 when(mAlertDialog.getWindow()).thenReturn(mock(Window.class)); 1266 if (SdkLevel.isAtLeastT()) { 1267 when(mBundle.getBoolean(UserManager.DISALLOW_WIFI_DIRECT)).thenReturn(false); 1268 } 1269 doAnswer(new AnswerWithArguments() { 1270 public boolean answer(WifiP2pGroupList groups) { 1271 groups.clear(); 1272 for (WifiP2pGroup group : mGroups.getGroupList()) { 1273 groups.add(group); 1274 } 1275 return true; 1276 } 1277 }).when(mWifiNative).p2pListNetworks(any(WifiP2pGroupList.class)); 1278 doAnswer(new AnswerWithArguments() { 1279 public boolean answer(int netId) { 1280 mGroups.remove(netId); 1281 return true; 1282 } 1283 }).when(mWifiNative).removeP2pNetwork(anyInt()); 1284 when(mWifiNative.setVendorElements(any())).thenReturn(true); 1285 when(mWifiSettingsConfigStore.get(eq(WIFI_VERBOSE_LOGGING_ENABLED))).thenReturn(true); 1286 1287 doAnswer(new AnswerWithArguments() { 1288 public void answer(CoexManager.CoexListener listener) { 1289 mCoexListener = listener; 1290 } 1291 }).when(mCoexManager).registerCoexListener(any(CoexManager.CoexListener.class)); 1292 when(mCoexManager.getCoexRestrictions()).thenReturn(0); 1293 when(mCoexManager.getCoexUnsafeChannels()).thenReturn(Collections.emptyList()); 1294 1295 mWifiP2pServiceImpl = new WifiP2pServiceImpl(mContext, mWifiInjector); 1296 if (supported) { 1297 // register these event: 1298 // * WifiManager.WIFI_STATE_CHANGED_ACTION 1299 // * LocationManager.MODE_CHANGED_ACTION 1300 // * TetheringManager.ACTION_TETHER_STATE_CHANGED 1301 // * UserManager.ACTION_USER_RESTRICTIONS_CHANGED 1302 if (SdkLevel.isAtLeastT()) { 1303 verify(mContext, times(4)).registerReceiver(mBcastRxCaptor.capture(), 1304 any(IntentFilter.class)); 1305 mUserRestrictionReceiver = mBcastRxCaptor.getAllValues().get(3); 1306 } else { 1307 verify(mContext, times(3)).registerReceiver(mBcastRxCaptor.capture(), 1308 any(IntentFilter.class)); 1309 } 1310 mWifiStateChangedReceiver = mBcastRxCaptor.getAllValues().get(0); 1311 mLocationModeReceiver = mBcastRxCaptor.getAllValues().get(1); 1312 mTetherStateReceiver = mBcastRxCaptor.getAllValues().get(2); 1313 } 1314 1315 mWifiP2pServiceImpl.mNetdWrapper = mNetdWrapper; 1316 mP2pStateMachineMessenger = mWifiP2pServiceImpl.getP2pStateMachineMessenger(); 1317 } 1318 1319 @Before setUp()1320 public void setUp() throws Exception { 1321 MockitoAnnotations.initMocks(this); 1322 1323 mStaticMockSession = mockitoSession() 1324 .mockStatic(NetworkInterface.class) 1325 .startMocking(); 1326 lenient().when(NetworkInterface.getByName(eq(IFACE_NAME_P2P))) 1327 .thenReturn(mP2pNetworkInterface); 1328 when(mLayoutInflater.cloneInContext(any())).thenReturn(mLayoutInflater); 1329 when(mLayoutInflater.inflate(anyInt(), any())).thenReturn(mView); 1330 when(mLayoutInflater.inflate(anyInt(), any(), anyBoolean())).thenReturn(mView); 1331 when(mView.findViewById(eq(R.id.name))).thenReturn(mock(TextView.class)); 1332 when(mView.findViewById(eq(R.id.value))).thenReturn(mock(TextView.class)); 1333 when(mView.findViewById(eq(R.id.info))).thenReturn(mock(ViewGroup.class)); 1334 ArrayList<InetAddress> p2pInetAddresses = new ArrayList<>(); 1335 p2pInetAddresses.add(InetAddresses.parseNumericAddress(P2P_GO_IP)); 1336 when(mP2pNetworkInterface.getInetAddresses()) 1337 .thenReturn(Collections.enumeration(p2pInetAddresses)); 1338 1339 setUpWifiP2pServiceImpl(true); 1340 mClient1 = new Binder(); 1341 mClient2 = new Binder(); 1342 when(mContext.createContextAsUser(any(), anyInt())).thenReturn(mContext); 1343 } 1344 1345 @After cleanUp()1346 public void cleanUp() throws Exception { 1347 mStaticMockSession.finishMocking(); 1348 } 1349 1350 /** 1351 * Send P2P statemachine internal message. 1352 */ sendP2pStateMachineMessage(int what)1353 private void sendP2pStateMachineMessage(int what) throws Exception { 1354 Message msg = Message.obtain(); 1355 msg.what = what; 1356 mP2pStateMachineMessenger.send(Message.obtain(msg)); 1357 mLooper.dispatchAll(); 1358 } 1359 1360 /** 1361 * Mock enter Disabled state. 1362 */ mockEnterDisabledState()1363 private void mockEnterDisabledState() throws Exception { 1364 sendP2pStateMachineMessage(WifiP2pMonitor.SUP_DISCONNECTION_EVENT); 1365 } 1366 1367 /** 1368 * Mock enter GroupNegotiation state. 1369 */ mockEnterGroupNegotiationState()1370 private void mockEnterGroupNegotiationState() throws Exception { 1371 sendCreateGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_TEMPORARY, null); 1372 } 1373 1374 1375 /** 1376 * Mock enter ProvisionDiscovery state. 1377 */ mockEnterProvisionDiscoveryState()1378 private void mockEnterProvisionDiscoveryState() throws Exception { 1379 mockPeersList(); 1380 sendConnectMsg(mClientMessenger, mTestWifiP2pPeerConfig); 1381 } 1382 1383 /** 1384 * Mock enter Group created state. 1385 */ mockEnterGroupCreatedState()1386 private void mockEnterGroupCreatedState() throws Exception { 1387 forceP2pEnabled(mClient1); 1388 WifiP2pGroup group = new WifiP2pGroup(); 1389 group.setNetworkId(WifiP2pGroup.NETWORK_ID_PERSISTENT); 1390 group.setNetworkName("DIRECT-xy-NEW"); 1391 group.setOwner(new WifiP2pDevice("thisDeviceMac")); 1392 group.setIsGroupOwner(true); 1393 group.setInterface(IFACE_NAME_P2P); 1394 sendGroupStartedMsg(group); 1395 simulateTetherReady(); 1396 } 1397 1398 /** 1399 * Mock enter the user authorizing negotiation request state. 1400 */ mockEnterUserAuthorizingNegotiationRequestState(int wpsType)1401 private void mockEnterUserAuthorizingNegotiationRequestState(int wpsType) throws Exception { 1402 mockPeersList(); 1403 1404 // Enter UserAuthorizingNegotiationRequestState 1405 WifiP2pConfig config = new WifiP2pConfig(); 1406 config.deviceAddress = mTestWifiP2pDevice.deviceAddress; 1407 config.wps = new WpsInfo(); 1408 config.wps.setup = wpsType; 1409 1410 sendNegotiationRequestEvent(config); 1411 } 1412 1413 1414 /** 1415 * Mock WifiP2pServiceImpl.mPeers. 1416 */ mockPeersList()1417 private void mockPeersList() throws Exception { 1418 sendDeviceFoundEventMsg(mTestWifiP2pDevice); 1419 } 1420 1421 /** 1422 * Verify that p2p init / teardown whn a client connects / disconnects 1423 * with wifi enabled 1424 */ 1425 @Test testP2pInitWhenClientConnectWithWifiEnabled()1426 public void testP2pInitWhenClientConnectWithWifiEnabled() throws Exception { 1427 simulateWifiStateChange(true); 1428 checkIsP2pInitWhenClientConnected(true, mClient1, 1429 new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME)); 1430 checkIsP2pTearDownWhenClientDisconnected(true, mClient1, null); 1431 } 1432 1433 /** 1434 * Verify that p2p doesn't init when a client connects / disconnects 1435 * with wifi disabled 1436 */ 1437 @Test testP2pDoesntInitWhenClientConnectWithWifiDisabled()1438 public void testP2pDoesntInitWhenClientConnectWithWifiDisabled() 1439 throws Exception { 1440 simulateWifiStateChange(false); 1441 checkIsP2pInitWhenClientConnected(false, mClient1, 1442 new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME)); 1443 checkIsP2pTearDownWhenClientDisconnected(false, mClient1, null); 1444 } 1445 1446 /** 1447 * Verify that p2p init / teardown when wifi off / on 1448 * with a client connected 1449 */ 1450 @Test checkIsP2pInitForWifiChanges()1451 public void checkIsP2pInitForWifiChanges() throws Exception { 1452 forceP2pEnabled(mClient1); 1453 1454 simulateWifiStateChange(false); 1455 mLooper.dispatchAll(); 1456 verify(mWifiNative).teardownInterface(); 1457 verify(mWifiMonitor).stopMonitoring(anyString()); 1458 // Force to back disable state for next test 1459 mockEnterDisabledState(); 1460 1461 // wifi off / on won't initialize the p2p interface. 1462 simulateWifiStateChange(true); 1463 mLooper.dispatchAll(); 1464 verify(mWifiNative, times(1)).setupInterface(any(), any(), any()); 1465 verify(mNetdWrapper, times(1)).setInterfaceUp(anyString()); 1466 verify(mWifiMonitor, atLeastOnce()).registerHandler(anyString(), anyInt(), any()); 1467 1468 // Lazy initialization is done once receiving a command. 1469 sendSimpleMsg(mClientMessenger, WifiP2pManager.DISCOVER_PEERS); 1470 verify(mWifiNative, times(2)).setupInterface(any(), any(), any()); 1471 verify(mNetdWrapper, times(2)).setInterfaceUp(anyString()); 1472 } 1473 1474 /** 1475 * Verify that p2p will teardown /won't init when DISALLOW_WIFI_DIRECT user restriction is set 1476 */ 1477 @Test checkIsP2pInitForUserRestrictionChanges()1478 public void checkIsP2pInitForUserRestrictionChanges() throws Exception { 1479 assumeTrue(SdkLevel.isAtLeastT()); 1480 forceP2pEnabled(mClient1); 1481 1482 // p2p interface disabled when user restriction is set 1483 when(mBundle.getBoolean(UserManager.DISALLOW_WIFI_DIRECT)).thenReturn(true); 1484 Intent intent = new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED); 1485 mUserRestrictionReceiver.onReceive(mContext, intent); 1486 mLooper.dispatchAll(); 1487 verify(mWifiNative).teardownInterface(); 1488 verify(mWifiMonitor).stopMonitoring(anyString()); 1489 // Force to back disable state for next test 1490 mockEnterDisabledState(); 1491 1492 // p2p interface won't initialize when user restriction is set 1493 sendSimpleMsg(mClientMessenger, WifiP2pManager.DISCOVER_PEERS); 1494 verify(mWifiNative, times(1)).setupInterface(any(), any(), any()); 1495 verify(mNetdWrapper, times(1)).setInterfaceUp(anyString()); 1496 } 1497 1498 /** 1499 * Verify p2p init / teardown when two clients connect / disconnect 1500 */ 1501 @Test checkIsP2pInitForTwoClientsConnection()1502 public void checkIsP2pInitForTwoClientsConnection() throws Exception { 1503 forceP2pEnabled(mClient1); 1504 WorkSource expectedRequestorWs = 1505 new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME); 1506 reset(mWifiNative); 1507 reset(mNetdWrapper); 1508 reset(mWifiMonitor); 1509 // P2pInit check count should keep in once, same as one client connected case. 1510 checkIsP2pInitWhenClientConnected(false, mClient2, expectedRequestorWs); 1511 checkIsP2pTearDownWhenClientDisconnected(false, mClient2, 1512 new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME)); 1513 checkIsP2pTearDownWhenClientDisconnected(true, mClient1, null); 1514 } 1515 1516 /** 1517 * Verify WifiP2pManager.ADD_LOCAL_SERVICE_FAILED is returned when a caller 1518 * uses abnormal way to send WifiP2pManager.ADD_LOCAL_SERVICE (i.e no channel info updated). 1519 */ 1520 @Test testAddLocalServiceFailureWhenNoChannelUpdated()1521 public void testAddLocalServiceFailureWhenNoChannelUpdated() throws Exception { 1522 forceP2pEnabled(mClient1); 1523 sendAddLocalServiceMsg(mClientMessenger); 1524 verify(mWifiNative, never()).p2pServiceAdd(any()); 1525 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_LOCAL_SERVICE_FAILED)); 1526 } 1527 1528 /** 1529 * Verify WifiP2pManager.ADD_LOCAL_SERVICE_FAILED is returned when a caller 1530 * uses wrong package name to initialize a channel. 1531 */ 1532 @Test testAddLocalServiceFailureWhenChannelUpdateWrongPkgName()1533 public void testAddLocalServiceFailureWhenChannelUpdateWrongPkgName() throws Exception { 1534 forceP2pEnabled(mClient1); 1535 doThrow(new SecurityException("P2p unit test")) 1536 .when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1537 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1538 sendAddLocalServiceMsg(mClientMessenger); 1539 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_LOCAL_SERVICE_FAILED)); 1540 verify(mWifiNative, never()).p2pServiceAdd(any()); 1541 } 1542 1543 /** 1544 * Verify WifiP2pManager.ADD_LOCAL_SERVICE_FAILED is returned when a caller 1545 * without proper permission attmepts to send WifiP2pManager.ADD_LOCAL_SERVICE. 1546 */ 1547 @Test testAddLocalServiceFailureWhenCallerPermissionDenied()1548 public void testAddLocalServiceFailureWhenCallerPermissionDenied() throws Exception { 1549 setTargetSdkGreaterThanT(); 1550 forceP2pEnabled(mClient1); 1551 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1552 if (SdkLevel.isAtLeastT()) { 1553 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 1554 .thenReturn(false); 1555 } else { 1556 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), anyInt(), 1557 anyBoolean())).thenReturn(false); 1558 } 1559 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1560 sendAddLocalServiceMsg(mClientMessenger); 1561 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_LOCAL_SERVICE_FAILED)); 1562 verify(mWifiNative, never()).p2pServiceAdd(any()); 1563 if (SdkLevel.isAtLeastT()) { 1564 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1565 any(), eq(true), any()); 1566 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1567 any(), any(), anyInt(), anyBoolean()); 1568 } else { 1569 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 1570 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 1571 } 1572 } 1573 verifyAddLocalService()1574 private void verifyAddLocalService() throws Exception { 1575 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1576 when(mWifiNative.p2pServiceAdd(any())).thenReturn(true); 1577 sendAddLocalServiceMsg(mClientMessenger); 1578 verify(mWifiNative).p2pServiceAdd(any()); 1579 if (SdkLevel.isAtLeastT()) { 1580 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1581 any(), eq(true), any()); 1582 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1583 any(), any(), anyInt(), anyBoolean()); 1584 } else { 1585 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 1586 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 1587 } 1588 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_LOCAL_SERVICE_SUCCEEDED)); 1589 } 1590 1591 /** 1592 * Verify the caller with proper permission sends WifiP2pManager.ADD_LOCAL_SERVICE. 1593 */ 1594 @Test testAddLocalServiceSuccess()1595 public void testAddLocalServiceSuccess() throws Exception { 1596 setTargetSdkGreaterThanT(); 1597 forceP2pEnabled(mClient1); 1598 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1599 verifyAddLocalService(); 1600 } 1601 1602 /** 1603 * Verify WifiP2pManager.ADD_LOCAL_SERVICE_FAILED is returned when native call failure. 1604 */ 1605 @Test testAddLocalServiceFailureWhenNativeCallFailure()1606 public void testAddLocalServiceFailureWhenNativeCallFailure() throws Exception { 1607 setTargetSdkGreaterThanT(); 1608 forceP2pEnabled(mClient1); 1609 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1610 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1611 when(mWifiNative.p2pServiceAdd(any())).thenReturn(false); 1612 sendAddLocalServiceMsg(mClientMessenger); 1613 verify(mWifiNative).p2pServiceAdd(any()); 1614 if (SdkLevel.isAtLeastT()) { 1615 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1616 any(), eq(true), any()); 1617 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1618 any(), any(), anyInt(), anyBoolean()); 1619 } else { 1620 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 1621 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 1622 } 1623 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_LOCAL_SERVICE_FAILED)); 1624 } 1625 1626 /** 1627 * Verify WifiP2pManager.CONNECT_FAILED is returned when a caller 1628 * uses abnormal way to send WifiP2pManager.CONNECT (i.e no channel info updated). 1629 */ 1630 @Test testConnectWithConfigValidAsGroupFailureWhenNoChannelUpdated()1631 public void testConnectWithConfigValidAsGroupFailureWhenNoChannelUpdated() throws Exception { 1632 forceP2pEnabled(mClient1); 1633 sendConnectMsgWithConfigValidAsGroup(mClientMessenger); 1634 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CONNECT_FAILED)); 1635 verify(mWifiNative, never()).p2pGroupAdd(any(), anyBoolean()); 1636 } 1637 1638 /** 1639 * Verify WifiP2pManager.CONNECT_FAILED is returned when a caller 1640 * uses wrong package name to initialize a channel. 1641 */ 1642 @Test testConnectWithConfigValidAsGroupFailureWhenChannelUpdateWrongPkgName()1643 public void testConnectWithConfigValidAsGroupFailureWhenChannelUpdateWrongPkgName() 1644 throws Exception { 1645 forceP2pEnabled(mClient1); 1646 doThrow(new SecurityException("P2p unit test")) 1647 .when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1648 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1649 sendConnectMsgWithConfigValidAsGroup(mClientMessenger); 1650 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CONNECT_FAILED)); 1651 verify(mWifiNative, never()).p2pGroupAdd(any(), anyBoolean()); 1652 } 1653 1654 /** 1655 * Verify WifiP2pManager.CONNECT_FAILED is returned when a caller 1656 * without proper permission attmepts to send WifiP2pManager.CONNECT. 1657 */ 1658 @Test testConnectWithConfigValidAsGroupFailureWhenPermissionDenied()1659 public void testConnectWithConfigValidAsGroupFailureWhenPermissionDenied() throws Exception { 1660 setTargetSdkGreaterThanT(); 1661 forceP2pEnabled(mClient1); 1662 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1663 if (SdkLevel.isAtLeastT()) { 1664 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 1665 .thenReturn(false); 1666 } else { 1667 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), anyInt(), 1668 anyBoolean())).thenReturn(false); 1669 } 1670 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1671 sendConnectMsgWithConfigValidAsGroup(mClientMessenger); 1672 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CONNECT_FAILED)); 1673 verify(mWifiNative, never()).p2pGroupAdd(any(), anyBoolean()); 1674 if (SdkLevel.isAtLeastT()) { 1675 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1676 any(), eq(true), any()); 1677 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1678 any(), any(), anyInt(), anyBoolean()); 1679 } else { 1680 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1681 eq("testFeature"), anyInt(), eq(false)); 1682 } 1683 } 1684 1685 /** 1686 * Verify the caller with proper permission sends WifiP2pManager.CONNECT. 1687 */ 1688 @Test testConnectWithConfigValidAsGroupSuccess()1689 public void testConnectWithConfigValidAsGroupSuccess() throws Exception { 1690 setTargetSdkGreaterThanT(); 1691 forceP2pEnabled(mClient1); 1692 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1693 when(mWifiNative.p2pGroupAdd(any(), eq(true))).thenReturn(true); 1694 sendConnectMsgWithConfigValidAsGroup(mClientMessenger); 1695 verify(mWifiNative).p2pGroupAdd(any(), eq(true)); 1696 if (SdkLevel.isAtLeastT()) { 1697 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1698 any(), eq(true), any()); 1699 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1700 any(), any(), anyInt(), anyBoolean()); 1701 } else { 1702 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1703 eq("testFeature"), anyInt(), eq(false)); 1704 } 1705 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CONNECT_SUCCEEDED)); 1706 } 1707 1708 /** 1709 * Verify WifiP2pManager.CONNECT_FAILED is returned when native call failure. 1710 */ 1711 @Test testConnectWithConfigValidAsGroupFailureWhenNativeCallFailure()1712 public void testConnectWithConfigValidAsGroupFailureWhenNativeCallFailure() throws Exception { 1713 setTargetSdkGreaterThanT(); 1714 forceP2pEnabled(mClient1); 1715 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1716 when(mWifiNative.p2pGroupAdd(any(), eq(true))).thenReturn(false); 1717 sendConnectMsgWithConfigValidAsGroup(mClientMessenger); 1718 verify(mWifiNative).p2pGroupAdd(any(), eq(true)); 1719 if (SdkLevel.isAtLeastT()) { 1720 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1721 any(), eq(true), any()); 1722 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1723 any(), any(), anyInt(), anyBoolean()); 1724 } else { 1725 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1726 eq("testFeature"), anyInt(), eq(false)); 1727 } 1728 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CONNECT_FAILED)); 1729 } 1730 1731 /** 1732 * Verify WifiP2pManager.CREATE_GROUP_FAILED is returned when a caller 1733 * uses abnormal way to send WifiP2pManager.CREATE_GROUP (i.e no channel info updated). 1734 */ 1735 @Test testCreateGroupWithConfigValidAsGroupFailureWhenNoChannelUpdated()1736 public void testCreateGroupWithConfigValidAsGroupFailureWhenNoChannelUpdated() 1737 throws Exception { 1738 forceP2pEnabled(mClient1); 1739 sendCreateGroupMsgWithConfigValidAsGroup(mClientMessenger); 1740 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CREATE_GROUP_FAILED)); 1741 verify(mWifiNative, never()).p2pGroupAdd(anyBoolean()); 1742 verify(mWifiNative, never()).p2pGroupAdd(any(), anyBoolean()); 1743 } 1744 1745 /** 1746 * Verify WifiP2pManager.CREATE_GROUP_FAILED is returned with null object when a caller 1747 * uses wrong package name to initialize a channel. 1748 */ 1749 @Test testCreateGroupWithConfigValidAsGroupFailureWhenChannelUpdateWrongPkgName()1750 public void testCreateGroupWithConfigValidAsGroupFailureWhenChannelUpdateWrongPkgName() 1751 throws Exception { 1752 forceP2pEnabled(mClient1); 1753 doThrow(new SecurityException("P2p unit test")) 1754 .when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1755 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1756 sendCreateGroupMsgWithConfigValidAsGroup(mClientMessenger); 1757 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CREATE_GROUP_FAILED)); 1758 verify(mWifiNative, never()).p2pGroupAdd(anyBoolean()); 1759 verify(mWifiNative, never()).p2pGroupAdd(any(), anyBoolean()); 1760 } 1761 1762 /** 1763 * Verify WifiP2pManager.CREATE_GROUP_FAILED is returned when a caller 1764 * without proper permission attmepts to send WifiP2pManager.CREATE_GROUP. 1765 */ 1766 @Test testCreateGroupWithConfigValidAsGroupFailureWhenPermissionDenied()1767 public void testCreateGroupWithConfigValidAsGroupFailureWhenPermissionDenied() 1768 throws Exception { 1769 setTargetSdkGreaterThanT(); 1770 forceP2pEnabled(mClient1); 1771 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1772 if (SdkLevel.isAtLeastT()) { 1773 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 1774 .thenReturn(false); 1775 } else { 1776 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), anyInt(), 1777 anyBoolean())).thenReturn(false); 1778 } 1779 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1780 sendCreateGroupMsgWithConfigValidAsGroup(mClientMessenger); 1781 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CREATE_GROUP_FAILED)); 1782 verify(mWifiNative, never()).p2pGroupAdd(anyBoolean()); 1783 verify(mWifiNative, never()).p2pGroupAdd(any(), anyBoolean()); 1784 if (SdkLevel.isAtLeastT()) { 1785 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1786 any(), eq(true), any()); 1787 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1788 any(), any(), anyInt(), anyBoolean()); 1789 } else { 1790 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1791 eq("testFeature"), anyInt(), eq(false)); 1792 } 1793 } 1794 1795 /** 1796 * Verify the caller with proper permission sends WifiP2pManager.CREATE_GROUP. 1797 */ 1798 @Test testCreateGroupWithConfigValidAsGroupSuccess()1799 public void testCreateGroupWithConfigValidAsGroupSuccess() throws Exception { 1800 setTargetSdkGreaterThanT(); 1801 forceP2pEnabled(mClient1); 1802 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1803 when(mWifiNative.p2pGroupAdd(any(), eq(false))).thenReturn(true); 1804 sendCreateGroupMsgWithConfigValidAsGroup(mClientMessenger); 1805 verify(mWifiNative).p2pGroupAdd(any(), eq(false)); 1806 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CREATE_GROUP_SUCCEEDED)); 1807 if (SdkLevel.isAtLeastT()) { 1808 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1809 any(), eq(true), any()); 1810 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1811 any(), any(), anyInt(), anyBoolean()); 1812 } else { 1813 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 1814 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 1815 } 1816 } 1817 1818 /** 1819 * Verify WifiP2pManager.CREATE_GROUP_FAILED is returned when native call failure. 1820 */ 1821 @Test testCreateGroupWithConfigValidAsGroupFailureWhenNativeCallFailure()1822 public void testCreateGroupWithConfigValidAsGroupFailureWhenNativeCallFailure() 1823 throws Exception { 1824 setTargetSdkGreaterThanT(); 1825 forceP2pEnabled(mClient1); 1826 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1827 when(mWifiNative.p2pGroupAdd(any(), eq(false))).thenReturn(false); 1828 sendCreateGroupMsgWithConfigValidAsGroup(mClientMessenger); 1829 verify(mWifiNative).p2pGroupAdd(any(), eq(false)); 1830 if (SdkLevel.isAtLeastT()) { 1831 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1832 any(), eq(true), any()); 1833 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1834 any(), any(), anyInt(), anyBoolean()); 1835 } else { 1836 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1837 eq("testFeature"), anyInt(), eq(false)); 1838 } 1839 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CREATE_GROUP_FAILED)); 1840 } 1841 1842 /** 1843 * Verify WifiP2pManager.DISCOVER_PEERS_FAILED is returned when a caller 1844 * uses abnormal way to send WifiP2pManager.REQUEST_PEERS (i.e no channel info updated). 1845 */ 1846 @Test testDiscoverPeersFailureWhenNoChannelUpdated()1847 public void testDiscoverPeersFailureWhenNoChannelUpdated() throws Exception { 1848 forceP2pEnabled(mClient1); 1849 sendDiscoverPeersMsg(mClientMessenger); 1850 verify(mWifiNative, never()).p2pFind(anyInt()); 1851 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_PEERS_FAILED)); 1852 } 1853 1854 /** 1855 * Verify WifiP2pManager.DISCOVER_PEERS_FAILED is returned when a caller 1856 * uses wrong package name to initialize a channel. 1857 */ 1858 @Test testDiscoverPeersFailureWhenChannelUpdateWrongPkgName()1859 public void testDiscoverPeersFailureWhenChannelUpdateWrongPkgName() throws Exception { 1860 forceP2pEnabled(mClient1); 1861 doThrow(new SecurityException("P2p unit test")) 1862 .when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1863 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1864 sendDiscoverPeersMsg(mClientMessenger); 1865 verify(mWifiNative, never()).p2pFind(anyInt()); 1866 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_PEERS_FAILED)); 1867 } 1868 1869 /** 1870 * Verify WifiP2pManager.DISCOVER_PEERS_FAILED is returned with null object when a caller 1871 * without proper permission attmepts to send WifiP2pManager.DISCOVER_PEERS. 1872 */ 1873 @Test testDiscoverPeersFailureWhenPermissionDenied()1874 public void testDiscoverPeersFailureWhenPermissionDenied() throws Exception { 1875 setTargetSdkGreaterThanT(); 1876 forceP2pEnabled(mClient1); 1877 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1878 if (SdkLevel.isAtLeastT()) { 1879 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 1880 .thenReturn(false); 1881 } else { 1882 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), anyInt(), 1883 anyBoolean())).thenReturn(false); 1884 } 1885 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1886 sendDiscoverPeersMsg(mClientMessenger); 1887 verify(mWifiNative, never()).p2pFind(anyInt()); 1888 if (SdkLevel.isAtLeastT()) { 1889 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1890 any(), eq(true), any()); 1891 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1892 any(), any(), anyInt(), anyBoolean()); 1893 } else { 1894 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1895 eq("testFeature"), anyInt(), eq(true)); 1896 } 1897 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_PEERS_FAILED)); 1898 } 1899 1900 /** 1901 * Verify WifiP2pManager.DISCOVER_PEERS_FAILED is returned with null object when a caller 1902 * attmepts to send WifiP2pManager.DISCOVER_PEERS and location mode is disabled. 1903 */ 1904 @Test testDiscoverPeersFailureWhenLocationModeDisabled()1905 public void testDiscoverPeersFailureWhenLocationModeDisabled() throws Exception { 1906 forceP2pEnabled(mClient1); 1907 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 1908 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(anyString(), anyString(), anyInt(), 1909 eq(false))).thenReturn(true); 1910 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(anyString(), anyString(), anyInt(), 1911 eq(true))).thenReturn(false); 1912 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1913 sendDiscoverPeersMsg(mClientMessenger); 1914 verify(mWifiNative, never()).p2pFind(anyInt()); 1915 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1916 eq("testFeature"), anyInt(), eq(true)); 1917 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_PEERS_FAILED)); 1918 } 1919 1920 /** 1921 * Verify the caller with proper permission sends WifiP2pManager.DISCOVER_PEERS 1922 * with scan type, WIFI_P2P_SCAN_FULL. 1923 */ 1924 @Test testDiscoverPeersFullSuccess()1925 public void testDiscoverPeersFullSuccess() throws Exception { 1926 setTargetSdkGreaterThanT(); 1927 forceP2pEnabled(mClient1); 1928 when(mWifiNative.p2pFind(anyInt())).thenReturn(true); 1929 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1930 sendDiscoverPeersMsg(mClientMessenger); 1931 verify(mWifiNative).p2pFind(anyInt()); 1932 if (SdkLevel.isAtLeastT()) { 1933 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1934 any(), eq(true), any()); 1935 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1936 any(), any(), anyInt(), anyBoolean()); 1937 } else { 1938 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1939 eq("testFeature"), anyInt(), eq(true)); 1940 } 1941 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_PEERS_SUCCEEDED)); 1942 } 1943 1944 /** 1945 * Verify the caller with proper permission sends WifiP2pManager.DISCOVER_PEERS 1946 * with scan type, WIFI_P2P_SCAN_SOCIAL. 1947 */ 1948 @Test testDiscoverPeersSocialSuccess()1949 public void testDiscoverPeersSocialSuccess() throws Exception { 1950 setTargetSdkGreaterThanT(); 1951 when(mWifiNative.getSupportedFeatures()).thenReturn( 1952 WifiP2pManager.FEATURE_FLEXIBLE_DISCOVERY); 1953 forceP2pEnabled(mClient1); 1954 when(mWifiNative.p2pFind(anyInt(), anyInt(), anyInt())).thenReturn(true); 1955 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1956 sendDiscoverPeersMsg( 1957 mClientMessenger, WifiP2pManager.WIFI_P2P_SCAN_SOCIAL, 1958 WifiP2pManager.WIFI_P2P_SCAN_FREQ_UNSPECIFIED); 1959 verify(mWifiNative).p2pFind( 1960 eq(WifiP2pManager.WIFI_P2P_SCAN_SOCIAL), 1961 eq(WifiP2pManager.WIFI_P2P_SCAN_FREQ_UNSPECIFIED), anyInt()); 1962 if (SdkLevel.isAtLeastT()) { 1963 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1964 any(), eq(true), any()); 1965 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1966 any(), any(), anyInt(), anyBoolean()); 1967 } else { 1968 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1969 eq("testFeature"), anyInt(), eq(true)); 1970 } 1971 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_PEERS_SUCCEEDED)); 1972 } 1973 1974 /** 1975 * Verify the caller with proper permission sends WifiP2pManager.DISCOVER_PEERS 1976 * with scan type, WIFI_P2P_SCAN_SINGLE_FREQ. 1977 */ 1978 @Test testDiscoverPeersSpecificFrequencySuccess()1979 public void testDiscoverPeersSpecificFrequencySuccess() throws Exception { 1980 setTargetSdkGreaterThanT(); 1981 when(mWifiNative.getSupportedFeatures()).thenReturn( 1982 WifiP2pManager.FEATURE_FLEXIBLE_DISCOVERY); 1983 forceP2pEnabled(mClient1); 1984 when(mWifiNative.p2pFind(anyInt(), anyInt(), anyInt())).thenReturn(true); 1985 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 1986 int freq = 2412; 1987 sendDiscoverPeersMsg( 1988 mClientMessenger, WifiP2pManager.WIFI_P2P_SCAN_SINGLE_FREQ, freq); 1989 verify(mWifiNative).p2pFind( 1990 eq(WifiP2pManager.WIFI_P2P_SCAN_SINGLE_FREQ), eq(freq), anyInt()); 1991 if (SdkLevel.isAtLeastT()) { 1992 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 1993 any(), eq(true), any()); 1994 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 1995 any(), any(), anyInt(), anyBoolean()); 1996 } else { 1997 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 1998 eq("testFeature"), anyInt(), eq(true)); 1999 } 2000 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_PEERS_SUCCEEDED)); 2001 } 2002 2003 /** 2004 * Verify WifiP2pManager.DISCOVER_PEERS_FAILED is returned when native call failure. 2005 */ 2006 @Test testDiscoverPeersFailureWhenNativeCallFailure()2007 public void testDiscoverPeersFailureWhenNativeCallFailure() throws Exception { 2008 setTargetSdkGreaterThanT(); 2009 forceP2pEnabled(mClient1); 2010 when(mWifiNative.p2pFind(anyInt())).thenReturn(false); 2011 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2012 sendDiscoverPeersMsg(mClientMessenger); 2013 verify(mWifiNative).p2pFind(anyInt()); 2014 if (SdkLevel.isAtLeastT()) { 2015 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2016 any(), eq(true), any()); 2017 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2018 any(), any(), anyInt(), anyBoolean()); 2019 } else { 2020 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2021 eq("testFeature"), anyInt(), eq(true)); 2022 } 2023 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_PEERS_FAILED)); 2024 } 2025 2026 2027 /** 2028 * Verify WifiP2pManager.DISCOVER_SERVICES_FAILED is returned when a caller 2029 * uses abnormal way to send WifiP2pManager.DISCOVER_SERVICES (i.e no channel info updated). 2030 */ 2031 @Test testDiscoverServicesFailureWhenNoChannelUpdated()2032 public void testDiscoverServicesFailureWhenNoChannelUpdated() throws Exception { 2033 when(mWifiNative.p2pServDiscReq(anyString(), anyString())).thenReturn("mServiceDiscReqId"); 2034 forceP2pEnabled(mClient1); 2035 sendAddServiceRequestMsg(mClientMessenger); 2036 sendDiscoverServiceMsg(mClientMessenger); 2037 verify(mWifiNative, never()).p2pServDiscReq(anyString(), anyString()); 2038 verify(mWifiNative, never()).p2pFind(anyInt()); 2039 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_SERVICES_FAILED)); 2040 } 2041 2042 /** 2043 * Verify WifiP2pManager.DISCOVER_SERVICES_FAILED is returned when a caller 2044 * uses wrong package name to initialize a channel. 2045 */ 2046 @Test testDiscoverServicesFailureWhenChannelUpdateWrongPkgName()2047 public void testDiscoverServicesFailureWhenChannelUpdateWrongPkgName() throws Exception { 2048 when(mWifiNative.p2pServDiscReq(anyString(), anyString())).thenReturn("mServiceDiscReqId"); 2049 forceP2pEnabled(mClient1); 2050 doThrow(new SecurityException("P2p unit test")) 2051 .when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 2052 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2053 sendAddServiceRequestMsg(mClientMessenger); 2054 sendDiscoverServiceMsg(mClientMessenger); 2055 verify(mWifiNative, never()).p2pServDiscReq(anyString(), anyString()); 2056 verify(mWifiNative, never()).p2pFind(anyInt()); 2057 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_SERVICES_FAILED)); 2058 } 2059 2060 /** 2061 * Verify WifiP2pManager.DISCOVER_SERVICES_FAILED is returned when a caller 2062 * without proper permission attmepts to send WifiP2pManager.DISCOVER_SERVICES. 2063 */ 2064 @Test testDiscoverServicesFailureWhenPermissionDenied()2065 public void testDiscoverServicesFailureWhenPermissionDenied() throws Exception { 2066 setTargetSdkGreaterThanT(); 2067 when(mWifiNative.p2pServDiscReq(anyString(), anyString())) 2068 .thenReturn("mServiceDiscReqId"); 2069 forceP2pEnabled(mClient1); 2070 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 2071 if (SdkLevel.isAtLeastT()) { 2072 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 2073 .thenReturn(false); 2074 } else { 2075 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), anyInt(), 2076 anyBoolean())).thenReturn(false); 2077 } 2078 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2079 sendAddServiceRequestMsg(mClientMessenger); 2080 sendDiscoverServiceMsg(mClientMessenger); 2081 verify(mWifiNative, never()).p2pServDiscReq(anyString(), anyString()); 2082 verify(mWifiNative, never()).p2pFind(anyInt(), anyInt(), anyInt()); 2083 if (SdkLevel.isAtLeastT()) { 2084 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2085 any(), eq(true), any()); 2086 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2087 any(), any(), anyInt(), anyBoolean()); 2088 } else { 2089 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2090 eq("testFeature"), anyInt(), eq(true)); 2091 } 2092 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_SERVICES_FAILED)); 2093 } 2094 2095 /** 2096 * Verify WifiP2pManager.DISCOVER_SERVICES_FAILED is returned when a caller 2097 * attmepts to send WifiP2pManager.DISCOVER_SERVICES and location mode is disabled. 2098 */ 2099 @Test testDiscoverServicesFailureWhenLocationModeDisabled()2100 public void testDiscoverServicesFailureWhenLocationModeDisabled() throws Exception { 2101 when(mWifiNative.p2pServDiscReq(anyString(), anyString())) 2102 .thenReturn("mServiceDiscReqId"); 2103 forceP2pEnabled(mClient1); 2104 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 2105 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(anyString(), anyString(), anyInt(), 2106 eq(false))).thenReturn(true); 2107 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(anyString(), anyString(), anyInt(), 2108 eq(true))).thenReturn(false); 2109 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2110 sendAddServiceRequestMsg(mClientMessenger); 2111 sendDiscoverServiceMsg(mClientMessenger); 2112 verify(mWifiNative, never()).p2pServDiscReq(anyString(), anyString()); 2113 verify(mWifiNative, never()).p2pFind(anyInt(), anyInt(), anyInt()); 2114 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2115 eq("testFeature"), anyInt(), eq(true)); 2116 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_SERVICES_FAILED)); 2117 } 2118 2119 /** 2120 * Verify the caller with proper permission sends WifiP2pManager.DISCOVER_SERVICES. 2121 */ 2122 @Test testDiscoverServicesSuccess()2123 public void testDiscoverServicesSuccess() throws Exception { 2124 setTargetSdkGreaterThanT(); 2125 when(mWifiNative.p2pServDiscReq(anyString(), anyString())) 2126 .thenReturn("mServiceDiscReqId"); 2127 when(mWifiNative.p2pFind(anyInt())).thenReturn(true); 2128 forceP2pEnabled(mClient1); 2129 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2130 sendAddServiceRequestMsg(mClientMessenger); 2131 sendDiscoverServiceMsg(mClientMessenger); 2132 verify(mWifiNative).p2pServDiscReq(anyString(), anyString()); 2133 verify(mWifiNative, atLeastOnce()).p2pFind(anyInt()); 2134 if (SdkLevel.isAtLeastT()) { 2135 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2136 any(), eq(true), any()); 2137 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2138 any(), any(), anyInt(), anyBoolean()); 2139 } else { 2140 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2141 eq("testFeature"), anyInt(), eq(true)); 2142 } 2143 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_SERVICES_SUCCEEDED)); 2144 } 2145 2146 /** 2147 * Verify WifiP2pManager.DISCOVER_SERVICES_FAILED is returned when add service failure. 2148 */ 2149 @Test testDiscoverServicesFailureWhenAddServiceRequestFailure()2150 public void testDiscoverServicesFailureWhenAddServiceRequestFailure() throws Exception { 2151 setTargetSdkGreaterThanT(); 2152 when(mWifiNative.p2pServDiscReq(anyString(), anyString())).thenReturn(null); 2153 forceP2pEnabled(mClient1); 2154 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2155 sendAddServiceRequestMsg(mClientMessenger); 2156 sendDiscoverServiceMsg(mClientMessenger); 2157 verify(mWifiNative).p2pServDiscReq(anyString(), anyString()); 2158 verify(mWifiNative, never()).p2pFind(anyInt(), anyInt(), anyInt()); 2159 if (SdkLevel.isAtLeastT()) { 2160 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2161 any(), eq(true), any()); 2162 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2163 any(), any(), anyInt(), anyBoolean()); 2164 } else { 2165 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2166 eq("testFeature"), anyInt(), eq(true)); 2167 } 2168 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_SERVICES_FAILED)); 2169 } 2170 2171 /** 2172 * Verify WifiP2pManager.DISCOVER_SERVICES_FAILED is returned when native call failure. 2173 */ 2174 @Test testDiscoverServicesFailureWhenNativeCallFailure()2175 public void testDiscoverServicesFailureWhenNativeCallFailure() throws Exception { 2176 setTargetSdkGreaterThanT(); 2177 when(mWifiNative.p2pServDiscReq(anyString(), anyString())) 2178 .thenReturn("mServiceDiscReqId"); 2179 when(mWifiNative.p2pFind(anyInt())).thenReturn(false); 2180 forceP2pEnabled(mClient1); 2181 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2182 sendAddServiceRequestMsg(mClientMessenger); 2183 sendDiscoverServiceMsg(mClientMessenger); 2184 verify(mWifiNative).p2pServDiscReq(anyString(), anyString()); 2185 verify(mWifiNative).p2pFind(anyInt()); 2186 if (SdkLevel.isAtLeastT()) { 2187 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2188 any(), eq(true), any()); 2189 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2190 any(), any(), anyInt(), anyBoolean()); 2191 } else { 2192 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2193 eq("testFeature"), anyInt(), eq(true)); 2194 } 2195 assertTrue(mClientHandler.hasMessages(WifiP2pManager.DISCOVER_SERVICES_FAILED)); 2196 } 2197 2198 /** 2199 * Verify WifiP2pManager.RESPONSE_PEERS is returned with null object when a caller 2200 * uses abnormal way to send WifiP2pManager.REQUEST_PEERS (i.e no channel info updated). 2201 */ 2202 @Test testRequestPeersFailureWhenNoChannelUpdated()2203 public void testRequestPeersFailureWhenNoChannelUpdated() throws Exception { 2204 forceP2pEnabled(mClient1); 2205 mockPeersList(); 2206 sendRequestPeersMsg(mClientMessenger); 2207 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2208 WifiP2pDeviceList peers = (WifiP2pDeviceList) mMessageCaptor.getValue().obj; 2209 assertEquals(WifiP2pManager.RESPONSE_PEERS, mMessageCaptor.getValue().what); 2210 assertNull(peers.get(mTestWifiP2pDevice.deviceAddress)); 2211 2212 } 2213 2214 /** 2215 * Verify WifiP2pManager.RESPONSE_PEERS is returned with null object when a caller 2216 * uses wrong package name to initialize a channel. 2217 */ 2218 @Test testRequestPeersFailureWhenChannelUpdateWrongPkgName()2219 public void testRequestPeersFailureWhenChannelUpdateWrongPkgName() throws Exception { 2220 forceP2pEnabled(mClient1); 2221 mockPeersList(); 2222 doThrow(new SecurityException("P2p unit test")) 2223 .when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 2224 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2225 sendRequestPeersMsg(mClientMessenger); 2226 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2227 WifiP2pDeviceList peers = (WifiP2pDeviceList) mMessageCaptor.getValue().obj; 2228 assertEquals(WifiP2pManager.RESPONSE_PEERS, mMessageCaptor.getValue().what); 2229 assertNull(peers.get(mTestWifiP2pDevice.deviceAddress)); 2230 } 2231 2232 /** 2233 * Verify WifiP2pManager.RESPONSE_PEERS is returned with null object when a caller 2234 * without proper permission attmepts to send WifiP2pManager.REQUEST_PEERS. 2235 */ 2236 @Test testRequestPeersFailureWhenPermissionDenied()2237 public void testRequestPeersFailureWhenPermissionDenied() throws Exception { 2238 setTargetSdkGreaterThanT(); 2239 forceP2pEnabled(mClient1); 2240 mockPeersList(); 2241 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 2242 if (SdkLevel.isAtLeastT()) { 2243 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 2244 .thenReturn(false); 2245 } else { 2246 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), anyInt(), 2247 anyBoolean())).thenReturn(false); 2248 } 2249 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2250 sendRequestPeersMsg(mClientMessenger); 2251 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2252 if (SdkLevel.isAtLeastT()) { 2253 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2254 any(), eq(true), any()); 2255 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2256 any(), any(), anyInt(), anyBoolean()); 2257 } else { 2258 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2259 eq("testFeature"), anyInt(), eq(true)); 2260 } 2261 WifiP2pDeviceList peers = (WifiP2pDeviceList) mMessageCaptor.getValue().obj; 2262 assertEquals(WifiP2pManager.RESPONSE_PEERS, mMessageCaptor.getValue().what); 2263 assertNull(peers.get(mTestWifiP2pDevice.deviceAddress)); 2264 2265 } 2266 2267 /** 2268 * Verify WifiP2pManager.RESPONSE_PEERS is returned with null object when a caller 2269 * attmepts to send WifiP2pManager.REQUEST_PEERS and location mode is disabled. 2270 */ 2271 @Test testRequestPeersFailureWhenLocationModeDisabled()2272 public void testRequestPeersFailureWhenLocationModeDisabled() throws Exception { 2273 forceP2pEnabled(mClient1); 2274 mockPeersList(); 2275 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 2276 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(anyString(), anyString(), anyInt(), 2277 eq(false))).thenReturn(true); 2278 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(anyString(), anyString(), anyInt(), 2279 eq(true))).thenReturn(false); 2280 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2281 sendRequestPeersMsg(mClientMessenger); 2282 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2283 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2284 eq("testFeature"), anyInt(), eq(true)); 2285 WifiP2pDeviceList peers = (WifiP2pDeviceList) mMessageCaptor.getValue().obj; 2286 assertEquals(WifiP2pManager.RESPONSE_PEERS, mMessageCaptor.getValue().what); 2287 assertNull(peers.get(mTestWifiP2pDevice.deviceAddress)); 2288 2289 } 2290 2291 /** 2292 * Verify WifiP2pManager.RESPONSE_PEERS is returned with expect object when a caller 2293 * with proper permission to send WifiP2pManager.REQUEST_PEERS. 2294 */ 2295 @Test testRequestPeersSuccess()2296 public void testRequestPeersSuccess() throws Exception { 2297 setTargetSdkGreaterThanT(); 2298 forceP2pEnabled(mClient1); 2299 mockPeersList(); 2300 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2301 sendRequestPeersMsg(mClientMessenger); 2302 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2303 if (SdkLevel.isAtLeastT()) { 2304 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2305 any(), eq(true), any()); 2306 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2307 any(), any(), anyInt(), anyBoolean()); 2308 } else { 2309 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2310 eq("testFeature"), anyInt(), eq(true)); 2311 } 2312 WifiP2pDeviceList peers = (WifiP2pDeviceList) mMessageCaptor.getValue().obj; 2313 assertEquals(WifiP2pManager.RESPONSE_PEERS, mMessageCaptor.getValue().what); 2314 assertNotEquals(null, peers.get(mTestWifiP2pDevice.deviceAddress)); 2315 } 2316 2317 /** 2318 * Verify WifiP2pManager.RESPONSE_GROUP_INFO is returned with null object when a caller 2319 * uses abnormal way to send WifiP2pManager.REQUEST_GROUP_INFO (i.e no channel info updated). 2320 */ 2321 @Test testRequestGroupInfoFailureWhenNoChannelUpdated()2322 public void testRequestGroupInfoFailureWhenNoChannelUpdated() throws Exception { 2323 forceP2pEnabled(mClient1); 2324 sendGroupStartedMsg(mTestWifiP2pGroup); 2325 simulateTetherReady(); 2326 sendRequestGroupInfoMsg(mClientMessenger); 2327 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2328 assertEquals(WifiP2pManager.RESPONSE_GROUP_INFO, mMessageCaptor.getValue().what); 2329 assertNull(mMessageCaptor.getValue().obj); 2330 } 2331 2332 /** 2333 * Verify WifiP2pManager.RESPONSE_GROUP_INFO is returned with null object when a caller 2334 * uses wrong package name to initialize a channel. 2335 */ 2336 @Test testRequestGroupInfoFailureWhenChannelUpdateWrongPkgName()2337 public void testRequestGroupInfoFailureWhenChannelUpdateWrongPkgName() throws Exception { 2338 forceP2pEnabled(mClient1); 2339 sendGroupStartedMsg(mTestWifiP2pGroup); 2340 simulateTetherReady(); 2341 doThrow(new SecurityException("P2p unit test")) 2342 .when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 2343 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2344 sendRequestGroupInfoMsg(mClientMessenger); 2345 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2346 assertEquals(WifiP2pManager.RESPONSE_GROUP_INFO, mMessageCaptor.getValue().what); 2347 assertNull(mMessageCaptor.getValue().obj); 2348 } 2349 2350 /** 2351 * Verify WifiP2pManager.RESPONSE_GROUP_INFO is returned with null object when a caller 2352 * without proper permission attempts to send WifiP2pManager.REQUEST_GROUP_INFO. 2353 */ 2354 @Test testRequestGroupInfoFailureWhenPermissionDenied()2355 public void testRequestGroupInfoFailureWhenPermissionDenied() throws Exception { 2356 setTargetSdkGreaterThanT(); 2357 forceP2pEnabled(mClient1); 2358 sendGroupStartedMsg(mTestWifiP2pGroup); 2359 simulateTetherReady(); 2360 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 2361 if (SdkLevel.isAtLeastT()) { 2362 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 2363 .thenReturn(false); 2364 } else { 2365 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), anyInt(), 2366 anyBoolean())).thenReturn(false); 2367 } 2368 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2369 sendRequestGroupInfoMsg(mClientMessenger); 2370 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2371 if (SdkLevel.isAtLeastT()) { 2372 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2373 any(), eq(true), any()); 2374 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2375 any(), any(), anyInt(), anyBoolean()); 2376 } else { 2377 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2378 eq("testFeature"), anyInt(), eq(false)); 2379 } 2380 assertEquals(WifiP2pManager.RESPONSE_GROUP_INFO, mMessageCaptor.getValue().what); 2381 assertNull(mMessageCaptor.getValue().obj); 2382 } 2383 2384 /** 2385 * Verify WifiP2pManager.RESPONSE_GROUP_INFO is returned with expect object when a caller 2386 * with proper permission. 2387 */ 2388 @Test testRequestGroupInfoSuccess()2389 public void testRequestGroupInfoSuccess() throws Exception { 2390 setTargetSdkGreaterThanT(); 2391 mTestWifiP2pGroup.setOwner(mTestThisDevice); 2392 forceP2pEnabled(mClient1); 2393 sendGroupStartedMsg(mTestWifiP2pGroup); 2394 simulateTetherReady(); 2395 when(mWifiPermissionsUtil.checkLocalMacAddressPermission(anyInt())).thenReturn(false); 2396 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2397 sendRequestGroupInfoMsg(mClientMessenger); 2398 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2399 if (SdkLevel.isAtLeastT()) { 2400 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2401 any(), eq(true), any()); 2402 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2403 any(), any(), anyInt(), anyBoolean()); 2404 } else { 2405 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2406 eq("testFeature"), anyInt(), eq(false)); 2407 } 2408 assertEquals(WifiP2pManager.RESPONSE_GROUP_INFO, mMessageCaptor.getValue().what); 2409 WifiP2pGroup wifiP2pGroup = (WifiP2pGroup) mMessageCaptor.getValue().obj; 2410 assertEquals(mTestWifiP2pGroup.getNetworkName(), wifiP2pGroup.getNetworkName()); 2411 // Ensure that our own MAC address is anonymized if we're the group owner. 2412 assertEquals(ANONYMIZED_DEVICE_ADDRESS, wifiP2pGroup.getOwner().deviceAddress); 2413 } 2414 2415 /** 2416 * Verify WifiP2pManager.RESPONSE_GROUP_INFO does not anonymize this device's MAC address when 2417 * requested by an app with the LOCAL_MAC_ADDRESS permission. 2418 */ 2419 @Test testRequestGroupInfoIncludesMacForNetworkSettingsApp()2420 public void testRequestGroupInfoIncludesMacForNetworkSettingsApp() throws Exception { 2421 setTargetSdkGreaterThanT(); 2422 mTestWifiP2pGroup.setOwner(mTestThisDevice); 2423 forceP2pEnabled(mClient1); 2424 sendGroupStartedMsg(mTestWifiP2pGroup); 2425 simulateTetherReady(); 2426 when(mWifiPermissionsUtil.checkLocalMacAddressPermission(anyInt())).thenReturn(true); 2427 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2428 sendRequestGroupInfoMsg(mClientMessenger); 2429 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2430 if (SdkLevel.isAtLeastT()) { 2431 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2432 any(), eq(true), any()); 2433 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2434 any(), any(), anyInt(), anyBoolean()); 2435 } else { 2436 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2437 eq("testFeature"), anyInt(), eq(false)); 2438 } 2439 assertEquals(WifiP2pManager.RESPONSE_GROUP_INFO, mMessageCaptor.getValue().what); 2440 WifiP2pGroup wifiP2pGroup = (WifiP2pGroup) mMessageCaptor.getValue().obj; 2441 assertEquals(thisDeviceMac, wifiP2pGroup.getOwner().deviceAddress); 2442 } 2443 2444 /** 2445 * Verify WifiP2pManager.START_LISTEN_FAILED is returned when a caller 2446 * without proper permission attempts to send WifiP2pManager.START_LISTEN. 2447 */ 2448 @Test testStartListenFailureWhenPermissionDenied()2449 public void testStartListenFailureWhenPermissionDenied() throws Exception { 2450 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(anyString(), anyString(), anyInt(), 2451 anyBoolean())).thenReturn(false); 2452 forceP2pEnabled(mClient1); 2453 sendSimpleMsg(mClientMessenger, WifiP2pManager.START_LISTEN); 2454 assertTrue(mClientHandler.hasMessages(WifiP2pManager.START_LISTEN_FAILED)); 2455 // p2pFlush should be invoked once in forceP2pEnabled. 2456 verify(mWifiNative).p2pFlush(); 2457 verify(mWifiNative, never()).p2pStopFind(); 2458 verify(mWifiNative, never()).p2pExtListen(anyBoolean(), anyInt(), anyInt()); 2459 } 2460 2461 /** 2462 * Verify WifiP2pManager.START_LISTEN_FAILED is returned when native call failure. 2463 */ 2464 @Test testStartListenFailureWhenNativeCallFailure()2465 public void testStartListenFailureWhenNativeCallFailure() throws Exception { 2466 setTargetSdkGreaterThanT(); 2467 when(mWifiNative.p2pExtListen(eq(true), anyInt(), anyInt())).thenReturn(false); 2468 forceP2pEnabled(mClient1); 2469 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2470 sendSimpleMsg(mClientMessenger, WifiP2pManager.START_LISTEN); 2471 // p2pFlush should be invoked once in forceP2pEnabled. 2472 verify(mWifiNative).p2pFlush(); 2473 verify(mWifiNative).p2pStopFind(); 2474 verify(mWifiNative).p2pExtListen(eq(true), anyInt(), anyInt()); 2475 assertTrue(mClientHandler.hasMessages(WifiP2pManager.START_LISTEN_FAILED)); 2476 if (SdkLevel.isAtLeastT()) { 2477 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2478 any(), eq(true), any()); 2479 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2480 any(), any(), anyInt(), anyBoolean()); 2481 } else { 2482 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2483 eq("testFeature"), anyInt(), eq(true)); 2484 } 2485 } 2486 2487 /** 2488 * Verify the caller with proper permission sends WifiP2pManager.START_LISTEN. 2489 */ 2490 @Test testStartListenSuccess()2491 public void testStartListenSuccess() throws Exception { 2492 setTargetSdkGreaterThanT(); 2493 when(mWifiNative.p2pExtListen(eq(true), anyInt(), anyInt())).thenReturn(true); 2494 forceP2pEnabled(mClient1); 2495 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2496 sendSimpleMsg(mClientMessenger, WifiP2pManager.START_LISTEN); 2497 // p2pFlush should be invoked once in forceP2pEnabled. 2498 verify(mWifiNative).p2pFlush(); 2499 verify(mWifiNative).p2pStopFind(); 2500 verify(mWifiNative).p2pExtListen(eq(true), anyInt(), anyInt()); 2501 assertTrue(mClientHandler.hasMessages(WifiP2pManager.START_LISTEN_SUCCEEDED)); 2502 if (SdkLevel.isAtLeastT()) { 2503 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2504 any(), eq(true), any()); 2505 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2506 any(), any(), anyInt(), anyBoolean()); 2507 } else { 2508 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2509 eq("testFeature"), anyInt(), eq(true)); 2510 } 2511 } 2512 2513 /** 2514 * Verify WifiP2pManager.STOP_LISTEN_FAILED is returned when native call failure. 2515 */ 2516 @Test testStopListenFailureWhenNativeCallFailure()2517 public void testStopListenFailureWhenNativeCallFailure() throws Exception { 2518 when(mWifiNative.p2pExtListen(eq(false), anyInt(), anyInt())).thenReturn(false); 2519 forceP2pEnabled(mClient1); 2520 sendSimpleMsg(mClientMessenger, WifiP2pManager.STOP_LISTEN); 2521 verify(mWifiNative).p2pStopFind(); 2522 verify(mWifiNative).p2pExtListen(eq(false), anyInt(), anyInt()); 2523 assertTrue(mClientHandler.hasMessages(WifiP2pManager.STOP_LISTEN_FAILED)); 2524 } 2525 2526 /** 2527 * Verify the caller with proper permission sends WifiP2pManager.STOP_LISTEN. 2528 */ 2529 @Test testStopListenSuccess()2530 public void testStopListenSuccess() throws Exception { 2531 when(mWifiNative.p2pExtListen(eq(false), anyInt(), anyInt())).thenReturn(true); 2532 forceP2pEnabled(mClient1); 2533 sendSimpleMsg(mClientMessenger, WifiP2pManager.STOP_LISTEN); 2534 verify(mWifiNative).p2pStopFind(); 2535 verify(mWifiNative).p2pExtListen(eq(false), anyInt(), anyInt()); 2536 assertTrue(mClientHandler.hasMessages(WifiP2pManager.STOP_LISTEN_SUCCEEDED)); 2537 } 2538 2539 /** Verify the p2p randomized MAC feature is enabled if OEM supports it. */ 2540 @Test testP2pRandomMacWithOemSupport()2541 public void testP2pRandomMacWithOemSupport() throws Exception { 2542 when(mResources.getBoolean(R.bool.config_wifi_p2p_mac_randomization_supported)) 2543 .thenReturn(true); 2544 forceP2pEnabled(mClient1); 2545 verify(mWifiNative, never()).setMacRandomization(eq(false)); 2546 verify(mWifiNative).setMacRandomization(eq(true)); 2547 } 2548 2549 /** Verify the p2p randomized MAC feature is disabled if OEM does not support it. */ 2550 @Test testP2pRandomMacWithoutOemSupport()2551 public void testP2pRandomMacWithoutOemSupport() throws Exception { 2552 when(mResources.getBoolean(R.bool.config_wifi_p2p_mac_randomization_supported)) 2553 .thenReturn(false); 2554 forceP2pEnabled(mClient1); 2555 verify(mWifiNative, never()).setMacRandomization(eq(true)); 2556 verify(mWifiNative).setMacRandomization(eq(false)); 2557 } 2558 2559 /** 2560 * Verify the caller sends WifiP2pManager.DELETE_PERSISTENT_GROUP. 2561 */ 2562 @Test testDeletePersistentGroupSuccess()2563 public void testDeletePersistentGroupSuccess() throws Exception { 2564 // Move to enabled state 2565 forceP2pEnabled(mClient1); 2566 2567 sendDeletePersistentGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_PERSISTENT); 2568 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2569 Message message = mMessageCaptor.getValue(); 2570 assertEquals(WifiP2pManager.DELETE_PERSISTENT_GROUP_SUCCEEDED, message.what); 2571 } 2572 2573 /** 2574 * Verify that respond with DELETE_PERSISTENT_GROUP_FAILED 2575 * when caller sends DELETE_PERSISTENT_GROUP and p2p is disabled. 2576 */ 2577 @Test testDeletePersistentGroupFailureWhenP2pDisabled()2578 public void testDeletePersistentGroupFailureWhenP2pDisabled() throws Exception { 2579 sendDeletePersistentGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_PERSISTENT); 2580 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2581 Message message = mMessageCaptor.getValue(); 2582 assertEquals(WifiP2pManager.DELETE_PERSISTENT_GROUP_FAILED, message.what); 2583 assertEquals(WifiP2pManager.BUSY, message.arg1); 2584 } 2585 2586 /** 2587 * Verify that respond with DELETE_PERSISTENT_GROUP_FAILED 2588 * when caller sends DELETE_PERSISTENT_GROUP and p2p is unsupported. 2589 */ 2590 @Test testDeletePersistentGroupFailureWhenP2pUnsupported()2591 public void testDeletePersistentGroupFailureWhenP2pUnsupported() throws Exception { 2592 setUpWifiP2pServiceImpl(false); 2593 sendDeletePersistentGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_PERSISTENT); 2594 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2595 Message message = mMessageCaptor.getValue(); 2596 assertEquals(WifiP2pManager.DELETE_PERSISTENT_GROUP_FAILED, message.what); 2597 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 2598 } 2599 2600 /** 2601 * Verify that respond with DELETE_PERSISTENT_GROUP_FAILED 2602 * when caller sends DELETE_PERSISTENT_GROUP and doesn't have the necessary permissions. 2603 */ 2604 @Test testDeletePersistentGroupFailureWhenNoPermissions()2605 public void testDeletePersistentGroupFailureWhenNoPermissions() throws Exception { 2606 // Move to enabled state 2607 forceP2pEnabled(mClient1); 2608 2609 // no permissions held 2610 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 2611 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(false); 2612 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false); 2613 2614 sendDeletePersistentGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_PERSISTENT); 2615 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 2616 Message message = mMessageCaptor.getValue(); 2617 assertEquals(WifiP2pManager.DELETE_PERSISTENT_GROUP_FAILED, message.what); 2618 assertEquals(WifiP2pManager.ERROR, message.arg1); 2619 } 2620 2621 /** 2622 * Verify the peer scan counter is increased while receiving WifiP2pManager.DISCOVER_PEERS at 2623 * P2pEnabledState. 2624 */ 2625 @Test testPeerScanMetricWhenSendDiscoverPeers()2626 public void testPeerScanMetricWhenSendDiscoverPeers() throws Exception { 2627 setTargetSdkGreaterThanT(); 2628 forceP2pEnabled(mClient1); 2629 when(mWifiNative.p2pFind(anyInt())).thenReturn(true); 2630 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2631 sendDiscoverPeersMsg(mClientMessenger); 2632 verify(mWifiP2pMetrics).incrementPeerScans(); 2633 if (SdkLevel.isAtLeastT()) { 2634 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2635 any(), eq(true), any()); 2636 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2637 any(), any(), anyInt(), anyBoolean()); 2638 } else { 2639 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2640 eq("testFeature"), anyInt(), eq(true)); 2641 } 2642 } 2643 2644 /** 2645 * Verify the service scan counter is increased while receiving 2646 * WifiP2pManager.DISCOVER_SERVICES at P2pEnabledState. 2647 */ 2648 @Test testServiceScanMetricWhenSendDiscoverServices()2649 public void testServiceScanMetricWhenSendDiscoverServices() throws Exception { 2650 setTargetSdkGreaterThanT(); 2651 when(mWifiNative.p2pServDiscReq(anyString(), anyString())) 2652 .thenReturn("mServiceDiscReqId"); 2653 when(mWifiNative.p2pFind(anyInt())).thenReturn(true); 2654 forceP2pEnabled(mClient1); 2655 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2656 sendAddServiceRequestMsg(mClientMessenger); 2657 sendDiscoverServiceMsg(mClientMessenger); 2658 verify(mWifiP2pMetrics).incrementServiceScans(); 2659 if (SdkLevel.isAtLeastT()) { 2660 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2661 any(), eq(true), any()); 2662 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2663 any(), any(), anyInt(), anyBoolean()); 2664 } else { 2665 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2666 eq("testFeature"), anyInt(), eq(true)); 2667 } 2668 } 2669 2670 /** 2671 * Verify the persistent group counter is updated while receiving 2672 * WifiP2pManager.FACTORY_RESET. 2673 */ 2674 @Test testPersistentGroupMetricWhenSendFactoryReset()2675 public void testPersistentGroupMetricWhenSendFactoryReset() throws Exception { 2676 forceP2pEnabled(mClient1); 2677 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2678 2679 // permissions for factory reset 2680 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())) 2681 .thenReturn(true); 2682 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_NETWORK_RESET), any())) 2683 .thenReturn(false); 2684 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), any())) 2685 .thenReturn(false); 2686 2687 ArgumentCaptor<WifiP2pGroupList> groupsCaptor = 2688 ArgumentCaptor.forClass(WifiP2pGroupList.class); 2689 verify(mWifiP2pMetrics).updatePersistentGroup(groupsCaptor.capture()); 2690 assertEquals(3, groupsCaptor.getValue().getGroupList().size()); 2691 2692 sendSimpleMsg(mClientMessenger, WifiP2pManager.FACTORY_RESET); 2693 2694 verify(mWifiP2pMetrics, times(2)).updatePersistentGroup(groupsCaptor.capture()); 2695 // the captured object is the same object, just get the latest one is ok. 2696 assertEquals(0, groupsCaptor.getValue().getGroupList().size()); 2697 } 2698 2699 /** 2700 * Verify the persistent group counter is updated while receiving 2701 * WifiP2pMonitor.P2P_GROUP_STARTED_EVENT. 2702 */ 2703 @Test testPersistentGroupMetricWhenSendP2pGroupStartedEvent()2704 public void testPersistentGroupMetricWhenSendP2pGroupStartedEvent() throws Exception { 2705 forceP2pEnabled(mClient1); 2706 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2707 2708 ArgumentCaptor<WifiP2pGroupList> groupsCaptor = 2709 ArgumentCaptor.forClass(WifiP2pGroupList.class); 2710 verify(mWifiP2pMetrics).updatePersistentGroup(groupsCaptor.capture()); 2711 assertEquals(3, groupsCaptor.getValue().getGroupList().size()); 2712 2713 sendGroupStartedMsg(mTestWifiP2pNewPersistentGoGroup); 2714 simulateTetherReady(); 2715 2716 verify(mWifiP2pMetrics, times(2)).updatePersistentGroup(groupsCaptor.capture()); 2717 // the captured object is the same object, just get the latest one is ok. 2718 assertEquals(4, groupsCaptor.getValue().getGroupList().size()); 2719 } 2720 2721 /** 2722 * Verify the persistent group counter is updated while receiving 2723 * WifiP2pManager.DELETE_PERSISTENT_GROUP. 2724 */ 2725 @Test testPersistentGroupMetricWhenSendDeletePersistentGroup()2726 public void testPersistentGroupMetricWhenSendDeletePersistentGroup() throws Exception { 2727 forceP2pEnabled(mClient1); 2728 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2729 2730 ArgumentCaptor<WifiP2pGroupList> groupsCaptor = 2731 ArgumentCaptor.forClass(WifiP2pGroupList.class); 2732 verify(mWifiP2pMetrics).updatePersistentGroup(groupsCaptor.capture()); 2733 assertEquals(3, groupsCaptor.getValue().getGroupList().size()); 2734 2735 sendDeletePersistentGroupMsg(mClientMessenger, 0); 2736 2737 verify(mWifiP2pMetrics, times(2)).updatePersistentGroup(groupsCaptor.capture()); 2738 // the captured object is the same object, just get the latest one is ok. 2739 assertEquals(2, groupsCaptor.getValue().getGroupList().size()); 2740 } 2741 2742 /** 2743 * Verify the group event. 2744 */ 2745 @Test testGroupEventMetric()2746 public void testGroupEventMetric() throws Exception { 2747 forceP2pEnabled(mClient1); 2748 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2749 2750 sendGroupStartedMsg(mTestWifiP2pNewPersistentGoGroup); 2751 simulateTetherReady(); 2752 2753 ArgumentCaptor<WifiP2pGroup> groupCaptor = 2754 ArgumentCaptor.forClass(WifiP2pGroup.class); 2755 verify(mWifiP2pMetrics).startGroupEvent(groupCaptor.capture()); 2756 WifiP2pGroup groupCaptured = groupCaptor.getValue(); 2757 assertEquals(mTestWifiP2pNewPersistentGoGroup.toString(), groupCaptured.toString()); 2758 2759 sendGroupRemovedMsg(); 2760 verify(mWifiP2pMetrics).endGroupEvent(); 2761 } 2762 2763 /** 2764 * Verify the connection event for a fresh connection. 2765 */ 2766 @Test testStartFreshConnectionEventWhenSendConnect()2767 public void testStartFreshConnectionEventWhenSendConnect() throws Exception { 2768 setTargetSdkGreaterThanT(); 2769 forceP2pEnabled(mClient1); 2770 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2771 2772 mockPeersList(); 2773 sendConnectMsg(mClientMessenger, mTestWifiP2pPeerConfig); 2774 if (SdkLevel.isAtLeastT()) { 2775 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2776 any(), eq(true), any()); 2777 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2778 any(), any(), anyInt(), anyBoolean()); 2779 } else { 2780 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2781 eq("testFeature"), anyInt(), eq(false)); 2782 } 2783 2784 ArgumentCaptor<WifiP2pConfig> configCaptor = 2785 ArgumentCaptor.forClass(WifiP2pConfig.class); 2786 verify(mWifiP2pMetrics).startConnectionEvent( 2787 eq(P2pConnectionEvent.CONNECTION_FRESH), 2788 configCaptor.capture(), 2789 eq(WifiMetricsProto.GroupEvent.GROUP_UNKNOWN)); 2790 assertEquals(mTestWifiP2pPeerConfig.toString(), configCaptor.getValue().toString()); 2791 } 2792 2793 /** 2794 * Verify the connection event for a reinvoked connection. 2795 */ 2796 @Test testStartReinvokeConnectionEventWhenSendConnect()2797 public void testStartReinvokeConnectionEventWhenSendConnect() throws Exception { 2798 setTargetSdkGreaterThanT(); 2799 forceP2pEnabled(mClient1); 2800 when(mWifiNative.p2pGroupAdd(anyInt())) 2801 .thenReturn(true); 2802 when(mTestWifiP2pDevice.isGroupOwner()).thenReturn(true); 2803 when(mWifiNative.p2pGetSsid(eq(mTestWifiP2pDevice.deviceAddress))) 2804 .thenReturn(mTestWifiP2pGroup.getNetworkName()); 2805 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2806 2807 mockPeersList(); 2808 sendConnectMsg(mClientMessenger, mTestWifiP2pPeerConfig); 2809 if (SdkLevel.isAtLeastT()) { 2810 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2811 any(), eq(true), any()); 2812 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2813 any(), any(), anyInt(), anyBoolean()); 2814 } else { 2815 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2816 eq("testFeature"), anyInt(), eq(false)); 2817 } 2818 2819 ArgumentCaptor<WifiP2pConfig> configCaptor = 2820 ArgumentCaptor.forClass(WifiP2pConfig.class); 2821 verify(mWifiP2pMetrics).startConnectionEvent( 2822 eq(P2pConnectionEvent.CONNECTION_REINVOKE), 2823 configCaptor.capture(), 2824 eq(WifiMetricsProto.GroupEvent.GROUP_UNKNOWN)); 2825 assertEquals(mTestWifiP2pPeerConfig.toString(), configCaptor.getValue().toString()); 2826 } 2827 2828 /** 2829 * Verify the connection event for a reinvoked connection via 2830 * createGroup API. 2831 * 2832 * If there is a persistent group whose owner is this deivce, this would be 2833 * a reinvoked group. 2834 */ 2835 @Test testStartReinvokeConnectionEventWhenCreateGroup()2836 public void testStartReinvokeConnectionEventWhenCreateGroup() 2837 throws Exception { 2838 setTargetSdkGreaterThanT(); 2839 forceP2pEnabled(mClient1); 2840 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2841 2842 sendCreateGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_PERSISTENT, null); 2843 if (SdkLevel.isAtLeastT()) { 2844 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2845 any(), eq(true), any()); 2846 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2847 any(), any(), anyInt(), anyBoolean()); 2848 } else { 2849 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 2850 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 2851 } 2852 2853 verify(mWifiP2pMetrics).startConnectionEvent( 2854 eq(P2pConnectionEvent.CONNECTION_REINVOKE), 2855 eq(null), 2856 eq(WifiMetricsProto.GroupEvent.GROUP_OWNER)); 2857 } 2858 2859 /** 2860 * Verify the connection event for a local connection while setting 2861 * netId to {@link WifiP2pGroup#NETWORK_ID_PERSISTENT}. 2862 */ 2863 @Test testStartLocalConnectionWhenCreateGroup()2864 public void testStartLocalConnectionWhenCreateGroup() throws Exception { 2865 setTargetSdkGreaterThanT(); 2866 forceP2pEnabled(mClient1); 2867 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2868 2869 // permissions for factory reset 2870 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())) 2871 .thenReturn(true); 2872 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_NETWORK_RESET), any())) 2873 .thenReturn(false); 2874 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), any())) 2875 .thenReturn(false); 2876 2877 // There is one group hosted by this device in mGroups. 2878 // clear all groups to avoid re-invoking a group. 2879 sendSimpleMsg(mClientMessenger, WifiP2pManager.FACTORY_RESET); 2880 2881 sendCreateGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_PERSISTENT, null); 2882 if (SdkLevel.isAtLeastT()) { 2883 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2884 any(), eq(true), any()); 2885 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2886 any(), any(), anyInt(), anyBoolean()); 2887 } else { 2888 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 2889 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 2890 } 2891 2892 verify(mWifiP2pMetrics).startConnectionEvent( 2893 eq(P2pConnectionEvent.CONNECTION_LOCAL), 2894 eq(null), 2895 eq(WifiMetricsProto.GroupEvent.GROUP_OWNER)); 2896 } 2897 2898 /** 2899 * Verify the connection event for a local connection while setting the 2900 * netId to {@link WifiP2pGroup#NETWORK_ID_TEMPORARY}. 2901 */ 2902 @Test testStartLocalConnectionEventWhenCreateTemporaryGroup()2903 public void testStartLocalConnectionEventWhenCreateTemporaryGroup() throws Exception { 2904 setTargetSdkGreaterThanT(); 2905 forceP2pEnabled(mClient1); 2906 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2907 2908 sendCreateGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_TEMPORARY, null); 2909 if (SdkLevel.isAtLeastT()) { 2910 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2911 any(), eq(true), any()); 2912 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2913 any(), any(), anyInt(), anyBoolean()); 2914 } else { 2915 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 2916 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 2917 } 2918 2919 verify(mWifiP2pMetrics).startConnectionEvent( 2920 eq(P2pConnectionEvent.CONNECTION_LOCAL), 2921 eq(null), 2922 eq(WifiMetricsProto.GroupEvent.GROUP_OWNER)); 2923 } 2924 2925 /** 2926 * Verify the connection event for a fast connection via 2927 * connect with config. 2928 */ 2929 @Test testStartFastConnectionEventWhenSendConnectWithConfig()2930 public void testStartFastConnectionEventWhenSendConnectWithConfig() 2931 throws Exception { 2932 setTargetSdkGreaterThanT(); 2933 forceP2pEnabled(mClient1); 2934 when(mWifiNative.p2pGroupAdd(any(), eq(true))).thenReturn(true); 2935 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2936 2937 sendConnectMsg(mClientMessenger, mTestWifiP2pFastConnectionConfig); 2938 if (SdkLevel.isAtLeastT()) { 2939 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2940 any(), eq(true), any()); 2941 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2942 any(), any(), anyInt(), anyBoolean()); 2943 } else { 2944 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 2945 eq("testFeature"), anyInt(), eq(false)); 2946 } 2947 2948 ArgumentCaptor<WifiP2pConfig> configCaptor = 2949 ArgumentCaptor.forClass(WifiP2pConfig.class); 2950 verify(mWifiP2pMetrics).startConnectionEvent( 2951 eq(P2pConnectionEvent.CONNECTION_FAST), 2952 configCaptor.capture(), 2953 eq(WifiMetricsProto.GroupEvent.GROUP_CLIENT)); 2954 assertEquals(mTestWifiP2pFastConnectionConfig.toString(), 2955 configCaptor.getValue().toString()); 2956 } 2957 2958 /** 2959 * Verify the connection event for a fast connection via 2960 * createGroup API with config. 2961 */ 2962 @Test testStartFastConnectionEventWhenCreateGroupWithConfig()2963 public void testStartFastConnectionEventWhenCreateGroupWithConfig() 2964 throws Exception { 2965 setTargetSdkGreaterThanT(); 2966 forceP2pEnabled(mClient1); 2967 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2968 2969 sendCreateGroupMsg(mClientMessenger, 0, mTestWifiP2pFastConnectionConfig); 2970 if (SdkLevel.isAtLeastT()) { 2971 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 2972 any(), eq(true), any()); 2973 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 2974 any(), any(), anyInt(), anyBoolean()); 2975 } else { 2976 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 2977 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 2978 } 2979 2980 ArgumentCaptor<WifiP2pConfig> configCaptor = 2981 ArgumentCaptor.forClass(WifiP2pConfig.class); 2982 verify(mWifiP2pMetrics).startConnectionEvent( 2983 eq(P2pConnectionEvent.CONNECTION_FAST), 2984 configCaptor.capture(), 2985 eq(WifiMetricsProto.GroupEvent.GROUP_OWNER)); 2986 assertEquals(mTestWifiP2pFastConnectionConfig.toString(), 2987 configCaptor.getValue().toString()); 2988 } 2989 2990 /** 2991 * Verify the connection event ends while the group is formed. 2992 */ 2993 @Test testEndConnectionEventWhenGroupFormed()2994 public void testEndConnectionEventWhenGroupFormed() throws Exception { 2995 forceP2pEnabled(mClient1); 2996 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 2997 2998 WifiP2pGroup group = new WifiP2pGroup(); 2999 group.setNetworkId(WifiP2pGroup.NETWORK_ID_PERSISTENT); 3000 group.setNetworkName("DIRECT-xy-NEW"); 3001 group.setOwner(new WifiP2pDevice("thisDeviceMac")); 3002 group.setIsGroupOwner(true); 3003 group.setInterface(IFACE_NAME_P2P); 3004 sendGroupStartedMsg(group); 3005 simulateTetherReady(); 3006 verify(mWifiP2pMetrics).endConnectionEvent( 3007 eq(P2pConnectionEvent.CLF_NONE)); 3008 } 3009 3010 /** 3011 * Verify the connection event ends due to timeout. 3012 */ 3013 @Test testEndConnectionEventWhenTimeout()3014 public void testEndConnectionEventWhenTimeout() throws Exception { 3015 setTargetSdkGreaterThanT(); 3016 forceP2pEnabled(mClient1); 3017 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 3018 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3019 3020 mockEnterGroupNegotiationState(); 3021 if (SdkLevel.isAtLeastT()) { 3022 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3023 any(), eq(true), any()); 3024 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3025 any(), any(), anyInt(), anyBoolean()); 3026 } else { 3027 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3028 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3029 } 3030 3031 mLooper.moveTimeForward(120 * 1000 * 2); 3032 mLooper.dispatchAll(); 3033 3034 verify(mWifiP2pMetrics).endConnectionEvent( 3035 eq(P2pConnectionEvent.CLF_TIMEOUT)); 3036 } 3037 3038 /** 3039 * Verify accepting the frequency conflict dialog will send a disconnect wifi request. 3040 */ 3041 @Test testAcceptFrequencyConflictDialogSendsDisconnectWifiRequest()3042 public void testAcceptFrequencyConflictDialogSendsDisconnectWifiRequest() throws Exception { 3043 forceP2pEnabled(mClient1); 3044 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 3045 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3046 AsyncChannel wifiChannel = mAsyncChannel; 3047 sendChannelHalfConnectedEvent(mClientMessenger, wifiChannel); 3048 WifiDialogManager.DialogHandle dialogHandle = mock(WifiDialogManager.DialogHandle.class); 3049 when(mWifiDialogManager.createSimpleDialog( 3050 any(), any(), any(), any(), any(), any(), any())).thenReturn(dialogHandle); 3051 ArgumentCaptor<WifiDialogManager.SimpleDialogCallback> callbackCaptor = 3052 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class); 3053 3054 mockEnterGroupNegotiationState(); 3055 mockPeersList(); 3056 sendSetOngoingPeerConfigMsg(mClientMessenger, mTestWifiP2pPeerConfig); 3057 mLooper.dispatchAll(); 3058 sendGoNegotiationFailureEvent(mClientMessenger, 3059 WifiP2pServiceImpl.P2pStatus.NO_COMMON_CHANNEL); 3060 3061 if (!SdkLevel.isAtLeastT()) { 3062 verify(mAlertDialog).show(); 3063 ArgumentCaptor<DialogInterface.OnClickListener> clickListener = ArgumentCaptor.forClass( 3064 DialogInterface.OnClickListener.class); 3065 verify(mAlertDialogBuilder).setPositiveButton(any(), clickListener.capture()); 3066 clickListener.getValue().onClick(mAlertDialog, DialogInterface.BUTTON_POSITIVE); 3067 } else { 3068 verify(mWifiDialogManager).createSimpleDialog( 3069 any(), any(), any(), any(), any(), callbackCaptor.capture(), any()); 3070 verify(dialogHandle).launchDialog(); 3071 callbackCaptor.getValue().onPositiveButtonClicked(); 3072 } 3073 mLooper.dispatchAll(); 3074 verify(wifiChannel).sendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST, 1); 3075 } 3076 3077 /** 3078 * Verify DISCONNECT_WIFI_REQUEST is cleared when cancelConnect() is called. 3079 */ 3080 @Test testClearDisconnectWifiRequestOnCallCancelConnect()3081 public void testClearDisconnectWifiRequestOnCallCancelConnect() throws Exception { 3082 // accept the frequency conflict dialog to start next try. 3083 testAcceptFrequencyConflictDialogSendsDisconnectWifiRequest(); 3084 3085 reset(mAsyncChannel); 3086 sendSimpleMsg(mClientMessenger, WifiP2pManager.CANCEL_CONNECT); 3087 verify(mAsyncChannel).sendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST, 0); 3088 } 3089 3090 /** 3091 * Verify DISCONNECT_WIFI_REQUEST is cleared when group formation fails. 3092 */ 3093 @Test testClearDisconnectWifiRequestWhenGroupFormationFails()3094 public void testClearDisconnectWifiRequestWhenGroupFormationFails() throws Exception { 3095 // accept the frequency conflict dialog to start next try. 3096 testAcceptFrequencyConflictDialogSendsDisconnectWifiRequest(); 3097 3098 reset(mAsyncChannel); 3099 // Send a reject to trigger handleGroupCreationFailure(). 3100 sendSimpleMsg(mClientMessenger, WifiP2pServiceImpl.DROP_WIFI_USER_REJECT); 3101 verify(mAsyncChannel).sendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST, 0); 3102 } 3103 3104 /** 3105 * Verify declining the frequency conflict dialog will end the P2P connection event. 3106 */ 3107 @Test testDeclineFrequencyConflictDialogEndsP2pConnectionEvent()3108 public void testDeclineFrequencyConflictDialogEndsP2pConnectionEvent() throws Exception { 3109 forceP2pEnabled(mClient1); 3110 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 3111 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3112 AsyncChannel wifiChannel = mock(AsyncChannel.class); 3113 sendChannelHalfConnectedEvent(mClientMessenger, wifiChannel); 3114 WifiDialogManager.DialogHandle dialogHandle = mock(WifiDialogManager.DialogHandle.class); 3115 when(mWifiDialogManager.createSimpleDialog( 3116 any(), any(), any(), any(), any(), any(), any())).thenReturn(dialogHandle); 3117 ArgumentCaptor<WifiDialogManager.SimpleDialogCallback> callbackCaptor = 3118 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class); 3119 3120 mockEnterGroupNegotiationState(); 3121 mockPeersList(); 3122 sendSetOngoingPeerConfigMsg(mClientMessenger, mTestWifiP2pPeerConfig); 3123 mLooper.dispatchAll(); 3124 sendGoNegotiationFailureEvent(mClientMessenger, 3125 WifiP2pServiceImpl.P2pStatus.NO_COMMON_CHANNEL); 3126 3127 if (!SdkLevel.isAtLeastT()) { 3128 verify(mAlertDialog).show(); 3129 ArgumentCaptor<DialogInterface.OnClickListener> clickListener = ArgumentCaptor.forClass( 3130 DialogInterface.OnClickListener.class); 3131 verify(mAlertDialogBuilder).setNegativeButton(any(), clickListener.capture()); 3132 clickListener.getValue().onClick(mAlertDialog, DialogInterface.BUTTON_NEGATIVE); 3133 } else { 3134 verify(mWifiDialogManager).createSimpleDialog( 3135 any(), any(), any(), any(), any(), callbackCaptor.capture(), any()); 3136 verify(dialogHandle).launchDialog(); 3137 callbackCaptor.getValue().onNegativeButtonClicked(); 3138 3139 } 3140 mLooper.dispatchAll(); 3141 verify(mWifiP2pMetrics).endConnectionEvent(P2pConnectionEvent.CLF_USER_REJECT); 3142 } 3143 3144 /** 3145 * Verify the frequency conflict dialog is dismissed when the frequency conflict state exits. 3146 */ 3147 @Test testFrequencyConflictDialogDismissedOnStateExit()3148 public void testFrequencyConflictDialogDismissedOnStateExit() throws Exception { 3149 forceP2pEnabled(mClient1); 3150 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 3151 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3152 AsyncChannel wifiChannel = mock(AsyncChannel.class); 3153 sendChannelHalfConnectedEvent(mClientMessenger, wifiChannel); 3154 WifiDialogManager.DialogHandle dialogHandle = mock(WifiDialogManager.DialogHandle.class); 3155 when(mWifiDialogManager.createSimpleDialog( 3156 any(), any(), any(), any(), any(), any(), any())).thenReturn(dialogHandle); 3157 ArgumentCaptor<WifiDialogManager.SimpleDialogCallback> callbackCaptor = 3158 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class); 3159 3160 mockEnterGroupNegotiationState(); 3161 mockPeersList(); 3162 sendSetOngoingPeerConfigMsg(mClientMessenger, mTestWifiP2pPeerConfig); 3163 mLooper.dispatchAll(); 3164 sendGoNegotiationFailureEvent(mClientMessenger, 3165 WifiP2pServiceImpl.P2pStatus.NO_COMMON_CHANNEL); 3166 WifiP2pGroup group = new WifiP2pGroup(); 3167 group.setNetworkId(WifiP2pGroup.NETWORK_ID_PERSISTENT); 3168 group.setNetworkName("DIRECT-xy-NEW"); 3169 group.setOwner(new WifiP2pDevice("thisDeviceMac")); 3170 group.setIsGroupOwner(true); 3171 group.setInterface(IFACE_NAME_P2P); 3172 sendGroupStartedMsg(group); 3173 3174 if (!SdkLevel.isAtLeastT()) { 3175 verify(mAlertDialog).show(); 3176 verify(mAlertDialog).dismiss(); 3177 } else { 3178 verify(mWifiDialogManager).createSimpleDialog( 3179 any(), any(), any(), any(), any(), callbackCaptor.capture(), any()); 3180 verify(dialogHandle).launchDialog(); 3181 verify(dialogHandle).dismissDialog(); 3182 } 3183 } 3184 3185 /** 3186 * Verify the connection event ends due to the cancellation. 3187 */ 3188 @Test testEndConnectionEventWhenCancel()3189 public void testEndConnectionEventWhenCancel() throws Exception { 3190 setTargetSdkGreaterThanT(); 3191 forceP2pEnabled(mClient1); 3192 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 3193 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3194 3195 mockEnterGroupNegotiationState(); 3196 if (SdkLevel.isAtLeastT()) { 3197 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3198 any(), eq(true), any()); 3199 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3200 any(), any(), anyInt(), anyBoolean()); 3201 } else { 3202 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3203 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3204 } 3205 3206 sendSimpleMsg(mClientMessenger, WifiP2pManager.CANCEL_CONNECT); 3207 3208 verify(mWifiP2pMetrics).endConnectionEvent( 3209 eq(P2pConnectionEvent.CLF_CANCEL)); 3210 } 3211 3212 /** 3213 * Verify the connection event ends due to the provision discovery failure. 3214 */ 3215 @Test testEndConnectionEventWhenProvDiscFailure()3216 public void testEndConnectionEventWhenProvDiscFailure() throws Exception { 3217 setTargetSdkGreaterThanT(); 3218 forceP2pEnabled(mClient1); 3219 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 3220 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3221 3222 mockEnterProvisionDiscoveryState(); 3223 if (SdkLevel.isAtLeastT()) { 3224 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3225 any(), eq(true), any()); 3226 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3227 any(), any(), anyInt(), anyBoolean()); 3228 } else { 3229 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3230 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3231 } 3232 WifiP2pProvDiscEvent pdEvent = new WifiP2pProvDiscEvent(); 3233 pdEvent.device.deviceAddress = mTestWifiP2pPeerConfig.deviceAddress; 3234 3235 sendSimpleMsg(null, WifiP2pMonitor.P2P_PROV_DISC_FAILURE_EVENT, 3236 WifiP2pMonitor.PROV_DISC_STATUS_UNKNOWN, pdEvent); 3237 3238 verify(mWifiP2pMetrics).endConnectionEvent( 3239 eq(P2pConnectionEvent.CLF_PROV_DISC_FAIL)); 3240 } 3241 3242 /** 3243 * Verify the connection event ends due to the group removal. 3244 */ 3245 @Test testEndConnectionEventWhenGroupRemoval()3246 public void testEndConnectionEventWhenGroupRemoval() throws Exception { 3247 setTargetSdkGreaterThanT(); 3248 forceP2pEnabled(mClient1); 3249 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 3250 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3251 3252 mockEnterGroupNegotiationState(); 3253 if (SdkLevel.isAtLeastT()) { 3254 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3255 any(), eq(true), any()); 3256 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3257 any(), any(), anyInt(), anyBoolean()); 3258 } else { 3259 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3260 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3261 } 3262 3263 sendSimpleMsg(null, WifiP2pMonitor.P2P_GROUP_REMOVED_EVENT); 3264 verify(mContext).sendBroadcastWithMultiplePermissions( 3265 argThat(new WifiP2pServiceImplTest 3266 .P2pConnectionChangedIntentMatcherForNetworkState(FAILED)), any()); 3267 if (SdkLevel.isAtLeastT()) { 3268 verify(mContext).sendBroadcast( 3269 argThat(new WifiP2pServiceImplTest 3270 .P2pConnectionChangedIntentMatcherForNetworkState(FAILED)), any(), 3271 any()); 3272 verify(mBroadcastOptions, atLeastOnce()) 3273 .setRequireAllOfPermissions(TEST_REQUIRED_PERMISSIONS_T); 3274 verify(mBroadcastOptions, atLeastOnce()) 3275 .setRequireNoneOfPermissions(TEST_EXCLUDED_PERMISSIONS_T); 3276 } 3277 3278 verify(mWifiP2pMetrics).endConnectionEvent(eq(P2pConnectionEvent.CLF_UNKNOWN)); 3279 } 3280 3281 @Test testStartP2pLocationOn()3282 public void testStartP2pLocationOn() throws Exception { 3283 assumeTrue(SdkLevel.isAtLeastT()); 3284 simulateLocationModeChange(true); 3285 simulateWifiStateChange(true); 3286 checkIsP2pInitWhenClientConnected(true, mClient1, 3287 new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME)); 3288 3289 verify(mBroadcastOptions, atLeastOnce()) 3290 .setRequireAllOfPermissions(TEST_REQUIRED_PERMISSIONS_T); 3291 verify(mBroadcastOptions, atLeastOnce()) 3292 .setRequireNoneOfPermissions(TEST_EXCLUDED_PERMISSIONS_T); 3293 } 3294 3295 @Test testStartP2pLocationOff()3296 public void testStartP2pLocationOff() throws Exception { 3297 assumeTrue(SdkLevel.isAtLeastT()); 3298 simulateLocationModeChange(false); 3299 simulateWifiStateChange(true); 3300 checkIsP2pInitWhenClientConnected(true, mClient1, 3301 new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME)); 3302 3303 verify(mBroadcastOptions, atLeastOnce()) 3304 .setRequireAllOfPermissions(TEST_REQUIRED_PERMISSIONS_T); 3305 verify(mBroadcastOptions, never()).setRequireNoneOfPermissions(TEST_EXCLUDED_PERMISSIONS_T); 3306 } 3307 3308 /** 3309 * Verify the connection event ends due to the invitation failure. 3310 */ 3311 @Test testEndConnectionEventWhenInvitationFailure()3312 public void testEndConnectionEventWhenInvitationFailure() throws Exception { 3313 setTargetSdkGreaterThanT(); 3314 forceP2pEnabled(mClient1); 3315 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 3316 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3317 3318 mockEnterGroupNegotiationState(); 3319 if (SdkLevel.isAtLeastT()) { 3320 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3321 any(), eq(true), any()); 3322 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3323 any(), any(), anyInt(), anyBoolean()); 3324 } else { 3325 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3326 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3327 } 3328 3329 sendInvitationResultMsg(WifiP2pServiceImpl.P2pStatus.UNKNOWN); 3330 3331 verify(mWifiP2pMetrics).endConnectionEvent( 3332 eq(P2pConnectionEvent.CLF_INVITATION_FAIL)); 3333 } 3334 3335 /** 3336 * Verify WifiP2pManager.RESPONSE_DEVICE_INFO is returned with null object when a caller 3337 * without proper permission attempts. 3338 */ 3339 @Test testRequestDeviceInfoFailureWhenPermissionDenied()3340 public void testRequestDeviceInfoFailureWhenPermissionDenied() throws Exception { 3341 setTargetSdkGreaterThanT(); 3342 forceP2pEnabled(mClient1); 3343 doNothing().when(mWifiPermissionsUtil).checkPackage(anyInt(), anyString()); 3344 if (SdkLevel.isAtLeastT()) { 3345 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 3346 .thenReturn(false); 3347 } else { 3348 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), anyInt(), 3349 anyBoolean())).thenReturn(false); 3350 } 3351 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3352 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DEVICE_INFO); 3353 if (SdkLevel.isAtLeastT()) { 3354 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3355 any(), eq(true), any()); 3356 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3357 any(), any(), anyInt(), anyBoolean()); 3358 } else { 3359 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3360 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3361 } 3362 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3363 assertEquals(WifiP2pManager.RESPONSE_DEVICE_INFO, mMessageCaptor.getValue().what); 3364 assertNull(mMessageCaptor.getValue().obj); 3365 } 3366 3367 /** 3368 * Verify WifiP2pManager.RESPONSE_DEVICE_INFO is returned with expect object when a caller 3369 * with proper permission attempts in p2p enabled state. 3370 */ 3371 @Test testRequestDeviceInfoSuccessWhenP2pEnabled()3372 public void testRequestDeviceInfoSuccessWhenP2pEnabled() throws Exception { 3373 setTargetSdkGreaterThanT(); 3374 forceP2pEnabled(mClient1); 3375 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3376 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DEVICE_INFO); 3377 if (SdkLevel.isAtLeastT()) { 3378 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3379 any(), eq(true), any()); 3380 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3381 any(), any(), anyInt(), anyBoolean()); 3382 } else { 3383 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3384 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3385 } 3386 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3387 assertEquals(WifiP2pManager.RESPONSE_DEVICE_INFO, mMessageCaptor.getValue().what); 3388 WifiP2pDevice wifiP2pDevice = (WifiP2pDevice) mMessageCaptor.getValue().obj; 3389 assertEquals(ANONYMIZED_DEVICE_ADDRESS, wifiP2pDevice.deviceAddress); 3390 assertEquals(thisDeviceName, wifiP2pDevice.deviceName); 3391 } 3392 3393 /** 3394 * Verify WifiP2pManager.RESPONSE_DEVICE_INFO is returned with empty object when a caller 3395 * with proper permission attempts in p2p disabled state. 3396 */ 3397 @Test testRequestDeviceInfoReturnEmptyWifiP2pDeviceWhenP2pDisabled()3398 public void testRequestDeviceInfoReturnEmptyWifiP2pDeviceWhenP2pDisabled() throws Exception { 3399 setTargetSdkGreaterThanT(); 3400 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3401 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DEVICE_INFO); 3402 if (SdkLevel.isAtLeastT()) { 3403 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3404 any(), eq(true), any()); 3405 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3406 any(), any(), anyInt(), anyBoolean()); 3407 } else { 3408 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3409 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3410 } 3411 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3412 assertEquals(WifiP2pManager.RESPONSE_DEVICE_INFO, mMessageCaptor.getValue().what); 3413 WifiP2pDevice wifiP2pDevice = (WifiP2pDevice) mMessageCaptor.getValue().obj; 3414 assertEquals("", wifiP2pDevice.deviceAddress); 3415 assertEquals("", wifiP2pDevice.deviceName); 3416 } 3417 3418 /** 3419 * Verify WifiP2pManager.RESPONSE_DEVICE_INFO returns an object with the actual device MAC when 3420 * the caller holds the LOCAL_MAC_ADDRESS permission. 3421 */ 3422 @Test testRequestDeviceInfoReturnsActualMacForNetworkSettingsApp()3423 public void testRequestDeviceInfoReturnsActualMacForNetworkSettingsApp() throws Exception { 3424 setTargetSdkGreaterThanT(); 3425 forceP2pEnabled(mClient1); 3426 when(mWifiPermissionsUtil.checkLocalMacAddressPermission(anyInt())).thenReturn(true); 3427 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3428 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DEVICE_INFO); 3429 if (SdkLevel.isAtLeastT()) { 3430 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 3431 any(), eq(true), any()); 3432 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 3433 any(), any(), anyInt(), anyBoolean()); 3434 } else { 3435 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 3436 eq("testPkg1"), eq("testFeature"), anyInt(), eq(false)); 3437 } 3438 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3439 assertEquals(WifiP2pManager.RESPONSE_DEVICE_INFO, mMessageCaptor.getValue().what); 3440 WifiP2pDevice wifiP2pDevice = (WifiP2pDevice) mMessageCaptor.getValue().obj; 3441 assertEquals(thisDeviceMac, wifiP2pDevice.deviceAddress); 3442 assertEquals(thisDeviceName, wifiP2pDevice.deviceName); 3443 } 3444 verifyCustomizeDefaultDeviceName(String expectedName, boolean isRandomPostfix)3445 private String verifyCustomizeDefaultDeviceName(String expectedName, boolean isRandomPostfix) 3446 throws Exception { 3447 forceP2pEnabled(mClient1); 3448 when(mWifiPermissionsUtil.checkLocalMacAddressPermission(anyInt())).thenReturn(true); 3449 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 3450 3451 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DEVICE_INFO); 3452 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3453 assertEquals(WifiP2pManager.RESPONSE_DEVICE_INFO, mMessageCaptor.getValue().what); 3454 3455 WifiP2pDevice wifiP2pDevice = (WifiP2pDevice) mMessageCaptor.getValue().obj; 3456 if (isRandomPostfix) { 3457 assertEquals(expectedName, 3458 wifiP2pDevice.deviceName.substring(0, expectedName.length())); 3459 } else { 3460 assertEquals(expectedName, wifiP2pDevice.deviceName); 3461 } 3462 return wifiP2pDevice.deviceName; 3463 } 3464 setupDefaultDeviceNameCustomization( String prefix, int postfixDigit)3465 private void setupDefaultDeviceNameCustomization( 3466 String prefix, int postfixDigit) { 3467 when(mWifiSettingsConfigStore.get(eq(WIFI_P2P_DEVICE_NAME))).thenReturn(null); 3468 when(mFrameworkFacade.getSecureStringSetting(any(), eq(Settings.Secure.ANDROID_ID))) 3469 .thenReturn(TEST_ANDROID_ID); 3470 when(mWifiGlobals.getWifiP2pDeviceNamePrefix()).thenReturn(prefix); 3471 when(mWifiGlobals.getWifiP2pDeviceNamePostfixNumDigits()).thenReturn(postfixDigit); 3472 } 3473 3474 /** Verify that the default device name is customized by overlay on S or older. */ 3475 @Test testCustomizeDefaultDeviceNameOnSorOlder()3476 public void testCustomizeDefaultDeviceNameOnSorOlder() throws Exception { 3477 assumeFalse(SdkLevel.isAtLeastT()); 3478 setupDefaultDeviceNameCustomization("Niceboat-", -1); 3479 verifyCustomizeDefaultDeviceName("Niceboat-" + TEST_ANDROID_ID.substring(0, 4), false); 3480 } 3481 3482 /** Verify that the default device name is customized by overlay. */ 3483 @Test testCustomizeDefaultDeviceName()3484 public void testCustomizeDefaultDeviceName() throws Exception { 3485 assumeTrue(SdkLevel.isAtLeastT()); 3486 setupDefaultDeviceNameCustomization("Niceboat-", -1); 3487 verifyCustomizeDefaultDeviceName("Niceboat-", true); 3488 } 3489 3490 /** Verify that the prefix fallback to Android_ if the prefix is too long. */ 3491 @Test testCustomizeDefaultDeviceNameTooLongPrefix()3492 public void testCustomizeDefaultDeviceNameTooLongPrefix() throws Exception { 3493 setupDefaultDeviceNameCustomization( 3494 StringUtil.generateRandomNumberString( 3495 WifiP2pServiceImpl.DEVICE_NAME_PREFIX_LENGTH_MAX + 1), 4); 3496 verifyCustomizeDefaultDeviceName(WifiP2pServiceImpl.DEFAULT_DEVICE_NAME_PREFIX, true); 3497 } 3498 3499 /** Verify that the prefix fallback to Android_ if the prefix is empty. */ 3500 @Test testCustomizeDefaultDeviceNameEmptyPrefix()3501 public void testCustomizeDefaultDeviceNameEmptyPrefix() throws Exception { 3502 setupDefaultDeviceNameCustomization("", 6); 3503 verifyCustomizeDefaultDeviceName(WifiP2pServiceImpl.DEFAULT_DEVICE_NAME_PREFIX, true); 3504 } 3505 3506 /** Verify that the postfix fallbacks to 4-digit ANDROID_ID if the length is smaller than 4. */ 3507 @Test testCustomizeDefaultDeviceNamePostfixTooShortOnSorOlder()3508 public void testCustomizeDefaultDeviceNamePostfixTooShortOnSorOlder() throws Exception { 3509 assumeFalse(SdkLevel.isAtLeastT()); 3510 setupDefaultDeviceNameCustomization("Prefix", 3511 WifiP2pServiceImpl.DEVICE_NAME_POSTFIX_LENGTH_MIN - 1); 3512 verifyCustomizeDefaultDeviceName("Prefix" + TEST_ANDROID_ID.substring(0, 4), true); 3513 } 3514 3515 /** Verify that the postfix fallbacks to 4-digit ANDROID_ID if the length is smaller than 4. */ 3516 @Test testCustomizeDefaultDeviceNamePostfixTooShort()3517 public void testCustomizeDefaultDeviceNamePostfixTooShort() throws Exception { 3518 assumeTrue(SdkLevel.isAtLeastT()); 3519 setupDefaultDeviceNameCustomization("Prefix", 3520 WifiP2pServiceImpl.DEVICE_NAME_POSTFIX_LENGTH_MIN - 1); 3521 verifyCustomizeDefaultDeviceName("Prefix", true); 3522 } 3523 3524 /** Verify that the postfix fallbacks to 4-digit ANDROID_ID if the length is 0.*/ 3525 @Test testCustomizeDefaultDeviceNamePostfixIsZeroLengthOnSorOlder()3526 public void testCustomizeDefaultDeviceNamePostfixIsZeroLengthOnSorOlder() throws Exception { 3527 assumeFalse(SdkLevel.isAtLeastT()); 3528 setupDefaultDeviceNameCustomization("Prefix", 0); 3529 verifyCustomizeDefaultDeviceName("Prefix" + TEST_ANDROID_ID.substring(0, 4), true); 3530 } 3531 3532 /** Verify that the postfix fallbacks to 4-digit ANDROID_ID if the length is 0.*/ 3533 @Test testCustomizeDefaultDeviceNamePostfixIsZeroLength()3534 public void testCustomizeDefaultDeviceNamePostfixIsZeroLength() throws Exception { 3535 assumeTrue(SdkLevel.isAtLeastT()); 3536 setupDefaultDeviceNameCustomization("Prefix", 0); 3537 verifyCustomizeDefaultDeviceName("Prefix", true); 3538 } 3539 3540 /** Verify that the digit length exceeds the remaining bytes. */ 3541 @Test testCustomizeDefaultDeviceNameWithFewerRemainingBytes()3542 public void testCustomizeDefaultDeviceNameWithFewerRemainingBytes() throws Exception { 3543 int postfixLength = 6; 3544 String prefix = StringUtil.generateRandomNumberString( 3545 WifiP2pServiceImpl.DEVICE_NAME_LENGTH_MAX - postfixLength + 1); 3546 setupDefaultDeviceNameCustomization(prefix, postfixLength); 3547 verifyCustomizeDefaultDeviceName(prefix, true); 3548 } 3549 3550 /** Verify that the default device name is customized by overlay 3551 * when saved one is an empty string. */ 3552 @Test testCustomizeDefaultDeviceNameWithEmptySavedNameOnSorOlder()3553 public void testCustomizeDefaultDeviceNameWithEmptySavedNameOnSorOlder() throws Exception { 3554 assumeFalse(SdkLevel.isAtLeastT()); 3555 setupDefaultDeviceNameCustomization("Niceboat-", -1); 3556 when(mWifiSettingsConfigStore.get(eq(WIFI_P2P_DEVICE_NAME))).thenReturn(""); 3557 verifyCustomizeDefaultDeviceName("Niceboat-" + TEST_ANDROID_ID.substring(0, 4), false); 3558 } 3559 3560 /** Verify that the default device name is customized by overlay 3561 * when saved one is an empty string. */ 3562 @Test testCustomizeDefaultDeviceNameWithEmptySavedName()3563 public void testCustomizeDefaultDeviceNameWithEmptySavedName() throws Exception { 3564 assumeTrue(SdkLevel.isAtLeastT()); 3565 setupDefaultDeviceNameCustomization("Niceboat-", -1); 3566 when(mWifiSettingsConfigStore.get(eq(WIFI_P2P_DEVICE_NAME))).thenReturn(""); 3567 verifyCustomizeDefaultDeviceName("Niceboat-", true); 3568 } 3569 3570 /** Verify that the default device name is preserved in a period. */ 3571 @Test testCustomizeDefaultDeviceNameIsPreserved()3572 public void testCustomizeDefaultDeviceNameIsPreserved() throws Exception { 3573 when(mClock.getElapsedSinceBootMillis()).thenReturn(0L); 3574 3575 setupDefaultDeviceNameCustomization("Niceboat-", 4); 3576 String defaultDeviceName = verifyCustomizeDefaultDeviceName("Niceboat-", true); 3577 3578 // re-init P2P, and the default name should be the same. 3579 mockEnterDisabledState(); 3580 sendP2pStateMachineMessage(WifiP2pServiceImpl.ENABLE_P2P); 3581 ArgumentCaptor<Message> msgCaptor = ArgumentCaptor.forClass(Message.class); 3582 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DEVICE_INFO); 3583 verify(mClientHandler, times(2)).sendMessage(msgCaptor.capture()); 3584 assertEquals(WifiP2pManager.RESPONSE_DEVICE_INFO, msgCaptor.getValue().what); 3585 WifiP2pDevice wifiP2pDevice = (WifiP2pDevice) msgCaptor.getAllValues().get(1).obj; 3586 assertEquals(defaultDeviceName, wifiP2pDevice.deviceName); 3587 3588 // After the default name expires, the default name should be changed. 3589 when(mClock.getElapsedSinceBootMillis()).thenReturn( 3590 WifiP2pServiceImpl.DEFAULT_DEVICE_NAME_LIFE_TIME_MILLIS); 3591 mockEnterDisabledState(); 3592 sendP2pStateMachineMessage(WifiP2pServiceImpl.ENABLE_P2P); 3593 msgCaptor = ArgumentCaptor.forClass(Message.class); 3594 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DEVICE_INFO); 3595 verify(mClientHandler, times(3)).sendMessage(msgCaptor.capture()); 3596 assertEquals(WifiP2pManager.RESPONSE_DEVICE_INFO, msgCaptor.getValue().what); 3597 wifiP2pDevice = (WifiP2pDevice) msgCaptor.getAllValues().get(2).obj; 3598 assertNotEquals(defaultDeviceName, wifiP2pDevice.deviceName); 3599 } 3600 3601 /** 3602 * Verify the caller sends WifiP2pManager.STOP_DISCOVERY. 3603 */ 3604 @Test testStopDiscoverySuccess()3605 public void testStopDiscoverySuccess() throws Exception { 3606 when(mWifiNative.p2pStopFind()).thenReturn(true); 3607 forceP2pEnabled(mClient1); 3608 sendSimpleMsg(mClientMessenger, WifiP2pManager.STOP_DISCOVERY); 3609 verify(mWifiNative).p2pStopFind(); 3610 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3611 Message message = mMessageCaptor.getValue(); 3612 assertEquals(WifiP2pManager.STOP_DISCOVERY_SUCCEEDED, message.what); 3613 } 3614 3615 /** 3616 * Verify WifiP2pManager.STOP_DISCOVERY_FAILED is returned when native call failure. 3617 */ 3618 @Test testStopDiscoveryFailureWhenNativeCallFailure()3619 public void testStopDiscoveryFailureWhenNativeCallFailure() throws Exception { 3620 when(mWifiNative.p2pStopFind()).thenReturn(false); 3621 forceP2pEnabled(mClient1); 3622 sendSimpleMsg(mClientMessenger, WifiP2pManager.STOP_DISCOVERY); 3623 verify(mWifiNative).p2pStopFind(); 3624 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3625 Message message = mMessageCaptor.getValue(); 3626 assertEquals(WifiP2pManager.STOP_DISCOVERY_FAILED, message.what); 3627 assertEquals(WifiP2pManager.ERROR, message.arg1); 3628 } 3629 3630 /** 3631 * Verify WifiP2pManager.STOP_DISCOVERY_FAILED is returned when p2p is disabled. 3632 */ 3633 @Test testStopDiscoveryFailureWhenP2pDisabled()3634 public void testStopDiscoveryFailureWhenP2pDisabled() throws Exception { 3635 sendSimpleMsg(mClientMessenger, WifiP2pManager.STOP_DISCOVERY); 3636 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3637 Message message = mMessageCaptor.getValue(); 3638 assertEquals(WifiP2pManager.STOP_DISCOVERY_FAILED, message.what); 3639 assertEquals(WifiP2pManager.BUSY, message.arg1); 3640 } 3641 3642 /** 3643 * Verify WifiP2pManager.STOP_DISCOVERY_FAILED is returned when p2p is unsupported. 3644 */ 3645 @Test testStopDiscoveryFailureWhenP2pUnsupported()3646 public void testStopDiscoveryFailureWhenP2pUnsupported() throws Exception { 3647 setUpWifiP2pServiceImpl(false); 3648 sendSimpleMsg(mClientMessenger, WifiP2pManager.STOP_DISCOVERY); 3649 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3650 Message message = mMessageCaptor.getValue(); 3651 assertEquals(WifiP2pManager.STOP_DISCOVERY_FAILED, message.what); 3652 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 3653 } 3654 3655 /** 3656 * Verify the caller sends WifiP2pManager.CANCEL_CONNECT. 3657 */ 3658 @Test testCancelConnectSuccess()3659 public void testCancelConnectSuccess() throws Exception { 3660 // Move to group creating state 3661 testConnectWithConfigValidAsGroupSuccess(); 3662 3663 sendSimpleMsg(mClientMessenger, WifiP2pManager.CANCEL_CONNECT); 3664 verify(mClientHandler, atLeastOnce()).sendMessage(mMessageCaptor.capture()); 3665 Message message = mMessageCaptor.getValue(); 3666 assertEquals(WifiP2pManager.CANCEL_CONNECT_SUCCEEDED, message.what); 3667 } 3668 3669 /** 3670 * Verify WifiP2pManager.CANCEL_CONNECT_FAILED is returned when p2p is inactive. 3671 */ 3672 @Test testCancelConnectFailureWhenP2pInactive()3673 public void testCancelConnectFailureWhenP2pInactive() throws Exception { 3674 // Move to inactive state 3675 forceP2pEnabled(mClient1); 3676 3677 sendSimpleMsg(mClientMessenger, WifiP2pManager.CANCEL_CONNECT); 3678 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3679 Message message = mMessageCaptor.getValue(); 3680 assertEquals(WifiP2pManager.CANCEL_CONNECT_FAILED, message.what); 3681 assertEquals(WifiP2pManager.BUSY, message.arg1); 3682 } 3683 3684 /** 3685 * Verify WifiP2pManager.CANCEL_CONNECT_FAILED is returned when p2p is disabled. 3686 */ 3687 @Test testCancelConnectFailureWhenP2pDisabled()3688 public void testCancelConnectFailureWhenP2pDisabled() throws Exception { 3689 sendSimpleMsg(mClientMessenger, WifiP2pManager.CANCEL_CONNECT); 3690 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3691 Message message = mMessageCaptor.getValue(); 3692 assertEquals(WifiP2pManager.CANCEL_CONNECT_FAILED, message.what); 3693 assertEquals(WifiP2pManager.BUSY, message.arg1); 3694 } 3695 3696 /** 3697 * Verify WifiP2pManager.CANCEL_CONNECT_FAILED is returned when p2p is unsupported. 3698 */ 3699 @Test testCancelConnectFailureWhenP2pUnsupported()3700 public void testCancelConnectFailureWhenP2pUnsupported() throws Exception { 3701 setUpWifiP2pServiceImpl(false); 3702 sendSimpleMsg(mClientMessenger, WifiP2pManager.CANCEL_CONNECT); 3703 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3704 Message message = mMessageCaptor.getValue(); 3705 assertEquals(WifiP2pManager.CANCEL_CONNECT_FAILED, message.what); 3706 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 3707 } 3708 3709 /** 3710 * Verify the caller sends WifiP2pManager.REMOVE_GROUP. 3711 */ 3712 @Test testRemoveGroupSuccess()3713 public void testRemoveGroupSuccess() throws Exception { 3714 mockEnterGroupCreatedState(); 3715 3716 when(mWifiNative.p2pGroupRemove(eq(IFACE_NAME_P2P))).thenReturn(true); 3717 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_GROUP); 3718 verify(mWifiNative).p2pGroupRemove(eq(IFACE_NAME_P2P)); 3719 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3720 Message message = mMessageCaptor.getValue(); 3721 assertEquals(WifiP2pManager.REMOVE_GROUP_SUCCEEDED, message.what); 3722 } 3723 3724 /** 3725 * Verify WifiP2pManager.REMOVE_GROUP_FAILED is returned when native call failure. 3726 */ 3727 @Test testRemoveGroupFailureWhenNativeCallFailure()3728 public void testRemoveGroupFailureWhenNativeCallFailure() throws Exception { 3729 mockEnterGroupCreatedState(); 3730 3731 when(mWifiNative.p2pGroupRemove(eq(IFACE_NAME_P2P))).thenReturn(false); 3732 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_GROUP); 3733 verify(mWifiNative).p2pGroupRemove(eq(IFACE_NAME_P2P)); 3734 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3735 Message message = mMessageCaptor.getValue(); 3736 assertEquals(WifiP2pManager.REMOVE_GROUP_FAILED, message.what); 3737 assertEquals(WifiP2pManager.ERROR, message.arg1); 3738 } 3739 3740 /** 3741 * Verify WifiP2pManager.REMOVE_GROUP_FAILED is returned when p2p is creating group. 3742 */ 3743 @Test testRemoveGroupFailureWhenP2pCreatingGroup()3744 public void testRemoveGroupFailureWhenP2pCreatingGroup() throws Exception { 3745 // Move to group creating state 3746 testConnectWithConfigValidAsGroupSuccess(); 3747 3748 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_GROUP); 3749 verify(mClientHandler, atLeastOnce()).sendMessage(mMessageCaptor.capture()); 3750 Message message = mMessageCaptor.getValue(); 3751 assertEquals(WifiP2pManager.REMOVE_GROUP_FAILED, message.what); 3752 assertEquals(WifiP2pManager.BUSY, message.arg1); 3753 } 3754 3755 /** 3756 * Verify WifiP2pManager.REMOVE_GROUP_FAILED is returned when p2p is inactive. 3757 */ 3758 @Test testRemoveGroupFailureWhenP2pInactive()3759 public void testRemoveGroupFailureWhenP2pInactive() throws Exception { 3760 // Move to inactive state 3761 forceP2pEnabled(mClient1); 3762 3763 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_GROUP); 3764 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3765 Message message = mMessageCaptor.getValue(); 3766 assertEquals(WifiP2pManager.REMOVE_GROUP_FAILED, message.what); 3767 assertEquals(WifiP2pManager.BUSY, message.arg1); 3768 } 3769 3770 /** 3771 * Verify WifiP2pManager.REMOVE_GROUP_FAILED is returned when p2p is disabled. 3772 */ 3773 @Test testRemoveGroupFailureWhenP2pDisabled()3774 public void testRemoveGroupFailureWhenP2pDisabled() throws Exception { 3775 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_GROUP); 3776 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3777 Message message = mMessageCaptor.getValue(); 3778 assertEquals(WifiP2pManager.REMOVE_GROUP_FAILED, message.what); 3779 assertEquals(WifiP2pManager.BUSY, message.arg1); 3780 } 3781 3782 /** 3783 * Verify WifiP2pManager.REMOVE_GROUP_FAILED is returned when p2p is unsupported. 3784 */ 3785 @Test testRemoveGroupFailureWhenP2pUnsupported()3786 public void testRemoveGroupFailureWhenP2pUnsupported() throws Exception { 3787 setUpWifiP2pServiceImpl(false); 3788 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_GROUP); 3789 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3790 Message message = mMessageCaptor.getValue(); 3791 assertEquals(WifiP2pManager.REMOVE_GROUP_FAILED, message.what); 3792 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 3793 } 3794 3795 /** 3796 * Verify the caller sends WifiP2pManager.SET_CHANNEL. 3797 */ 3798 @Test testSetChannelSuccess()3799 public void testSetChannelSuccess() throws Exception { 3800 // Move to enabled state 3801 forceP2pEnabled(mClient1); 3802 3803 Bundle p2pChannels = new Bundle(); 3804 p2pChannels.putInt("lc", 1); 3805 p2pChannels.putInt("oc", 2); 3806 when(mWifiNative.p2pSetListenChannel(anyInt())).thenReturn(true); 3807 when(mWifiNative.p2pSetOperatingChannel(anyInt(), any())).thenReturn(true); 3808 sendSetChannelMsg(mClientMessenger, p2pChannels); 3809 verify(mWifiNative).p2pSetListenChannel(eq(1)); 3810 verify(mWifiNative).p2pSetOperatingChannel(eq(2), any()); 3811 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3812 Message message = mMessageCaptor.getValue(); 3813 assertEquals(WifiP2pManager.SET_CHANNEL_SUCCEEDED, message.what); 3814 } 3815 3816 /** 3817 * Verify WifiP2pManager.SET_CHANNEL_FAILED is returned when native call failure. 3818 */ 3819 @Test testSetChannelFailureWhenNativeCallSetListenChannelFailure()3820 public void testSetChannelFailureWhenNativeCallSetListenChannelFailure() throws Exception { 3821 // Move to enabled state 3822 forceP2pEnabled(mClient1); 3823 3824 Bundle p2pChannels = new Bundle(); 3825 p2pChannels.putInt("lc", 1); 3826 p2pChannels.putInt("oc", 2); 3827 when(mWifiNative.p2pSetListenChannel(anyInt())).thenReturn(false); 3828 when(mWifiNative.p2pSetOperatingChannel(anyInt(), any())).thenReturn(true); 3829 sendSetChannelMsg(mClientMessenger, p2pChannels); 3830 verify(mWifiNative).p2pSetListenChannel(eq(1)); 3831 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3832 Message message = mMessageCaptor.getValue(); 3833 assertEquals(WifiP2pManager.SET_CHANNEL_FAILED, message.what); 3834 } 3835 3836 /** 3837 * Verify WifiP2pManager.SET_CHANNEL_FAILED is returned when native call failure. 3838 */ 3839 @Test testSetChannelFailureWhenNativeCallSetOperatingChannelFailure()3840 public void testSetChannelFailureWhenNativeCallSetOperatingChannelFailure() throws Exception { 3841 // Move to enabled state 3842 forceP2pEnabled(mClient1); 3843 3844 Bundle p2pChannels = new Bundle(); 3845 p2pChannels.putInt("lc", 1); 3846 p2pChannels.putInt("oc", 2); 3847 when(mWifiNative.p2pSetListenChannel(anyInt())).thenReturn(true); 3848 when(mWifiNative.p2pSetOperatingChannel(anyInt(), any())).thenReturn(false); 3849 sendSetChannelMsg(mClientMessenger, p2pChannels); 3850 verify(mWifiNative).p2pSetListenChannel(eq(1)); 3851 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3852 Message message = mMessageCaptor.getValue(); 3853 assertEquals(WifiP2pManager.SET_CHANNEL_FAILED, message.what); 3854 } 3855 3856 /** 3857 * Verify WifiP2pManager.SET_CHANNEL_FAILED is returned when no permissions are held. 3858 */ 3859 @Test testSetChannelFailureWhenNoPermissions()3860 public void testSetChannelFailureWhenNoPermissions() throws Exception { 3861 // Move to enabled state 3862 forceP2pEnabled(mClient1); 3863 3864 // no permissions held 3865 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 3866 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(false); 3867 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false); 3868 3869 Bundle p2pChannels = new Bundle(); 3870 p2pChannels.putInt("lc", 1); 3871 p2pChannels.putInt("oc", 2); 3872 sendSetChannelMsg(mClientMessenger, p2pChannels); 3873 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3874 Message message = mMessageCaptor.getValue(); 3875 assertEquals(WifiP2pManager.SET_CHANNEL_FAILED, message.what); 3876 assertEquals(WifiP2pManager.ERROR, message.arg1); 3877 } 3878 3879 /** 3880 * Verify p2pSetListenChannel doesn't been called when message contain null object. 3881 */ 3882 @Test testSetChannelFailureWhenObjectIsNull()3883 public void testSetChannelFailureWhenObjectIsNull() throws Exception { 3884 when(mWifiNative.p2pSetListenChannel(anyInt())).thenReturn(true); 3885 when(mWifiNative.p2pSetOperatingChannel(anyInt(), any())).thenReturn(true); 3886 3887 // Move to enabled state 3888 forceP2pEnabled(mClient1); 3889 3890 when(mWifiNative.p2pSetListenChannel(anyInt())).thenReturn(false); 3891 when(mWifiNative.p2pSetOperatingChannel(anyInt(), any())).thenReturn(true); 3892 sendSetChannelMsg(mClientMessenger, null); 3893 // Should be called only once on entering P2pEnabledState. 3894 verify(mWifiNative, times(1)).p2pSetListenChannel(anyInt()); 3895 verify(mWifiNative, times(1)).p2pSetOperatingChannel(anyInt(), any()); 3896 } 3897 3898 /** 3899 * Verify the caller sends WifiP2pManager.START_WPS with push button configuration. 3900 */ 3901 @Test testStartWpsWithPbcSuccess()3902 public void testStartWpsWithPbcSuccess() throws Exception { 3903 mockEnterGroupCreatedState(); 3904 3905 when(mWifiNative.startWpsPbc(anyString(), any())).thenReturn(true); 3906 WpsInfo wps = new WpsInfo(); 3907 wps.setup = WpsInfo.PBC; 3908 sendStartWpsMsg(mClientMessenger, wps); 3909 verify(mWifiNative).startWpsPbc(eq(IFACE_NAME_P2P), isNull()); 3910 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3911 Message message = mMessageCaptor.getValue(); 3912 assertEquals(WifiP2pManager.START_WPS_SUCCEEDED, message.what); 3913 } 3914 3915 /** 3916 * Verify the caller sends WifiP2pManager.START_WPS with pin display. 3917 */ 3918 @Test testStartWpsWithPinDisplaySuccess()3919 public void testStartWpsWithPinDisplaySuccess() throws Exception { 3920 // TODO(hsiuchangchen): This test item is related to UI. 3921 } 3922 3923 /** 3924 * Verify the caller sends WifiP2pManager.START_WPS with pin keypad. 3925 */ 3926 @Test testStartWpsWithPinKeypadSuccess()3927 public void testStartWpsWithPinKeypadSuccess() throws Exception { 3928 mockEnterGroupCreatedState(); 3929 3930 when(mWifiNative.startWpsPinKeypad(anyString(), anyString())).thenReturn(true); 3931 WpsInfo wps = new WpsInfo(); 3932 wps.setup = WpsInfo.KEYPAD; 3933 wps.pin = "1234"; 3934 sendStartWpsMsg(mClientMessenger, wps); 3935 verify(mWifiNative).startWpsPinKeypad(eq(IFACE_NAME_P2P), eq("1234")); 3936 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3937 Message message = mMessageCaptor.getValue(); 3938 assertEquals(WifiP2pManager.START_WPS_SUCCEEDED, message.what); 3939 } 3940 3941 /** 3942 * Verify WifiP2pManager.START_WPS_FAILED is returned when message contain null object. 3943 */ 3944 @Test testStartWpsFailureWhenObjectIsNull()3945 public void testStartWpsFailureWhenObjectIsNull() throws Exception { 3946 mockEnterGroupCreatedState(); 3947 3948 WpsInfo wps = null; 3949 sendStartWpsMsg(mClientMessenger, wps); 3950 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3951 Message message = mMessageCaptor.getValue(); 3952 assertEquals(WifiP2pManager.START_WPS_FAILED, message.what); 3953 } 3954 3955 /** 3956 * Verify WifiP2pManager.START_WPS_FAILED is returned when native call failure with 3957 * push button configuration. 3958 */ 3959 @Test testStartWpsWithPbcFailureWhenNativeCallFailure()3960 public void testStartWpsWithPbcFailureWhenNativeCallFailure() throws Exception { 3961 mockEnterGroupCreatedState(); 3962 when(mWifiNative.startWpsPbc(anyString(), any())).thenReturn(false); 3963 WpsInfo wps = new WpsInfo(); 3964 wps.setup = WpsInfo.PBC; 3965 sendStartWpsMsg(mClientMessenger, wps); 3966 verify(mWifiNative).startWpsPbc(eq(IFACE_NAME_P2P), isNull()); 3967 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3968 Message message = mMessageCaptor.getValue(); 3969 assertEquals(WifiP2pManager.START_WPS_FAILED, message.what); 3970 } 3971 3972 /** 3973 * Verify WifiP2pManager.START_WPS_FAILED is returned when native call failure with 3974 * pin display. 3975 */ 3976 @Test testStartWpsWithPinDisplayFailureWhenNativeCallFailure()3977 public void testStartWpsWithPinDisplayFailureWhenNativeCallFailure() throws Exception { 3978 mockEnterGroupCreatedState(); 3979 3980 when(mWifiNative.startWpsPinDisplay(anyString(), any())).thenReturn("abcd"); 3981 WpsInfo wps = new WpsInfo(); 3982 wps.setup = WpsInfo.DISPLAY; 3983 sendStartWpsMsg(mClientMessenger, wps); 3984 verify(mWifiNative).startWpsPinDisplay(eq(IFACE_NAME_P2P), isNull()); 3985 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 3986 Message message = mMessageCaptor.getValue(); 3987 assertEquals(WifiP2pManager.START_WPS_FAILED, message.what); 3988 } 3989 3990 /** 3991 * Verify WifiP2pManager.START_WPS_FAILED is returned when native call failure with 3992 * pin keypad. 3993 */ 3994 @Test testStartWpsWithPinKeypadFailureWhenNativeCallFailure()3995 public void testStartWpsWithPinKeypadFailureWhenNativeCallFailure() throws Exception { 3996 mockEnterGroupCreatedState(); 3997 3998 when(mWifiNative.startWpsPinKeypad(anyString(), anyString())).thenReturn(false); 3999 WpsInfo wps = new WpsInfo(); 4000 wps.setup = WpsInfo.KEYPAD; 4001 wps.pin = "1234"; 4002 sendStartWpsMsg(mClientMessenger, wps); 4003 verify(mWifiNative).startWpsPinKeypad(eq(IFACE_NAME_P2P), eq("1234")); 4004 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4005 Message message = mMessageCaptor.getValue(); 4006 assertEquals(WifiP2pManager.START_WPS_FAILED, message.what); 4007 } 4008 4009 /** 4010 * Verify WifiP2pManager.START_WPS_FAILED is returned when p2p is inactive. 4011 */ 4012 @Test testStartWpsFailureWhenP2pInactive()4013 public void testStartWpsFailureWhenP2pInactive() throws Exception { 4014 // Move to inactive state 4015 forceP2pEnabled(mClient1); 4016 4017 WpsInfo wps = new WpsInfo(); 4018 sendStartWpsMsg(mClientMessenger, wps); 4019 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4020 Message message = mMessageCaptor.getValue(); 4021 assertEquals(WifiP2pManager.START_WPS_FAILED, message.what); 4022 assertEquals(WifiP2pManager.BUSY, message.arg1); 4023 } 4024 4025 /** 4026 * Verify WifiP2pManager.START_WPS_FAILED is returned when p2p is disabled. 4027 */ 4028 @Test testStartWpsFailureWhenP2pDisabled()4029 public void testStartWpsFailureWhenP2pDisabled() throws Exception { 4030 WpsInfo wps = new WpsInfo(); 4031 sendStartWpsMsg(mClientMessenger, wps); 4032 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4033 Message message = mMessageCaptor.getValue(); 4034 assertEquals(WifiP2pManager.START_WPS_FAILED, message.what); 4035 assertEquals(WifiP2pManager.BUSY, message.arg1); 4036 } 4037 4038 /** 4039 * Verify WifiP2pManager.START_WPS_FAILED is returned when p2p is unsupported. 4040 */ 4041 @Test testStartWpsFailureWhenP2pUnsupported()4042 public void testStartWpsFailureWhenP2pUnsupported() throws Exception { 4043 setUpWifiP2pServiceImpl(false); 4044 WpsInfo wps = new WpsInfo(); 4045 sendStartWpsMsg(mClientMessenger, wps); 4046 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4047 Message message = mMessageCaptor.getValue(); 4048 assertEquals(WifiP2pManager.START_WPS_FAILED, message.what); 4049 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 4050 } 4051 4052 /** 4053 * Verify the caller sends WifiP2pManager.SET_DEVICE_NAME. 4054 */ 4055 @Test testSetDeviceNameSuccess()4056 public void testSetDeviceNameSuccess() throws Exception { 4057 // Move to enabled state 4058 forceP2pEnabled(mClient1); 4059 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4060 4061 mTestThisDevice.deviceName = "another-name"; 4062 when(mWifiNative.setDeviceName(anyString())).thenReturn(true); 4063 when(mWifiNative.setP2pSsidPostfix(anyString())).thenReturn(true); 4064 sendSetDeviceNameMsg(mClientMessenger, mTestThisDevice); 4065 verify(mWifiNative).setDeviceName(eq(mTestThisDevice.deviceName)); 4066 verify(mWifiNative).setP2pSsidPostfix(eq("-" + mTestThisDevice.deviceName)); 4067 verify(mWifiSettingsConfigStore).put( 4068 eq(WIFI_P2P_DEVICE_NAME), eq(mTestThisDevice.deviceName)); 4069 checkSendThisDeviceChangedBroadcast(); 4070 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4071 Message message = mMessageCaptor.getValue(); 4072 assertEquals(WifiP2pManager.SET_DEVICE_NAME_SUCCEEDED, message.what); 4073 } 4074 4075 /** 4076 * Verify the caller sends WifiP2pManager.SET_DEVICE_NAME with an empty name. 4077 */ 4078 @Test testSetDeviceNameFailureWithEmptyName()4079 public void testSetDeviceNameFailureWithEmptyName() throws Exception { 4080 // Move to enabled state 4081 forceP2pEnabled(mClient1); 4082 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4083 4084 // clear the one called on entering P2pEnabledState. 4085 reset(mWifiNative); 4086 mTestThisDevice.deviceName = ""; 4087 when(mWifiNative.setDeviceName(anyString())).thenReturn(true); 4088 sendSetDeviceNameMsg(mClientMessenger, mTestThisDevice); 4089 verify(mWifiNative, never()).setDeviceName(any()); 4090 verify(mWifiSettingsConfigStore, never()).put(any(), any()); 4091 4092 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4093 Message message = mMessageCaptor.getValue(); 4094 assertEquals(WifiP2pManager.SET_DEVICE_NAME_FAILED, message.what); 4095 assertEquals(WifiP2pManager.ERROR, message.arg1); 4096 } 4097 4098 /** 4099 * Verify WifiP2pManager.SET_DEVICE_NAME_FAILED is returned when native call failed. 4100 */ 4101 @Test testSetDeviceNameFailureWhenNativeCallFailure()4102 public void testSetDeviceNameFailureWhenNativeCallFailure() throws Exception { 4103 // Move to enabled state 4104 forceP2pEnabled(mClient1); 4105 4106 // clear the one called on entering P2pEnabledState. 4107 reset(mWifiNative); 4108 when(mWifiNative.setDeviceName(anyString())).thenReturn(false); 4109 sendSetDeviceNameMsg(mClientMessenger, mTestThisDevice); 4110 verify(mWifiNative).setDeviceName(eq(mTestThisDevice.deviceName)); 4111 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4112 Message message = mMessageCaptor.getValue(); 4113 assertEquals(WifiP2pManager.SET_DEVICE_NAME_FAILED, message.what); 4114 assertEquals(WifiP2pManager.ERROR, message.arg1); 4115 } 4116 4117 /** 4118 * Verify WifiP2pManager.SET_DEVICE_NAME_FAILED is returned when p2p device is null. 4119 */ 4120 @Test testSetDeviceNameFailureWhenDeviceIsNull()4121 public void testSetDeviceNameFailureWhenDeviceIsNull() throws Exception { 4122 // Move to enabled state 4123 forceP2pEnabled(mClient1); 4124 4125 sendSetDeviceNameMsg(mClientMessenger, null); 4126 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4127 Message message = mMessageCaptor.getValue(); 4128 assertEquals(WifiP2pManager.SET_DEVICE_NAME_FAILED, message.what); 4129 assertEquals(WifiP2pManager.ERROR, message.arg1); 4130 } 4131 4132 /** 4133 * Verify WifiP2pManager.SET_DEVICE_NAME_FAILED is returned when p2p device's name is null. 4134 */ 4135 @Test testSetDeviceNameFailureWhenDeviceNameIsNull()4136 public void testSetDeviceNameFailureWhenDeviceNameIsNull() throws Exception { 4137 // Move to enabled state 4138 forceP2pEnabled(mClient1); 4139 4140 mTestThisDevice.deviceName = null; 4141 sendSetDeviceNameMsg(mClientMessenger, mTestThisDevice); 4142 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4143 Message message = mMessageCaptor.getValue(); 4144 assertEquals(WifiP2pManager.SET_DEVICE_NAME_FAILED, message.what); 4145 assertEquals(WifiP2pManager.ERROR, message.arg1); 4146 } 4147 4148 /** 4149 * Verify WifiP2pManager.SET_DEVICE_NAME_FAILED is returned when p2p is disabled. 4150 */ 4151 @Test testSetDeviceNameFailureWhenP2pDisabled()4152 public void testSetDeviceNameFailureWhenP2pDisabled() throws Exception { 4153 sendSetDeviceNameMsg(mClientMessenger, mTestThisDevice); 4154 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4155 Message message = mMessageCaptor.getValue(); 4156 assertEquals(WifiP2pManager.SET_DEVICE_NAME_FAILED, message.what); 4157 assertEquals(WifiP2pManager.BUSY, message.arg1); 4158 } 4159 4160 /** 4161 * Verify WifiP2pManager.SET_DEVICE_NAME_FAILED is returned when p2p is unsupported. 4162 */ 4163 @Test testSetDeviceNameFailureWhenP2pUnsupported()4164 public void testSetDeviceNameFailureWhenP2pUnsupported() throws Exception { 4165 setUpWifiP2pServiceImpl(false); 4166 sendSetDeviceNameMsg(mClientMessenger, mTestThisDevice); 4167 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4168 Message message = mMessageCaptor.getValue(); 4169 assertEquals(WifiP2pManager.SET_DEVICE_NAME_FAILED, message.what); 4170 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 4171 } 4172 4173 /** 4174 * Verify WifiP2pManager.SET_DEVICE_NAME_FAILED is returned when no permissions are held. 4175 */ 4176 @Test testSetDeviceNameFailureWhenNoPermissions()4177 public void testSetDeviceNameFailureWhenNoPermissions() throws Exception { 4178 // Move to enabled state 4179 forceP2pEnabled(mClient1); 4180 4181 // no permissions held 4182 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 4183 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(false); 4184 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false); 4185 4186 sendSetDeviceNameMsg(mClientMessenger, null); 4187 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4188 Message message = mMessageCaptor.getValue(); 4189 assertEquals(WifiP2pManager.SET_DEVICE_NAME_FAILED, message.what); 4190 assertEquals(WifiP2pManager.ERROR, message.arg1); 4191 } 4192 4193 /** 4194 * Verify the caller sends WifiP2pManager.SET_WFD_INFO with wfd enabled. 4195 */ 4196 @Test testSetWfdInfoSuccessWithWfdEnabled()4197 public void testSetWfdInfoSuccessWithWfdEnabled() throws Exception { 4198 // Move to enabled state 4199 forceP2pEnabled(mClient1); 4200 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4201 4202 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4203 mTestThisDevice.wfdInfo.setEnabled(true); 4204 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4205 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4206 .thenReturn(PackageManager.PERMISSION_GRANTED); 4207 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 4208 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(true); 4209 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4210 4211 verify(mWifiInjector).getWifiPermissionsWrapper(); 4212 verify(mWifiPermissionsWrapper).getUidPermission( 4213 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4214 verify(mWifiNative).setWfdEnable(eq(true)); 4215 verify(mWifiNative).setWfdDeviceInfo(eq(mTestThisDevice.wfdInfo.getDeviceInfoHex())); 4216 checkSendThisDeviceChangedBroadcast(); 4217 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4218 Message message = mMessageCaptor.getValue(); 4219 assertEquals(WifiP2pManager.SET_WFD_INFO_SUCCEEDED, message.what); 4220 } 4221 4222 /** 4223 * Verify the caller sends WifiP2pManager.SET_WFD_INFO with wfd is disabled. 4224 */ 4225 @Test testSetWfdInfoSuccessWithWfdDisabled()4226 public void testSetWfdInfoSuccessWithWfdDisabled() throws Exception { 4227 // Move to enabled state 4228 forceP2pEnabled(mClient1); 4229 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4230 4231 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4232 mTestThisDevice.wfdInfo.setEnabled(false); 4233 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4234 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4235 .thenReturn(PackageManager.PERMISSION_GRANTED); 4236 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 4237 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4238 4239 verify(mWifiInjector).getWifiPermissionsWrapper(); 4240 verify(mWifiPermissionsWrapper).getUidPermission( 4241 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4242 verify(mWifiNative).setWfdEnable(eq(false)); 4243 checkSendThisDeviceChangedBroadcast(); 4244 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4245 Message message = mMessageCaptor.getValue(); 4246 assertEquals(WifiP2pManager.SET_WFD_INFO_SUCCEEDED, message.what); 4247 } 4248 4249 /** 4250 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when wfd permission denied. 4251 */ 4252 @Test testSetWfdInfoFailureWhenWfdPermissionDenied()4253 public void testSetWfdInfoFailureWhenWfdPermissionDenied() throws Exception { 4254 // Move to enabled state 4255 forceP2pEnabled(mClient1); 4256 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4257 4258 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4259 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4260 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4261 .thenReturn(PackageManager.PERMISSION_DENIED); 4262 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4263 verify(mWifiInjector).getWifiPermissionsWrapper(); 4264 verify(mWifiPermissionsWrapper).getUidPermission( 4265 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4266 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4267 Message message = mMessageCaptor.getValue(); 4268 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 4269 assertEquals(WifiP2pManager.ERROR, message.arg1); 4270 } 4271 4272 /** 4273 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when wfdInfo is null. 4274 */ 4275 @Test testSetWfdInfoFailureWhenWfdInfoIsNull()4276 public void testSetWfdInfoFailureWhenWfdInfoIsNull() throws Exception { 4277 // Move to enabled state 4278 forceP2pEnabled(mClient1); 4279 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4280 4281 mTestThisDevice.wfdInfo = null; 4282 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4283 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4284 .thenReturn(PackageManager.PERMISSION_GRANTED); 4285 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4286 verify(mWifiInjector).getWifiPermissionsWrapper(); 4287 verify(mWifiPermissionsWrapper).getUidPermission( 4288 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4289 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4290 Message message = mMessageCaptor.getValue(); 4291 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 4292 assertEquals(WifiP2pManager.ERROR, message.arg1); 4293 } 4294 4295 /** 4296 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when wfd is enabled 4297 * and native call "setWfdEnable" failure. 4298 */ 4299 @Test testSetWfdInfoFailureWithWfdEnabledWhenNativeCallFailure1()4300 public void testSetWfdInfoFailureWithWfdEnabledWhenNativeCallFailure1() throws Exception { 4301 // Move to enabled state 4302 forceP2pEnabled(mClient1); 4303 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4304 4305 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4306 mTestThisDevice.wfdInfo.setEnabled(true); 4307 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4308 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4309 .thenReturn(PackageManager.PERMISSION_GRANTED); 4310 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(false); 4311 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4312 4313 verify(mWifiInjector).getWifiPermissionsWrapper(); 4314 verify(mWifiPermissionsWrapper).getUidPermission( 4315 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4316 verify(mWifiNative).setWfdEnable(eq(true)); 4317 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4318 Message message = mMessageCaptor.getValue(); 4319 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 4320 assertEquals(WifiP2pManager.ERROR, message.arg1); 4321 } 4322 4323 /** 4324 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when wfd is enabled 4325 * and native call "setWfdDeviceInfo" failure. 4326 */ 4327 @Test testSetWfdInfoFailureWithWfdEnabledWhenNativeCallFailure2()4328 public void testSetWfdInfoFailureWithWfdEnabledWhenNativeCallFailure2() throws Exception { 4329 // Move to enabled state 4330 forceP2pEnabled(mClient1); 4331 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4332 4333 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4334 mTestThisDevice.wfdInfo.setEnabled(true); 4335 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4336 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4337 .thenReturn(PackageManager.PERMISSION_GRANTED); 4338 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 4339 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(false); 4340 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4341 4342 verify(mWifiInjector).getWifiPermissionsWrapper(); 4343 verify(mWifiPermissionsWrapper).getUidPermission( 4344 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4345 verify(mWifiNative).setWfdEnable(eq(true)); 4346 verify(mWifiNative).setWfdDeviceInfo(eq(mTestThisDevice.wfdInfo.getDeviceInfoHex())); 4347 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4348 Message message = mMessageCaptor.getValue(); 4349 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 4350 assertEquals(WifiP2pManager.ERROR, message.arg1); 4351 } 4352 4353 /** 4354 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when wfd is disabled 4355 * and native call failure. 4356 */ 4357 @Test testSetWfdInfoFailureWithWfdDisabledWhenNativeCallFailure()4358 public void testSetWfdInfoFailureWithWfdDisabledWhenNativeCallFailure() throws Exception { 4359 // Move to enabled state 4360 forceP2pEnabled(mClient1); 4361 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 4362 4363 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4364 mTestThisDevice.wfdInfo.setEnabled(false); 4365 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4366 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4367 .thenReturn(PackageManager.PERMISSION_GRANTED); 4368 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(false); 4369 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4370 4371 verify(mWifiInjector).getWifiPermissionsWrapper(); 4372 verify(mWifiPermissionsWrapper).getUidPermission( 4373 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4374 verify(mWifiNative).setWfdEnable(eq(false)); 4375 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4376 Message message = mMessageCaptor.getValue(); 4377 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 4378 assertEquals(WifiP2pManager.ERROR, message.arg1); 4379 } 4380 4381 /** 4382 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when wfd permission denied 4383 * and p2p is disabled. 4384 */ 4385 @Test testSetWfdInfoFailureWhenWfdPermissionDeniedAndP2pDisabled()4386 public void testSetWfdInfoFailureWhenWfdPermissionDeniedAndP2pDisabled() throws Exception { 4387 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4388 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4389 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4390 .thenReturn(PackageManager.PERMISSION_DENIED); 4391 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4392 verify(mWifiInjector).getWifiPermissionsWrapper(); 4393 verify(mWifiPermissionsWrapper).getUidPermission( 4394 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4395 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4396 Message message = mMessageCaptor.getValue(); 4397 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 4398 assertEquals(WifiP2pManager.ERROR, message.arg1); 4399 } 4400 4401 /** 4402 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when p2p is unsupported. 4403 */ 4404 @Test testSetWfdInfoFailureWhenP2pUnsupported()4405 public void testSetWfdInfoFailureWhenP2pUnsupported() throws Exception { 4406 setUpWifiP2pServiceImpl(false); 4407 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4408 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4409 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4410 .thenReturn(PackageManager.PERMISSION_GRANTED); 4411 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4412 verify(mWifiInjector).getWifiPermissionsWrapper(); 4413 verify(mWifiPermissionsWrapper).getUidPermission( 4414 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4415 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4416 Message message = mMessageCaptor.getValue(); 4417 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 4418 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 4419 } 4420 4421 /** 4422 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when wfd permission denied 4423 * and p2p is unsupported. 4424 */ 4425 @Test testSetWfdInfoFailureWhenWfdPermissionDeniedAndP2pUnsupported()4426 public void testSetWfdInfoFailureWhenWfdPermissionDeniedAndP2pUnsupported() throws Exception { 4427 setUpWifiP2pServiceImpl(false); 4428 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 4429 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4430 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4431 .thenReturn(PackageManager.PERMISSION_DENIED); 4432 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 4433 verify(mWifiInjector).getWifiPermissionsWrapper(); 4434 verify(mWifiPermissionsWrapper).getUidPermission( 4435 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4436 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4437 Message message = mMessageCaptor.getValue(); 4438 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 4439 assertEquals(WifiP2pManager.ERROR, message.arg1); 4440 } 4441 4442 /** 4443 * Verify the call setMiracastMode when p2p is enabled. 4444 */ 4445 @Test testSetMiracastModeWhenP2pEnabled()4446 public void testSetMiracastModeWhenP2pEnabled() throws Exception { 4447 // Move to enabled state 4448 forceP2pEnabled(mClient1); 4449 4450 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4451 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4452 .thenReturn(PackageManager.PERMISSION_GRANTED); 4453 mWifiP2pServiceImpl.setMiracastMode(0); 4454 mLooper.dispatchAll(); 4455 verify(mWifiInjector).getWifiPermissionsWrapper(); 4456 verify(mWifiPermissionsWrapper).getUidPermission( 4457 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4458 verify(mWifiNative).setMiracastMode(eq(0)); 4459 } 4460 4461 /** 4462 * Verify the call setMiracastMode when p2p is disable. 4463 */ 4464 @Test testSetMiracastModeWhenP2pDisabled()4465 public void testSetMiracastModeWhenP2pDisabled() throws Exception { 4466 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4467 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4468 .thenReturn(PackageManager.PERMISSION_GRANTED); 4469 mWifiP2pServiceImpl.setMiracastMode(0); 4470 mLooper.dispatchAll(); 4471 verify(mWifiInjector).getWifiPermissionsWrapper(); 4472 verify(mWifiPermissionsWrapper).getUidPermission( 4473 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4474 verify(mWifiNative, never()).setMiracastMode(anyInt()); 4475 } 4476 4477 /** 4478 * Verify the call setMiracastMode when CONFIGURE_WIFI_DISPLAY permission denied. 4479 */ 4480 @Test(expected = SecurityException.class) testSetMiracastModeWhenPermissionDeined()4481 public void testSetMiracastModeWhenPermissionDeined() throws Exception { 4482 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 4483 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 4484 .thenReturn(PackageManager.PERMISSION_DENIED); 4485 mWifiP2pServiceImpl.setMiracastMode(0); 4486 verify(mWifiInjector).getWifiPermissionsWrapper(); 4487 verify(mWifiPermissionsWrapper).getUidPermission( 4488 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 4489 verify(mWifiNative, never()).setMiracastMode(anyInt()); 4490 } 4491 4492 /** 4493 * Verify the caller sends WifiP2pManager.FACTORY_RESET when p2p is enabled. 4494 */ 4495 @Test testFactoryResetSuccessWhenP2pEnabled()4496 public void testFactoryResetSuccessWhenP2pEnabled() throws Exception { 4497 // Move to enabled state 4498 forceP2pEnabled(mClient1); 4499 4500 when(mWifiInjector.getUserManager()).thenReturn(mUserManager); 4501 when(mPackageManager.getNameForUid(anyInt())).thenReturn("testPkg"); 4502 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 4503 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_NETWORK_RESET), any())) 4504 .thenReturn(false); 4505 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), any())) 4506 .thenReturn(false); 4507 when(mWifiNative.p2pListNetworks(any())).thenReturn(true); 4508 sendSimpleMsg(mClientMessenger, WifiP2pManager.FACTORY_RESET); 4509 checkSendP2pPersistentGroupsChangedBroadcast(); 4510 verify(mWifiInjector).getUserManager(); 4511 verify(mPackageManager).getNameForUid(anyInt()); 4512 verify(mWifiPermissionsUtil).checkNetworkSettingsPermission(anyInt()); 4513 verify(mUserManager).hasUserRestrictionForUser( 4514 eq(UserManager.DISALLOW_NETWORK_RESET), any()); 4515 verify(mUserManager).hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), any()); 4516 verify(mWifiNative, atLeastOnce()).p2pListNetworks(any()); 4517 verify(mWifiSettingsConfigStore).put(eq(WIFI_P2P_PENDING_FACTORY_RESET), eq(false)); 4518 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4519 Message message = mMessageCaptor.getValue(); 4520 assertEquals(WifiP2pManager.FACTORY_RESET_SUCCEEDED, message.what); 4521 } 4522 4523 /** 4524 * Verify the caller sends WifiP2pManager.FACTORY_RESET when p2p is disabled at first 4525 * and changes to enabled. 4526 */ 4527 @Test testFactoryResetSuccessWhenP2pFromDisabledToEnabled()4528 public void testFactoryResetSuccessWhenP2pFromDisabledToEnabled() throws Exception { 4529 when(mWifiInjector.getUserManager()).thenReturn(mUserManager); 4530 when(mPackageManager.getNameForUid(anyInt())).thenReturn("testPkg"); 4531 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 4532 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_NETWORK_RESET), any())) 4533 .thenReturn(false); 4534 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), any())) 4535 .thenReturn(false); 4536 when(mWifiNative.p2pListNetworks(any())).thenReturn(true); 4537 sendSimpleMsg(mClientMessenger, WifiP2pManager.FACTORY_RESET); 4538 verify(mWifiInjector).getUserManager(); 4539 verify(mPackageManager).getNameForUid(anyInt()); 4540 verify(mWifiPermissionsUtil).checkNetworkSettingsPermission(anyInt()); 4541 verify(mUserManager).hasUserRestrictionForUser( 4542 eq(UserManager.DISALLOW_NETWORK_RESET), any()); 4543 verify(mUserManager).hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), any()); 4544 verify(mWifiNative, never()).p2pListNetworks(any()); 4545 verify(mWifiSettingsConfigStore).put(eq(WIFI_P2P_PENDING_FACTORY_RESET), eq(true)); 4546 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4547 Message message = mMessageCaptor.getValue(); 4548 assertEquals(WifiP2pManager.FACTORY_RESET_SUCCEEDED, message.what); 4549 4550 // Move to enabled state 4551 when(mWifiSettingsConfigStore.get(eq(WIFI_P2P_PENDING_FACTORY_RESET))).thenReturn(true); 4552 forceP2pEnabled(mClient1); 4553 verify(mPackageManager, times(2)).getNameForUid(anyInt()); 4554 verify(mWifiPermissionsUtil, times(2)).checkNetworkSettingsPermission(anyInt()); 4555 verify(mUserManager, times(2)).hasUserRestrictionForUser( 4556 eq(UserManager.DISALLOW_NETWORK_RESET), any()); 4557 verify(mUserManager, times(2)).hasUserRestrictionForUser( 4558 eq(UserManager.DISALLOW_CONFIG_WIFI), any()); 4559 verify(mWifiNative, atLeastOnce()).p2pListNetworks(any()); 4560 verify(mWifiSettingsConfigStore).get(eq(WIFI_P2P_PENDING_FACTORY_RESET)); 4561 verify(mWifiSettingsConfigStore).put(eq(WIFI_P2P_PENDING_FACTORY_RESET), eq(false)); 4562 checkSendP2pPersistentGroupsChangedBroadcast(); 4563 } 4564 4565 /** 4566 * Verify WifiP2pManager.FACTORY_RESET_FAILED is returned without network setting permission. 4567 */ 4568 @Test testFactoryResetFailureWithoutNetworkSettingPermission()4569 public void testFactoryResetFailureWithoutNetworkSettingPermission() throws Exception { 4570 // Move to enabled state 4571 forceP2pEnabled(mClient1); 4572 4573 when(mWifiInjector.getUserManager()).thenReturn(mUserManager); 4574 when(mPackageManager.getNameForUid(anyInt())).thenReturn("testPkg"); 4575 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 4576 sendSimpleMsg(mClientMessenger, WifiP2pManager.FACTORY_RESET); 4577 verify(mWifiInjector).getUserManager(); 4578 verify(mPackageManager).getNameForUid(anyInt()); 4579 verify(mWifiPermissionsUtil).checkNetworkSettingsPermission(anyInt()); 4580 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4581 Message message = mMessageCaptor.getValue(); 4582 assertEquals(WifiP2pManager.FACTORY_RESET_FAILED, message.what); 4583 assertEquals(WifiP2pManager.ERROR, message.arg1); 4584 } 4585 4586 /** 4587 * Verify WifiP2pManager.FACTORY_RESET_FAILED is returned when network reset disallow. 4588 */ 4589 @Test testFactoryResetFailureWhenNetworkResetDisallow()4590 public void testFactoryResetFailureWhenNetworkResetDisallow() throws Exception { 4591 // Move to enabled state 4592 forceP2pEnabled(mClient1); 4593 4594 when(mWifiInjector.getUserManager()).thenReturn(mUserManager); 4595 when(mPackageManager.getNameForUid(anyInt())).thenReturn("testPkg"); 4596 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 4597 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_NETWORK_RESET), any())) 4598 .thenReturn(true); 4599 sendSimpleMsg(mClientMessenger, WifiP2pManager.FACTORY_RESET); 4600 verify(mWifiInjector).getUserManager(); 4601 verify(mPackageManager).getNameForUid(anyInt()); 4602 verify(mWifiPermissionsUtil).checkNetworkSettingsPermission(anyInt()); 4603 verify(mUserManager).hasUserRestrictionForUser( 4604 eq(UserManager.DISALLOW_NETWORK_RESET), any()); 4605 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4606 Message message = mMessageCaptor.getValue(); 4607 assertEquals(WifiP2pManager.FACTORY_RESET_FAILED, message.what); 4608 assertEquals(WifiP2pManager.ERROR, message.arg1); 4609 } 4610 4611 /** 4612 * Verify WifiP2pManager.FACTORY_RESET_FAILED is returned when config wifi disallow. 4613 */ 4614 @Test testFactoryResetFailureWhenConfigWifiDisallow()4615 public void testFactoryResetFailureWhenConfigWifiDisallow() throws Exception { 4616 // Move to enabled state 4617 forceP2pEnabled(mClient1); 4618 4619 when(mWifiInjector.getUserManager()).thenReturn(mUserManager); 4620 when(mPackageManager.getNameForUid(anyInt())).thenReturn("testPkg"); 4621 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true); 4622 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_NETWORK_RESET), any())) 4623 .thenReturn(false); 4624 when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), any())) 4625 .thenReturn(true); 4626 sendSimpleMsg(mClientMessenger, WifiP2pManager.FACTORY_RESET); 4627 verify(mWifiInjector).getUserManager(); 4628 verify(mPackageManager).getNameForUid(anyInt()); 4629 verify(mWifiPermissionsUtil).checkNetworkSettingsPermission(anyInt()); 4630 verify(mUserManager).hasUserRestrictionForUser( 4631 eq(UserManager.DISALLOW_NETWORK_RESET), any()); 4632 verify(mUserManager).hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI), any()); 4633 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4634 Message message = mMessageCaptor.getValue(); 4635 assertEquals(WifiP2pManager.FACTORY_RESET_FAILED, message.what); 4636 assertEquals(WifiP2pManager.ERROR, message.arg1); 4637 } 4638 4639 /** 4640 * Verify WifiP2pManager.FACTORY_RESET_FAILED is returned when p2p is unsupported. 4641 */ 4642 @Test testFactoryResetFailureWhenP2pUnsupported()4643 public void testFactoryResetFailureWhenP2pUnsupported() throws Exception { 4644 setUpWifiP2pServiceImpl(false); 4645 4646 sendSimpleMsg(mClientMessenger, WifiP2pManager.FACTORY_RESET); 4647 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4648 Message message = mMessageCaptor.getValue(); 4649 assertEquals(WifiP2pManager.FACTORY_RESET_FAILED, message.what); 4650 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 4651 } 4652 4653 /** 4654 * Verify the caller sends WifiP2pManager.SET_ONGOING_PEER_CONFIG. 4655 */ 4656 @Test testSetOngingPeerConfigSuccess()4657 public void testSetOngingPeerConfigSuccess() throws Exception { 4658 forceP2pEnabled(mClient1); 4659 mockPeersList(); 4660 WifiP2pConfig config = new WifiP2pConfig(); 4661 config.deviceAddress = mTestWifiP2pDevice.deviceAddress; 4662 4663 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(true); 4664 sendSetOngoingPeerConfigMsg(mClientMessenger, config); 4665 4666 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4667 Message message = mMessageCaptor.getValue(); 4668 assertEquals(WifiP2pManager.SET_ONGOING_PEER_CONFIG_SUCCEEDED, message.what); 4669 } 4670 4671 /** 4672 * Verify WifiP2pManager.SET_ONGOING_PEER_CONFIG_FAILED is returned without NETWORK_STACK 4673 * permission. 4674 */ 4675 @Test testSetOngingPeerConfigFailureWithoutPermission()4676 public void testSetOngingPeerConfigFailureWithoutPermission() throws Exception { 4677 forceP2pEnabled(mClient1); 4678 mockPeersList(); 4679 WifiP2pConfig config = new WifiP2pConfig(); 4680 4681 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(false); 4682 sendSetOngoingPeerConfigMsg(mClientMessenger, config); 4683 4684 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4685 Message message = mMessageCaptor.getValue(); 4686 assertEquals(WifiP2pManager.SET_ONGOING_PEER_CONFIG_FAILED, message.what); 4687 } 4688 4689 /** 4690 * Verify WifiP2pManager.SET_ONGOING_PEER_CONFIG_FAILED is returned with invalid peer config. 4691 */ 4692 @Test testSetOngoingPeerConfigFailureWithInvalidPeerConfig()4693 public void testSetOngoingPeerConfigFailureWithInvalidPeerConfig() throws Exception { 4694 forceP2pEnabled(mClient1); 4695 mockPeersList(); 4696 WifiP2pConfig config = new WifiP2pConfig(); 4697 4698 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(true); 4699 sendSetOngoingPeerConfigMsg(mClientMessenger, config); 4700 4701 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4702 Message message = mMessageCaptor.getValue(); 4703 assertEquals(WifiP2pManager.SET_ONGOING_PEER_CONFIG_FAILED, message.what); 4704 } 4705 4706 /** 4707 * Verify that respond with RESPONSE_ONGOING_PEER_CONFIG 4708 * when caller sends REQUEST_ONGOING_PEER_CONFIG and permission is granted. 4709 */ 4710 @Test testRequestOngoingPeerConfigSuccess()4711 public void testRequestOngoingPeerConfigSuccess() throws Exception { 4712 forceP2pEnabled(mClient1); 4713 4714 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(true); 4715 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_ONGOING_PEER_CONFIG); 4716 4717 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4718 Message message = mMessageCaptor.getValue(); 4719 WifiP2pConfig config = (WifiP2pConfig) message.obj; 4720 assertEquals(WifiP2pManager.RESPONSE_ONGOING_PEER_CONFIG, message.what); 4721 assertNotNull(config); 4722 } 4723 4724 /** 4725 * Verify that respond with RESPONSE_ONGOING_PEER_CONFIG 4726 * when caller sends REQUEST_ONGOING_PEER_CONFIG and has no NETWORK_STACK permission. 4727 */ 4728 @Test testRequestOngoingPeerConfigFailureWithoutPermission()4729 public void testRequestOngoingPeerConfigFailureWithoutPermission() throws Exception { 4730 forceP2pEnabled(mClient1); 4731 4732 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(false); 4733 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_ONGOING_PEER_CONFIG); 4734 4735 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4736 Message message = mMessageCaptor.getValue(); 4737 WifiP2pConfig config = (WifiP2pConfig) message.obj; 4738 assertEquals(WifiP2pManager.RESPONSE_ONGOING_PEER_CONFIG, message.what); 4739 assertNull(config); 4740 } 4741 4742 /** 4743 * Verify that respond with RESPONSE_PERSISTENT_GROUP_INFO 4744 * when caller sends REQUEST_PERSISTENT_GROUP_INFO. 4745 */ 4746 @Test testRequestPersistentGroupInfoSuccess()4747 public void testRequestPersistentGroupInfoSuccess() throws Exception { 4748 // Ensure our own MAC address is not anonymized in the result 4749 when(mWifiPermissionsUtil.checkLocalMacAddressPermission(anyInt())).thenReturn(true); 4750 forceP2pEnabled(mClient1); 4751 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 4752 4753 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_PERSISTENT_GROUP_INFO); 4754 4755 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4756 Message message = mMessageCaptor.getValue(); 4757 WifiP2pGroupList groups = (WifiP2pGroupList) message.obj; 4758 assertEquals(WifiP2pManager.RESPONSE_PERSISTENT_GROUP_INFO, message.what); 4759 // WifiP2pGroupList does not implement equals operator, 4760 // use toString to compare two lists. 4761 assertEquals(mGroups.toString(), groups.toString()); 4762 } 4763 4764 /** 4765 * Verify that when no permissions are held, an empty {@link WifiP2pGroupList} is returned. 4766 */ 4767 @Test testRequestPersistentGroupInfoNoPermissionFailure()4768 public void testRequestPersistentGroupInfoNoPermissionFailure() throws Exception { 4769 // Ensure our own MAC address is not anonymized in the result 4770 forceP2pEnabled(mClient1); 4771 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 4772 4773 // no permissions held 4774 when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false); 4775 when(mWifiPermissionsUtil.checkNetworkStackPermission(anyInt())).thenReturn(false); 4776 when(mWifiPermissionsUtil.checkReadWifiCredentialPermission(anyInt())).thenReturn(false); 4777 4778 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_PERSISTENT_GROUP_INFO); 4779 4780 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4781 Message message = mMessageCaptor.getValue(); 4782 WifiP2pGroupList groups = (WifiP2pGroupList) message.obj; 4783 assertEquals(WifiP2pManager.RESPONSE_PERSISTENT_GROUP_INFO, message.what); 4784 // WifiP2pGroupList does not implement equals operator, 4785 // use toString to compare two lists. 4786 // Expect empty WifiP2pGroupList() 4787 assertEquals(new WifiP2pGroupList().toString(), groups.toString()); 4788 } 4789 4790 /** 4791 * Verify that respond with RESPONSE_PERSISTENT_GROUP_INFO 4792 * when caller sends REQUEST_PERSISTENT_GROUP_INFO without LOCATION_FINE permission. 4793 */ 4794 @Test testRequestPersistentGroupInfoNoLocationFinePermission()4795 public void testRequestPersistentGroupInfoNoLocationFinePermission() throws Exception { 4796 assumeTrue(SdkLevel.isAtLeastT()); 4797 // Ensure our own MAC address is not anonymized in the result 4798 when(mWifiPermissionsUtil.checkLocalMacAddressPermission(anyInt())).thenReturn(true); 4799 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 4800 .thenReturn(false); 4801 when(mWifiPermissionsUtil.isTargetSdkLessThan(any(), 4802 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false); 4803 when(mWifiPermissionsUtil.checkCallersLocationPermission( 4804 anyString(), anyString(), anyInt(), anyBoolean(), any())).thenReturn(false); 4805 forceP2pEnabled(mClient1); 4806 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 4807 4808 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_PERSISTENT_GROUP_INFO); 4809 4810 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4811 Message message = mMessageCaptor.getValue(); 4812 WifiP2pGroupList groups = (WifiP2pGroupList) message.obj; 4813 assertEquals(WifiP2pManager.RESPONSE_PERSISTENT_GROUP_INFO, message.what); 4814 // WifiP2pGroupList does not implement equals operator, 4815 // use toString to compare two lists. 4816 // Expect empty WifiP2pGroupList() 4817 assertEquals(new WifiP2pGroupList().toString(), groups.toString()); 4818 } 4819 4820 /** 4821 * Verify that respond with RESPONSE_CONNECTION_INFO 4822 * when caller sends REQUEST_CONNECTION_INFO. 4823 */ 4824 @Test testRequestConnectionInfoSuccess()4825 public void testRequestConnectionInfoSuccess() throws Exception { 4826 forceP2pEnabled(mClient1); 4827 4828 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_CONNECTION_INFO); 4829 4830 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4831 Message message = mMessageCaptor.getValue(); 4832 WifiP2pInfo info = (WifiP2pInfo) message.obj; 4833 assertEquals(WifiP2pManager.RESPONSE_CONNECTION_INFO, message.what); 4834 // WifiP2pInfo does not implement equals operator, 4835 // use toString to compare two objects. 4836 assertEquals((new WifiP2pInfo()).toString(), info.toString()); 4837 } 4838 4839 /** 4840 * Verify that respond with RESPONSE_P2P_STATE 4841 * when caller sends REQUEST_P2P_STATE and p2p is enabled. 4842 */ 4843 @Test testRequestP2pStateEnabled()4844 public void testRequestP2pStateEnabled() throws Exception { 4845 forceP2pEnabled(mClient1); 4846 4847 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_P2P_STATE); 4848 4849 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4850 Message message = mMessageCaptor.getValue(); 4851 assertEquals(WifiP2pManager.RESPONSE_P2P_STATE, message.what); 4852 assertEquals(WifiP2pManager.WIFI_P2P_STATE_ENABLED, message.arg1); 4853 } 4854 4855 /** 4856 * Verify that respond with RESPONSE_P2P_STATE 4857 * when caller sends REQUEST_P2P_STATE and p2p is disabled. 4858 */ 4859 @Test testRequestP2pStateDisabled()4860 public void testRequestP2pStateDisabled() throws Exception { 4861 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_P2P_STATE); 4862 4863 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4864 Message message = mMessageCaptor.getValue(); 4865 assertEquals(WifiP2pManager.RESPONSE_P2P_STATE, message.what); 4866 assertEquals(WifiP2pManager.WIFI_P2P_STATE_DISABLED, message.arg1); 4867 } 4868 4869 /** 4870 * Verify that respond with RESPONSE_DISCOVERY_STATE 4871 * when caller sends REQUEST_DISCOVERY_STATE and discovery is started. 4872 */ 4873 @Test testRequestDiscoveryStateWhenStarted()4874 public void testRequestDiscoveryStateWhenStarted() throws Exception { 4875 forceP2pEnabled(mClient1); 4876 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(any(), any(), 4877 anyInt(), anyBoolean())).thenReturn(false); 4878 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(eq("testPkg1"), eq("testFeature"), 4879 anyInt(), anyBoolean())).thenReturn(true); 4880 when(mWifiNative.p2pFind(anyInt())).thenReturn(true); 4881 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 4882 sendDiscoverPeersMsg(mClientMessenger); 4883 verify(mWifiNative).p2pFind(anyInt()); 4884 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 4885 eq("testPkg1"), eq("testFeature"), anyInt(), eq(true)); 4886 4887 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DISCOVERY_STATE); 4888 4889 // there are 2 responses: 4890 // * WifiP2pManager.DISCOVER_PEERS_SUCCEEDED 4891 // * WifiP2pManager.RESPONSE_DISCOVERY_STATE 4892 verify(mClientHandler, times(2)).sendMessage(mMessageCaptor.capture()); 4893 List<Message> messages = mMessageCaptor.getAllValues(); 4894 assertEquals(WifiP2pManager.DISCOVER_PEERS_SUCCEEDED, messages.get(0).what); 4895 assertEquals(WifiP2pManager.RESPONSE_DISCOVERY_STATE, messages.get(1).what); 4896 assertEquals(WifiP2pManager.WIFI_P2P_DISCOVERY_STARTED, messages.get(1).arg1); 4897 } 4898 4899 /** 4900 * Verify that respond with RESPONSE_DISCOVERY_STATE 4901 * when caller sends REQUEST_DISCOVERY_STATE and discovery is stopped. 4902 */ 4903 @Test testRequestDiscoveryStateWhenStopped()4904 public void testRequestDiscoveryStateWhenStopped() throws Exception { 4905 forceP2pEnabled(mClient1); 4906 4907 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_DISCOVERY_STATE); 4908 4909 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4910 Message message = mMessageCaptor.getValue(); 4911 assertEquals(WifiP2pManager.RESPONSE_DISCOVERY_STATE, message.what); 4912 assertEquals(WifiP2pManager.WIFI_P2P_DISCOVERY_STOPPED, message.arg1); 4913 } 4914 4915 /** 4916 * Verify that respond with RESPONSE_NETWORK_INFO 4917 * when caller sends REQUEST_NETWORK_INFO. 4918 */ 4919 @Test testRequestNetworkInfoSuccess()4920 public void testRequestNetworkInfoSuccess() throws Exception { 4921 NetworkInfo info_gold = 4922 new NetworkInfo(ConnectivityManager.TYPE_WIFI_P2P, 0, "WIFI_P2P", ""); 4923 4924 sendSimpleMsg(mClientMessenger, WifiP2pManager.REQUEST_NETWORK_INFO); 4925 4926 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4927 Message message = mMessageCaptor.getValue(); 4928 NetworkInfo info = (NetworkInfo) message.obj; 4929 assertEquals(WifiP2pManager.RESPONSE_NETWORK_INFO, message.what); 4930 assertEquals(info_gold.toString(), info.toString()); 4931 } 4932 4933 /** 4934 * Verify the caller sends WifiP2pManager.REMOVE_LOCAL_SERVICE. 4935 */ 4936 @Test testRemoveLocalServiceSuccess()4937 public void testRemoveLocalServiceSuccess() throws Exception { 4938 setTargetSdkGreaterThanT(); 4939 forceP2pEnabled(mClient1); 4940 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 4941 verifyAddLocalService(); 4942 4943 sendRemoveLocalServiceMsg(mClientMessenger, mTestWifiP2pServiceInfo); 4944 verify(mWifiNative).p2pServiceDel(any(WifiP2pServiceInfo.class)); 4945 4946 assertTrue(mClientHandler.hasMessages(WifiP2pManager.REMOVE_LOCAL_SERVICE_SUCCEEDED)); 4947 } 4948 4949 /** 4950 * Verify the caller sends WifiP2pManager.REMOVE_LOCAL_SERVICE without client info. 4951 */ 4952 @Test testRemoveLocalServiceSuccessWithoutClientInfo()4953 public void testRemoveLocalServiceSuccessWithoutClientInfo() throws Exception { 4954 forceP2pEnabled(mClient1); 4955 4956 sendRemoveLocalServiceMsg(mClientMessenger, mTestWifiP2pServiceInfo); 4957 verify(mWifiNative, never()).p2pServiceDel(any(WifiP2pServiceInfo.class)); 4958 4959 assertTrue(mClientHandler.hasMessages(WifiP2pManager.REMOVE_LOCAL_SERVICE_SUCCEEDED)); 4960 } 4961 4962 /** 4963 * Verify the caller sends WifiP2pManager.REMOVE_LOCAL_SERVICE when service info is null. 4964 */ 4965 @Test testRemoveLocalServiceSuccessWithNullServiceInfo()4966 public void testRemoveLocalServiceSuccessWithNullServiceInfo() throws Exception { 4967 setTargetSdkGreaterThanT(); 4968 forceP2pEnabled(mClient1); 4969 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 4970 verifyAddLocalService(); 4971 4972 sendRemoveLocalServiceMsg(mClientMessenger, null); 4973 verify(mWifiNative, never()).p2pServiceDel(any(WifiP2pServiceInfo.class)); 4974 4975 assertTrue(mClientHandler.hasMessages(WifiP2pManager.REMOVE_LOCAL_SERVICE_SUCCEEDED)); 4976 } 4977 4978 /** 4979 * Verify that respond with REMOVE_LOCAL_SERVICE_FAILED 4980 * when caller sends REMOVE_LOCAL_SERVICE and p2p is disabled. 4981 */ 4982 @Test testRemoveLocalServiceFailureWhenP2pDisabled()4983 public void testRemoveLocalServiceFailureWhenP2pDisabled() throws Exception { 4984 sendRemoveLocalServiceMsg(mClientMessenger, null); 4985 verify(mWifiNative, never()).p2pServiceDel(any(WifiP2pServiceInfo.class)); 4986 4987 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 4988 Message message = mMessageCaptor.getValue(); 4989 assertEquals(WifiP2pManager.REMOVE_LOCAL_SERVICE_FAILED, message.what); 4990 assertEquals(WifiP2pManager.BUSY, message.arg1); 4991 } 4992 4993 /** 4994 * Verify that respond with REMOVE_LOCAL_SERVICE_FAILED 4995 * when caller sends REMOVE_LOCAL_SERVICE and p2p is unsupported. 4996 */ 4997 @Test testRemoveLocalServiceFailureWhenP2pUnsupported()4998 public void testRemoveLocalServiceFailureWhenP2pUnsupported() throws Exception { 4999 setUpWifiP2pServiceImpl(false); 5000 5001 sendRemoveLocalServiceMsg(mClientMessenger, null); 5002 verify(mWifiNative, never()).p2pServiceDel(any(WifiP2pServiceInfo.class)); 5003 5004 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5005 Message message = mMessageCaptor.getValue(); 5006 assertEquals(WifiP2pManager.REMOVE_LOCAL_SERVICE_FAILED, message.what); 5007 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 5008 } 5009 5010 /** 5011 * Verify the caller sends WifiP2pManager.CLEAR_LOCAL_SERVICES. 5012 */ 5013 @Test testClearLocalServiceSuccess()5014 public void testClearLocalServiceSuccess() throws Exception { 5015 setTargetSdkGreaterThanT(); 5016 forceP2pEnabled(mClient1); 5017 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5018 verifyAddLocalService(); 5019 5020 sendSimpleMsg(mClientMessenger, WifiP2pManager.CLEAR_LOCAL_SERVICES); 5021 verify(mWifiNative, atLeastOnce()).p2pServiceDel(any(WifiP2pServiceInfo.class)); 5022 5023 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CLEAR_LOCAL_SERVICES_SUCCEEDED)); 5024 } 5025 5026 /** 5027 * Verify the caller sends WifiP2pManager.CLEAR_LOCAL_SERVICES without client info. 5028 */ 5029 @Test testClearLocalServiceSuccessWithoutClientInfo()5030 public void testClearLocalServiceSuccessWithoutClientInfo() throws Exception { 5031 forceP2pEnabled(mClient1); 5032 5033 sendSimpleMsg(mClientMessenger, WifiP2pManager.CLEAR_LOCAL_SERVICES); 5034 verify(mWifiNative, never()).p2pServiceDel(any(WifiP2pServiceInfo.class)); 5035 5036 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CLEAR_LOCAL_SERVICES_SUCCEEDED)); 5037 } 5038 5039 /** 5040 * Verify that respond with CLEAR_LOCAL_SERVICES_FAILED 5041 * when caller sends CLEAR_LOCAL_SERVICES and p2p is disabled. 5042 */ 5043 @Test testClearLocalServiceFailureWhenP2pDisabled()5044 public void testClearLocalServiceFailureWhenP2pDisabled() throws Exception { 5045 sendSimpleMsg(mClientMessenger, WifiP2pManager.CLEAR_LOCAL_SERVICES); 5046 verify(mWifiNative, never()).p2pServiceDel(any(WifiP2pServiceInfo.class)); 5047 5048 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5049 Message message = mMessageCaptor.getValue(); 5050 assertEquals(WifiP2pManager.CLEAR_LOCAL_SERVICES_FAILED, message.what); 5051 assertEquals(WifiP2pManager.BUSY, message.arg1); 5052 } 5053 5054 /** 5055 * Verify that respond with CLEAR_LOCAL_SERVICES_FAILED 5056 * when caller sends CLEAR_LOCAL_SERVICES and p2p is unsupported. 5057 */ 5058 @Test testClearLocalServiceFailureWhenP2pUnsupported()5059 public void testClearLocalServiceFailureWhenP2pUnsupported() throws Exception { 5060 setUpWifiP2pServiceImpl(false); 5061 5062 sendSimpleMsg(mClientMessenger, WifiP2pManager.CLEAR_LOCAL_SERVICES); 5063 verify(mWifiNative, never()).p2pServiceDel(any(WifiP2pServiceInfo.class)); 5064 5065 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5066 Message message = mMessageCaptor.getValue(); 5067 assertEquals(WifiP2pManager.CLEAR_LOCAL_SERVICES_FAILED, message.what); 5068 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 5069 } 5070 5071 /** 5072 * Verify the caller sends WifiP2pManager.ADD_SERVICE_REQUEST without services discover. 5073 */ 5074 @Test testAddServiceRequestNoOverflow()5075 public void testAddServiceRequestNoOverflow() throws Exception { 5076 forceP2pEnabled(mClient1); 5077 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5078 5079 for (int i = 0; i < 256; i++) { 5080 reset(mTestWifiP2pServiceRequest); 5081 sendAddServiceRequestMsg(mClientMessenger); 5082 ArgumentCaptor<Integer> idCaptor = ArgumentCaptor.forClass(int.class); 5083 verify(mTestWifiP2pServiceRequest).setTransactionId(idCaptor.capture()); 5084 assertTrue(idCaptor.getValue().intValue() > 0); 5085 } 5086 } 5087 verifyAddServiceRequest()5088 private void verifyAddServiceRequest() throws Exception { 5089 sendAddServiceRequestMsg(mClientMessenger); 5090 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_SERVICE_REQUEST_SUCCEEDED)); 5091 } 5092 5093 /** 5094 * Verify the caller sends WifiP2pManager.ADD_SERVICE_REQUEST without services discover. 5095 */ 5096 @Test testAddServiceRequestSuccessWithoutServiceDiscover()5097 public void testAddServiceRequestSuccessWithoutServiceDiscover() throws Exception { 5098 forceP2pEnabled(mClient1); 5099 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5100 verifyAddServiceRequest(); 5101 } 5102 5103 /** 5104 * Verify the caller sends WifiP2pManager.ADD_SERVICE_REQUEST with services discover. 5105 */ 5106 @Test testAddServiceRequestSuccessWithServiceDiscover()5107 public void testAddServiceRequestSuccessWithServiceDiscover() throws Exception { 5108 testDiscoverServicesSuccess(); 5109 5110 sendAddServiceRequestMsg(mClientMessenger); 5111 verify(mWifiNative, atLeastOnce()).p2pServDiscReq(eq("00:00:00:00:00:00"), anyString()); 5112 5113 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_SERVICE_REQUEST_SUCCEEDED)); 5114 } 5115 5116 /** 5117 * Verify WifiP2pManager.ADD_SERVICE_REQUEST_FAILED is returned with null request. 5118 */ 5119 @Test testAddServiceRequestFailureWithNullRequest()5120 public void testAddServiceRequestFailureWithNullRequest() throws Exception { 5121 forceP2pEnabled(mClient1); 5122 5123 sendSimpleMsg(mClientMessenger, WifiP2pManager.ADD_SERVICE_REQUEST, null); 5124 5125 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_SERVICE_REQUEST_FAILED)); 5126 } 5127 5128 /** 5129 * Verify WifiP2pManager.ADD_SERVICE_REQUEST_FAILED is returned without client info. 5130 */ 5131 @Test testAddServiceRequestFailureWithoutClientInfo()5132 public void testAddServiceRequestFailureWithoutClientInfo() throws Exception { 5133 forceP2pEnabled(mClient1); 5134 5135 sendAddServiceRequestMsg(mClientMessenger); 5136 5137 assertTrue(mClientHandler.hasMessages(WifiP2pManager.ADD_SERVICE_REQUEST_FAILED)); 5138 } 5139 5140 /** 5141 * Verify that respond with ADD_SERVICE_REQUEST_FAILED 5142 * when caller sends ADD_SERVICE_REQUEST and p2p is disabled. 5143 */ 5144 @Test testAddServiceRequestFailureWhenP2pDisabled()5145 public void testAddServiceRequestFailureWhenP2pDisabled() throws Exception { 5146 sendAddServiceRequestMsg(mClientMessenger); 5147 5148 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5149 Message message = mMessageCaptor.getValue(); 5150 assertEquals(WifiP2pManager.ADD_SERVICE_REQUEST_FAILED, message.what); 5151 assertEquals(WifiP2pManager.BUSY, message.arg1); 5152 } 5153 5154 /** 5155 * Verify that respond with ADD_SERVICE_REQUEST_FAILED 5156 * when caller sends ADD_SERVICE_REQUEST and p2p is unsupported. 5157 */ 5158 @Test testAddServiceRequestFailureWhenP2pUnsupported()5159 public void testAddServiceRequestFailureWhenP2pUnsupported() throws Exception { 5160 setUpWifiP2pServiceImpl(false); 5161 5162 sendAddServiceRequestMsg(mClientMessenger); 5163 5164 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5165 Message message = mMessageCaptor.getValue(); 5166 assertEquals(WifiP2pManager.ADD_SERVICE_REQUEST_FAILED, message.what); 5167 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 5168 } 5169 5170 /** 5171 * Verify the caller sends WifiP2pManager.REMOVE_SERVICE_REQUEST. 5172 */ 5173 @Test testRemoveServiceRequestSuccess()5174 public void testRemoveServiceRequestSuccess() throws Exception { 5175 forceP2pEnabled(mClient1); 5176 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5177 verifyAddServiceRequest(); 5178 5179 sendRemoveServiceRequestMsg(mClientMessenger, mTestWifiP2pServiceRequest); 5180 5181 assertTrue(mClientHandler.hasMessages(WifiP2pManager.REMOVE_SERVICE_REQUEST_SUCCEEDED)); 5182 } 5183 5184 /** 5185 * Verify the caller sends WifiP2pManager.REMOVE_SERVICE_REQUEST without client info. 5186 */ 5187 @Test testRemoveServiceRequestSuccessWithoutClientInfo()5188 public void testRemoveServiceRequestSuccessWithoutClientInfo() throws Exception { 5189 forceP2pEnabled(mClient1); 5190 5191 sendRemoveServiceRequestMsg(mClientMessenger, mTestWifiP2pServiceRequest); 5192 5193 assertTrue(mClientHandler.hasMessages(WifiP2pManager.REMOVE_SERVICE_REQUEST_SUCCEEDED)); 5194 } 5195 5196 /** 5197 * Verify the caller sends WifiP2pManager.REMOVE_SERVICE_REQUEST when service info is null. 5198 */ 5199 @Test testRemoveServiceRequestSuccessWithNullServiceInfo()5200 public void testRemoveServiceRequestSuccessWithNullServiceInfo() throws Exception { 5201 setTargetSdkGreaterThanT(); 5202 forceP2pEnabled(mClient1); 5203 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5204 verifyAddLocalService(); 5205 5206 sendRemoveServiceRequestMsg(mClientMessenger, null); 5207 5208 assertTrue(mClientHandler.hasMessages(WifiP2pManager.REMOVE_SERVICE_REQUEST_SUCCEEDED)); 5209 } 5210 5211 /** 5212 * Verify that respond with REMOVE_SERVICE_REQUEST_FAILED 5213 * when caller sends REMOVE_SERVICE_REQUEST and p2p is disabled. 5214 */ 5215 @Test testRemoveServiceRequestFailureWhenP2pDisabled()5216 public void testRemoveServiceRequestFailureWhenP2pDisabled() throws Exception { 5217 sendRemoveServiceRequestMsg(mClientMessenger, null); 5218 5219 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5220 Message message = mMessageCaptor.getValue(); 5221 assertEquals(WifiP2pManager.REMOVE_SERVICE_REQUEST_FAILED, message.what); 5222 assertEquals(WifiP2pManager.BUSY, message.arg1); 5223 } 5224 5225 /** 5226 * Verify that respond with REMOVE_SERVICE_REQUEST_FAILED 5227 * when caller sends REMOVE_SERVICE_REQUEST and p2p is unsupported. 5228 */ 5229 @Test testRemoveServiceRequestFailureWhenP2pUnsupported()5230 public void testRemoveServiceRequestFailureWhenP2pUnsupported() throws Exception { 5231 setUpWifiP2pServiceImpl(false); 5232 5233 sendRemoveServiceRequestMsg(mClientMessenger, null); 5234 5235 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5236 Message message = mMessageCaptor.getValue(); 5237 assertEquals(WifiP2pManager.REMOVE_SERVICE_REQUEST_FAILED, message.what); 5238 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 5239 } 5240 5241 /** 5242 * Verify the caller sends WifiP2pManager.CLEAR_SERVICE_REQUESTS. 5243 */ 5244 @Test testClearServiceRequestsSuccess()5245 public void testClearServiceRequestsSuccess() throws Exception { 5246 forceP2pEnabled(mClient1); 5247 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5248 verifyAddServiceRequest(); 5249 5250 sendSimpleMsg(mClientMessenger, WifiP2pManager.CLEAR_SERVICE_REQUESTS); 5251 5252 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CLEAR_SERVICE_REQUESTS_SUCCEEDED)); 5253 } 5254 5255 /** 5256 * Verify the caller sends WifiP2pManager.CLEAR_SERVICE_REQUESTS without client info. 5257 */ 5258 @Test testClearServiceRequestsSuccessWithoutClientInfo()5259 public void testClearServiceRequestsSuccessWithoutClientInfo() throws Exception { 5260 forceP2pEnabled(mClient1); 5261 5262 sendSimpleMsg(mClientMessenger, WifiP2pManager.CLEAR_SERVICE_REQUESTS); 5263 5264 assertTrue(mClientHandler.hasMessages(WifiP2pManager.CLEAR_SERVICE_REQUESTS_SUCCEEDED)); 5265 } 5266 5267 /** 5268 * Verify that respond with CLEAR_SERVICE_REQUESTS_FAILED 5269 * when caller sends CLEAR_SERVICE_REQUEST and p2p is disabled. 5270 */ 5271 @Test testClearServiceRequestsFailureWhenP2pDisabled()5272 public void testClearServiceRequestsFailureWhenP2pDisabled() throws Exception { 5273 sendSimpleMsg(mClientMessenger, WifiP2pManager.CLEAR_SERVICE_REQUESTS); 5274 5275 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5276 Message message = mMessageCaptor.getValue(); 5277 assertEquals(WifiP2pManager.CLEAR_SERVICE_REQUESTS_FAILED, message.what); 5278 assertEquals(WifiP2pManager.BUSY, message.arg1); 5279 } 5280 5281 /** 5282 * Verify that respond with CLEAR_SERVICE_REQUESTS_FAILED 5283 * when caller sends CLEAR_SERVICE_REQUEST and p2p is unsupported. 5284 */ 5285 @Test testClearServiceRequestsFailureWhenP2pUnsupported()5286 public void testClearServiceRequestsFailureWhenP2pUnsupported() throws Exception { 5287 setUpWifiP2pServiceImpl(false); 5288 5289 sendSimpleMsg(mClientMessenger, WifiP2pManager.CLEAR_SERVICE_REQUESTS); 5290 5291 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5292 Message message = mMessageCaptor.getValue(); 5293 assertEquals(WifiP2pManager.CLEAR_SERVICE_REQUESTS_FAILED, message.what); 5294 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 5295 } 5296 5297 /** 5298 * Verify when prior to Android T, stopping discovery is executed when location mode is 5299 * turned off. 5300 */ 5301 @Test testStopDiscoveryWhenLocationModeIsDisabled()5302 public void testStopDiscoveryWhenLocationModeIsDisabled() throws Exception { 5303 forceP2pEnabled(mClient1); 5304 simulateLocationModeChange(false); 5305 mLooper.dispatchAll(); 5306 if (SdkLevel.isAtLeastT()) { 5307 verify(mWifiNative, never()).p2pStopFind(); 5308 } else { 5309 verify(mWifiNative).p2pStopFind(); 5310 } 5311 } 5312 5313 /** 5314 * Verify a network name which is too long is rejected. 5315 */ 5316 @Test testSendConnectMsgWithTooLongNetworkName()5317 public void testSendConnectMsgWithTooLongNetworkName() throws Exception { 5318 mTestWifiP2pFastConnectionConfig.networkName = "DIRECT-xy-abcdefghijklmnopqrstuvw"; 5319 sendConnectMsg(mClientMessenger, mTestWifiP2pFastConnectionConfig); 5320 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5321 Message message = mMessageCaptor.getValue(); 5322 assertEquals(WifiP2pManager.CONNECT_FAILED, message.what); 5323 } 5324 5325 /** 5326 * Verify a network name which is too short is rejected. 5327 */ 5328 @Test testSendConnectMsgWithTooShortNetworkName()5329 public void testSendConnectMsgWithTooShortNetworkName() throws Exception { 5330 setTargetSdkGreaterThanT(); 5331 mTestWifiP2pFastConnectionConfig.networkName = "DIRECT-x"; 5332 forceP2pEnabled(mClient1); 5333 when(mWifiNative.p2pGroupAdd(any(), eq(true))).thenReturn(true); 5334 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5335 sendConnectMsg(mClientMessenger, mTestWifiP2pFastConnectionConfig); 5336 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5337 Message message = mMessageCaptor.getValue(); 5338 assertEquals(WifiP2pManager.CONNECT_FAILED, message.what); 5339 if (SdkLevel.isAtLeastT()) { 5340 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 5341 any(), eq(true), any()); 5342 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 5343 any(), any(), anyInt(), anyBoolean()); 5344 } else { 5345 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect( 5346 any(), any(), anyInt(), anyBoolean()); 5347 } 5348 } 5349 verifyGroupOwnerIntentSelection(int netId, int freq, int expectedGoIntent)5350 private void verifyGroupOwnerIntentSelection(int netId, int freq, int expectedGoIntent) 5351 throws Exception { 5352 when(mWifiInfo.getNetworkId()).thenReturn(netId); 5353 when(mWifiInfo.getFrequency()).thenReturn(freq); 5354 forceP2pEnabled(mClient1); 5355 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5356 5357 mockEnterProvisionDiscoveryState(); 5358 5359 WifiP2pProvDiscEvent pdEvent = new WifiP2pProvDiscEvent(); 5360 pdEvent.device = mTestWifiP2pDevice; 5361 sendSimpleMsg(null, 5362 WifiP2pMonitor.P2P_PROV_DISC_PBC_RSP_EVENT, 5363 pdEvent); 5364 5365 ArgumentCaptor<WifiP2pConfig> configCaptor = 5366 ArgumentCaptor.forClass(WifiP2pConfig.class); 5367 verify(mWifiNative).p2pConnect(configCaptor.capture(), anyBoolean()); 5368 WifiP2pConfig config = configCaptor.getValue(); 5369 assertEquals(expectedGoIntent, config.groupOwnerIntent); 5370 } 5371 5372 /** 5373 * Verify the group owner intent value is selected correctly when no STA connection. 5374 */ 5375 @Test testGroupOwnerIntentSelectionWithoutStaConnection()5376 public void testGroupOwnerIntentSelectionWithoutStaConnection() throws Exception { 5377 verifyGroupOwnerIntentSelection(WifiConfiguration.INVALID_NETWORK_ID, 2412, 5378 WifiP2pServiceImpl.DEFAULT_GROUP_OWNER_INTENT); 5379 } 5380 5381 /** 5382 * Verify the group owner intent value is selected correctly when 2.4GHz STA connection 5383 * without 2.4GHz/5GHz DBS support. 5384 */ 5385 @Test testGroupOwnerIntentSelectionWith24GStaConnectionWithout24g5gDbs()5386 public void testGroupOwnerIntentSelectionWith24GStaConnectionWithout24g5gDbs() 5387 throws Exception { 5388 verifyGroupOwnerIntentSelection(1, 2412, 5); 5389 } 5390 5391 /** 5392 * Verify the group owner intent value is selected correctly when 2.4GHz STA connection 5393 * with 2.4GHz/5GHz DBS support. 5394 */ 5395 @Test testGroupOwnerIntentSelectionWith24GStaConnectionWith24g5gDbs()5396 public void testGroupOwnerIntentSelectionWith24GStaConnectionWith24g5gDbs() throws Exception { 5397 when(mWifiNative.is24g5gDbsSupported()).thenReturn(true); 5398 verifyGroupOwnerIntentSelection(1, 2412, 7); 5399 } 5400 5401 /** 5402 * Verify the group owner intent value is selected correctly when 5GHz STA connection 5403 * without 2.4GHz/5GHz DBS and 5GHz/6GHz DBS support. 5404 */ 5405 @Test testGroupOwnerIntentSelectionWith5GHzStaConnectionWithout24g5gDbs5g6gDbs()5406 public void testGroupOwnerIntentSelectionWith5GHzStaConnectionWithout24g5gDbs5g6gDbs() 5407 throws Exception { 5408 verifyGroupOwnerIntentSelection(1, 5200, 10); 5409 } 5410 5411 /** 5412 * Verify the group owner intent value is selected correctly when 5GHz STA connection 5413 * with 2.4GHz/5GHz DBS and without 5GHz/6GHz DBS support. 5414 */ 5415 @Test testGroupOwnerIntentSelectionWith5GHzStaConnectionWith24g5gDbsWithout5g6gDbs()5416 public void testGroupOwnerIntentSelectionWith5GHzStaConnectionWith24g5gDbsWithout5g6gDbs() 5417 throws Exception { 5418 when(mWifiNative.is24g5gDbsSupported()).thenReturn(true); 5419 verifyGroupOwnerIntentSelection(1, 5200, 8); 5420 } 5421 5422 /** 5423 * Verify the group owner intent value is selected correctly when 5GHz STA connection 5424 * with 2.4GHz/5GHz DBS and 5GHz/6GHz DBS support. 5425 */ 5426 @Test testGroupOwnerIntentSelectionWith5GHzStaConnectionWith24g5gDbs5g6gDbs()5427 public void testGroupOwnerIntentSelectionWith5GHzStaConnectionWith24g5gDbs5g6gDbs() 5428 throws Exception { 5429 when(mWifiNative.is24g5gDbsSupported()).thenReturn(true); 5430 when(mWifiNative.is5g6gDbsSupported()).thenReturn(true); 5431 verifyGroupOwnerIntentSelection(1, 5200, 9); 5432 } 5433 5434 /** 5435 * Verify the group owner intent value is selected correctly when 6GHz STA connection 5436 * without 5GHz/6GHz DBS support. 5437 */ 5438 @Test testGroupOwnerIntentSelectionWith6GHzStaConnectionWithout5g6gDbs()5439 public void testGroupOwnerIntentSelectionWith6GHzStaConnectionWithout5g6gDbs() 5440 throws Exception { 5441 verifyGroupOwnerIntentSelection(1, 6000, 11); 5442 } 5443 5444 /** 5445 * Verify the group owner intent value is selected correctly when 6GHz STA connection 5446 * with 5GHz/6GHz DBS support. 5447 */ 5448 @Test testGroupOwnerIntentSelectionWith6GHzStaConnectionWith5g6gDbs()5449 public void testGroupOwnerIntentSelectionWith6GHzStaConnectionWith5g6gDbs() throws Exception { 5450 when(mWifiNative.is5g6gDbsSupported()).thenReturn(true); 5451 verifyGroupOwnerIntentSelection(1, 6000, 12); 5452 } 5453 5454 /** 5455 * Verify that a P2P_PROV_DISC_SHOW_PIN_EVENT for config method DISPLAY triggers an invitation 5456 * sent dialog with the correct PIN. 5457 */ 5458 @Test testProvisionDiscoveryShowPinEventLaunchesInvitationSentDialog()5459 public void testProvisionDiscoveryShowPinEventLaunchesInvitationSentDialog() throws Exception { 5460 when(mWifiInfo.getNetworkId()).thenReturn(WifiConfiguration.INVALID_NETWORK_ID); 5461 when(mWifiInfo.getFrequency()).thenReturn(2412); 5462 mTestWifiP2pPeerConfig.wps.setup = WpsInfo.DISPLAY; 5463 forceP2pEnabled(mClient1); 5464 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5465 5466 mockEnterProvisionDiscoveryState(); 5467 5468 WifiP2pProvDiscEvent pdEvent = new WifiP2pProvDiscEvent(); 5469 pdEvent.device = mTestWifiP2pDevice; 5470 pdEvent.pin = "pin"; 5471 sendSimpleMsg(null, 5472 WifiP2pMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT, 5473 pdEvent); 5474 5475 verify(mWifiNative).p2pConnect(any(), anyBoolean()); 5476 if (!SdkLevel.isAtLeastT()) { 5477 verify(mAlertDialog).show(); 5478 } else { 5479 verify(mWifiDialogManager).createP2pInvitationSentDialog( 5480 pdEvent.device.deviceName, pdEvent.pin, Display.DEFAULT_DISPLAY); 5481 verify(mDialogHandle).launchDialog(); 5482 } 5483 } 5484 5485 /** 5486 * Verify that a P2P_PROV_DISC_SHOW_PIN_EVENT for config method DISPLAY triggers an invitation 5487 * sent dialog with the correct PIN. 5488 */ 5489 @Test testProvisionDiscoveryShowPinEventInactiveStateLaunchesInvitationReceivedDialog()5490 public void testProvisionDiscoveryShowPinEventInactiveStateLaunchesInvitationReceivedDialog() 5491 throws Exception { 5492 when(mWifiInfo.getNetworkId()).thenReturn(WifiConfiguration.INVALID_NETWORK_ID); 5493 when(mWifiInfo.getFrequency()).thenReturn(2412); 5494 mTestWifiP2pPeerConfig.wps.setup = WpsInfo.DISPLAY; 5495 forceP2pEnabled(mClient1); 5496 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5497 5498 sendDeviceFoundEventMsg(mTestWifiP2pDevice); 5499 WifiP2pProvDiscEvent pdEvent = new WifiP2pProvDiscEvent(); 5500 pdEvent.device = mTestWifiP2pDevice; 5501 pdEvent.pin = "pin"; 5502 sendSimpleMsg(null, 5503 WifiP2pMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT, 5504 pdEvent); 5505 5506 if (!SdkLevel.isAtLeastT()) { 5507 verify(mAlertDialog).show(); 5508 } else { 5509 verify(mWifiDialogManager).createP2pInvitationReceivedDialog( 5510 eq(pdEvent.device.deviceName), eq(false), eq(pdEvent.pin), 5511 anyInt(), any(), any()); 5512 verify(mDialogHandle).launchDialog(); 5513 } 5514 } 5515 setupCoexMock(int restrictionBits)5516 private List<CoexUnsafeChannel> setupCoexMock(int restrictionBits) { 5517 assumeTrue(SdkLevel.isAtLeastS()); 5518 List<CoexUnsafeChannel> unsafeChannels = new ArrayList<>(); 5519 unsafeChannels.add(new CoexUnsafeChannel(WifiScanner.WIFI_BAND_24_GHZ, 1)); 5520 unsafeChannels.add(new CoexUnsafeChannel(WifiScanner.WIFI_BAND_24_GHZ, 2)); 5521 unsafeChannels.add(new CoexUnsafeChannel(WifiScanner.WIFI_BAND_24_GHZ, 3)); 5522 unsafeChannels.add(new CoexUnsafeChannel(WifiScanner.WIFI_BAND_5_GHZ, 36)); 5523 unsafeChannels.add(new CoexUnsafeChannel(WifiScanner.WIFI_BAND_5_GHZ, 40)); 5524 unsafeChannels.add(new CoexUnsafeChannel(WifiScanner.WIFI_BAND_5_GHZ, 165)); 5525 when(mCoexManager.getCoexRestrictions()).thenReturn(restrictionBits); 5526 when(mCoexManager.getCoexUnsafeChannels()).thenReturn(unsafeChannels); 5527 when(mWifiNative.p2pSetListenChannel(anyInt())).thenReturn(true); 5528 when(mWifiNative.p2pSetOperatingChannel(anyInt(), any())).thenReturn(true); 5529 return unsafeChannels; 5530 } 5531 5532 /** Verify P2P unsafe channels are set if P2P bit presents in restriction bits. */ 5533 @Test testCoexCallbackWithWifiP2pUnsafeChannels()5534 public void testCoexCallbackWithWifiP2pUnsafeChannels() throws Exception { 5535 assumeTrue(SdkLevel.isAtLeastS()); 5536 setupCoexMock(0); 5537 assertNotNull(mCoexListener); 5538 forceP2pEnabled(mClient1); 5539 mLooper.dispatchAll(); 5540 5541 List<CoexUnsafeChannel> unsafeChannels = 5542 setupCoexMock(WifiManager.COEX_RESTRICTION_WIFI_DIRECT); 5543 mCoexListener.onCoexUnsafeChannelsChanged(); 5544 mLooper.dispatchAll(); 5545 5546 // On entering P2pEnabledState, these are called once first. 5547 verify(mWifiNative, times(2)).p2pSetListenChannel(eq(0)); 5548 ArgumentCaptor<List<CoexUnsafeChannel>> unsafeChannelsCaptor = 5549 ArgumentCaptor.forClass(List.class); 5550 verify(mWifiNative, times(2)).p2pSetOperatingChannel(eq(0), unsafeChannelsCaptor.capture()); 5551 List<List<CoexUnsafeChannel>> capturedUnsafeChannelsList = 5552 unsafeChannelsCaptor.getAllValues(); 5553 // The second one is what we sent. 5554 assertEquals(unsafeChannels, capturedUnsafeChannelsList.get(1)); 5555 } 5556 5557 /** Verify P2P unsafe channels are cleared if P2P bit does not present in restriction bits. */ 5558 @Test testCoexCallbackWithoutWifiP2pInRestrictionBits()5559 public void testCoexCallbackWithoutWifiP2pInRestrictionBits() throws Exception { 5560 assumeTrue(SdkLevel.isAtLeastS()); 5561 setupCoexMock(0); 5562 assertNotNull(mCoexListener); 5563 forceP2pEnabled(mClient1); 5564 mLooper.dispatchAll(); 5565 5566 mCoexListener.onCoexUnsafeChannelsChanged(); 5567 mLooper.dispatchAll(); 5568 5569 // On entering P2pEnabledState, these are called once first. 5570 verify(mWifiNative, times(2)).p2pSetListenChannel(eq(0)); 5571 ArgumentCaptor<List<CoexUnsafeChannel>> unsafeChannelsCaptor = 5572 ArgumentCaptor.forClass(List.class); 5573 verify(mWifiNative, times(2)).p2pSetOperatingChannel(eq(0), unsafeChannelsCaptor.capture()); 5574 List<List<CoexUnsafeChannel>> capturedUnsafeChannelsList = 5575 unsafeChannelsCaptor.getAllValues(); 5576 // The second one is what we sent. 5577 assertEquals(0, capturedUnsafeChannelsList.get(1).size()); 5578 } 5579 5580 /** 5581 * Verify the caller sends WifiP2pManager.SET_WFD_INFO with wfd enabled 5582 * and WFD R2 device info. 5583 */ 5584 @Test testSetWfdR2InfoSuccessWithWfdEnabled()5585 public void testSetWfdR2InfoSuccessWithWfdEnabled() throws Exception { 5586 assumeTrue(SdkLevel.isAtLeastS()); 5587 // Move to enabled state 5588 forceP2pEnabled(mClient1); 5589 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 5590 5591 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 5592 mTestThisDevice.wfdInfo.setEnabled(true); 5593 mTestThisDevice.wfdInfo.setR2DeviceType(WifiP2pWfdInfo.DEVICE_TYPE_WFD_SOURCE); 5594 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 5595 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 5596 .thenReturn(PackageManager.PERMISSION_GRANTED); 5597 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 5598 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(true); 5599 when(mWifiNative.setWfdR2DeviceInfo(anyString())).thenReturn(true); 5600 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 5601 5602 verify(mWifiInjector).getWifiPermissionsWrapper(); 5603 verify(mWifiPermissionsWrapper).getUidPermission( 5604 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 5605 verify(mWifiNative).setWfdEnable(eq(true)); 5606 verify(mWifiNative).setWfdDeviceInfo(eq(mTestThisDevice.wfdInfo.getDeviceInfoHex())); 5607 verify(mWifiNative).setWfdR2DeviceInfo(eq(mTestThisDevice.wfdInfo.getR2DeviceInfoHex())); 5608 checkSendThisDeviceChangedBroadcast(); 5609 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5610 Message message = mMessageCaptor.getValue(); 5611 assertEquals(WifiP2pManager.SET_WFD_INFO_SUCCEEDED, message.what); 5612 } 5613 5614 /** 5615 * Verify WifiP2pManager.SET_WFD_INFO_FAILED is returned when wfd is enabled, 5616 * WFD R2 device, and native call "setWfdR2DeviceInfo" failure. 5617 */ 5618 @Test testSetWfdR2InfoFailureWithWfdEnabledWhenNativeCallFailure2()5619 public void testSetWfdR2InfoFailureWithWfdEnabledWhenNativeCallFailure2() throws Exception { 5620 assumeTrue(SdkLevel.isAtLeastS()); 5621 // Move to enabled state 5622 forceP2pEnabled(mClient1); 5623 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 5624 5625 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 5626 mTestThisDevice.wfdInfo.setEnabled(true); 5627 mTestThisDevice.wfdInfo.setR2DeviceType(WifiP2pWfdInfo.DEVICE_TYPE_WFD_SOURCE); 5628 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 5629 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 5630 .thenReturn(PackageManager.PERMISSION_GRANTED); 5631 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 5632 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(true); 5633 when(mWifiNative.setWfdR2DeviceInfo(anyString())).thenReturn(false); 5634 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 5635 5636 verify(mWifiInjector).getWifiPermissionsWrapper(); 5637 verify(mWifiPermissionsWrapper).getUidPermission( 5638 eq(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY), anyInt()); 5639 verify(mWifiNative).setWfdEnable(eq(true)); 5640 verify(mWifiNative).setWfdDeviceInfo(eq(mTestThisDevice.wfdInfo.getDeviceInfoHex())); 5641 verify(mWifiNative).setWfdR2DeviceInfo(eq(mTestThisDevice.wfdInfo.getR2DeviceInfoHex())); 5642 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5643 Message message = mMessageCaptor.getValue(); 5644 assertEquals(WifiP2pManager.SET_WFD_INFO_FAILED, message.what); 5645 assertEquals(WifiP2pManager.ERROR, message.arg1); 5646 } 5647 5648 /** 5649 * Verify that P2P group is removed during group creating failure. 5650 */ 5651 @Test testGroupCreatingFailureDueToTethering()5652 public void testGroupCreatingFailureDueToTethering() throws Exception { 5653 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 5654 when(mWifiNative.p2pGroupRemove(eq(IFACE_NAME_P2P))).thenReturn(true); 5655 when(mWifiPermissionsUtil.checkCanAccessWifiDirect(eq("testPkg1"), eq("testFeature"), 5656 anyInt(), anyBoolean())).thenReturn(true); 5657 5658 WifiP2pGroup group = new WifiP2pGroup(); 5659 group.setNetworkId(WifiP2pGroup.NETWORK_ID_PERSISTENT); 5660 group.setNetworkName("DIRECT-xy-NEW"); 5661 group.setOwner(new WifiP2pDevice("thisDeviceMac")); 5662 group.setIsGroupOwner(true); 5663 group.setInterface(IFACE_NAME_P2P); 5664 5665 forceP2pEnabled(mClient1); 5666 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5667 mLooper.dispatchAll(); 5668 sendCreateGroupMsg(mClientMessenger, WifiP2pGroup.NETWORK_ID_TEMPORARY, null); 5669 mLooper.dispatchAll(); 5670 5671 sendGroupStartedMsg(group); 5672 mLooper.dispatchAll(); 5673 5674 mLooper.moveTimeForward(120 * 1000 * 2); 5675 mLooper.dispatchAll(); 5676 5677 verify(mWifiNative).p2pGroupRemove(group.getInterface()); 5678 } 5679 5680 /** 5681 * Verify the idle timer is cancelled after leaving inactive state. 5682 */ 5683 @Test testIdleTimeoutCancelledAfterLeavingInactiveState()5684 public void testIdleTimeoutCancelledAfterLeavingInactiveState() throws Exception { 5685 setTargetSdkGreaterThanT(); 5686 forceP2pEnabled(mClient1); 5687 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5688 5689 mockPeersList(); 5690 sendConnectMsg(mClientMessenger, mTestWifiP2pPeerConfig); 5691 if (SdkLevel.isAtLeastT()) { 5692 verify(mWifiPermissionsUtil, atLeastOnce()).checkNearbyDevicesPermission( 5693 any(), eq(true), any()); 5694 verify(mWifiPermissionsUtil, never()).checkCanAccessWifiDirect( 5695 any(), any(), anyInt(), anyBoolean()); 5696 } else { 5697 verify(mWifiPermissionsUtil).checkCanAccessWifiDirect(eq("testPkg1"), 5698 eq("testFeature"), anyInt(), eq(false)); 5699 } 5700 5701 ArgumentCaptor<WifiP2pConfig> configCaptor = 5702 ArgumentCaptor.forClass(WifiP2pConfig.class); 5703 verify(mWifiP2pMetrics).startConnectionEvent( 5704 eq(P2pConnectionEvent.CONNECTION_FRESH), 5705 configCaptor.capture(), 5706 eq(WifiMetricsProto.GroupEvent.GROUP_UNKNOWN)); 5707 assertEquals(mTestWifiP2pPeerConfig.toString(), configCaptor.getValue().toString()); 5708 // Verify timer is cannelled 5709 // Includes re-schedule 4 times: 5710 // 1. forceP2pEnabled(): enter InactiveState 5711 // 2. forceP2pEnabled: DISCOVER_PEERS 5712 // 3. CONNECT 5713 // 4. leave InactiveState 5714 verify(mAlarmManager, times(4)).setExact(anyInt(), anyLong(), 5715 eq(mWifiP2pServiceImpl.P2P_IDLE_SHUTDOWN_MESSAGE_TIMEOUT_TAG), any(), any()); 5716 verify(mAlarmManager, times(4)).cancel(eq(mWifiP2pServiceImpl.mP2pIdleShutdownMessage)); 5717 } 5718 5719 /** 5720 * Verify the interface down after idle timer is triggered. 5721 */ 5722 @Test testIdleTimeoutTriggered()5723 public void testIdleTimeoutTriggered() throws Exception { 5724 forceP2pEnabled(mClient1); 5725 mWifiP2pServiceImpl.mP2pIdleShutdownMessage.onAlarm(); 5726 mLooper.dispatchAll(); 5727 verify(mWifiNative).teardownInterface(); 5728 verify(mWifiMonitor).stopMonitoring(anyString()); 5729 } 5730 5731 /** 5732 * Verify the WFD info is set again on going back to P2pEnabledState 5733 * for the IdleShutdown case. 5734 */ 5735 @Test testWfdInfoIsSetAtP2pEnabledStateForIdleShutdown()5736 public void testWfdInfoIsSetAtP2pEnabledStateForIdleShutdown() throws Exception { 5737 // Move to enabled state 5738 forceP2pEnabled(mClient1); 5739 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 5740 5741 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 5742 mTestThisDevice.wfdInfo.setEnabled(true); 5743 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 5744 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 5745 .thenReturn(PackageManager.PERMISSION_GRANTED); 5746 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 5747 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(true); 5748 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 5749 5750 // P2P is off due to IDLE and data should be kept for the resume. 5751 mWifiP2pServiceImpl.mP2pIdleShutdownMessage.onAlarm(); 5752 mLooper.dispatchAll(); 5753 verify(mWifiNative).teardownInterface(); 5754 verify(mWifiMonitor).stopMonitoring(anyString()); 5755 sendSimpleMsg(null, WifiP2pMonitor.SUP_DISCONNECTION_EVENT); 5756 5757 reset(mWifiNative); 5758 when(mWifiNative.setupInterface(any(), any(), any())).thenReturn(IFACE_NAME_P2P); 5759 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 5760 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(true); 5761 5762 // send a command to resume P2P 5763 sendSimpleMsg(mClientMessenger, WifiP2pManager.DISCOVER_PEERS); 5764 5765 // Restore data for resuming from idle shutdown. 5766 verify(mWifiNative).setWfdEnable(eq(true)); 5767 verify(mWifiNative).setWfdDeviceInfo(eq(mTestThisDevice.wfdInfo.getDeviceInfoHex())); 5768 } 5769 5770 /** 5771 * Verify the WFD info is set again on going back to P2pEnabledState 5772 * for the normal shutdown case. 5773 */ 5774 @Test testWfdInfoIsSetAtP2pEnabledStateForNormalShutdown()5775 public void testWfdInfoIsSetAtP2pEnabledStateForNormalShutdown() throws Exception { 5776 // Move to enabled state 5777 forceP2pEnabled(mClient1); 5778 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 5779 5780 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 5781 mTestThisDevice.wfdInfo.setEnabled(true); 5782 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 5783 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 5784 .thenReturn(PackageManager.PERMISSION_GRANTED); 5785 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 5786 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(true); 5787 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 5788 5789 // P2P is really disabled when wifi is off. 5790 simulateWifiStateChange(false); 5791 mLooper.dispatchAll(); 5792 verify(mWifiNative).teardownInterface(); 5793 verify(mWifiMonitor).stopMonitoring(anyString()); 5794 5795 reset(mWifiNative); 5796 when(mWifiNative.setupInterface(any(), any(), any())).thenReturn(IFACE_NAME_P2P); 5797 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 5798 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(true); 5799 5800 // send a command to resume P2P 5801 sendSimpleMsg(mClientMessenger, WifiP2pManager.DISCOVER_PEERS); 5802 mLooper.dispatchAll(); 5803 5804 // In normal case, wfd info is cleared. 5805 verify(mWifiNative, never()).setWfdEnable(anyBoolean()); 5806 verify(mWifiNative, never()).setWfdDeviceInfo(anyString()); 5807 } 5808 5809 /** 5810 * Verify the WFD info is set if WFD info is set at P2pDisabledState. 5811 */ 5812 @Test testWfdInfoIsSetAtP2pEnabledWithPreSetWfdInfo()5813 public void testWfdInfoIsSetAtP2pEnabledWithPreSetWfdInfo() throws Exception { 5814 mTestThisDevice.wfdInfo = new WifiP2pWfdInfo(); 5815 mTestThisDevice.wfdInfo.setEnabled(true); 5816 when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper); 5817 when(mWifiPermissionsWrapper.getUidPermission(anyString(), anyInt())) 5818 .thenReturn(PackageManager.PERMISSION_GRANTED); 5819 when(mWifiNative.setWfdEnable(anyBoolean())).thenReturn(true); 5820 when(mWifiNative.setWfdDeviceInfo(anyString())).thenReturn(true); 5821 sendSetWfdInfoMsg(mClientMessenger, mTestThisDevice.wfdInfo); 5822 5823 // At disabled state, WFD info is stored in the service, but not set actually. 5824 verify(mWifiNative, never()).setWfdEnable(anyBoolean()); 5825 verify(mWifiNative, never()).setWfdDeviceInfo(any()); 5826 5827 // Move to enabled state 5828 forceP2pEnabled(mClient1); 5829 mTestThisDevice.status = mTestThisDevice.AVAILABLE; 5830 5831 // Restore data for resuming from idle shutdown. 5832 verify(mWifiNative).setWfdEnable(eq(true)); 5833 verify(mWifiNative).setWfdDeviceInfo(eq(mTestThisDevice.wfdInfo.getDeviceInfoHex())); 5834 } 5835 5836 /** 5837 * Verify the frequency changed event handling. 5838 */ 5839 @Test testP2pFrequencyChangedEventHandling()5840 public void testP2pFrequencyChangedEventHandling() throws Exception { 5841 // Move to group created state 5842 forceP2pEnabled(mClient1); 5843 WifiP2pGroup group = new WifiP2pGroup(); 5844 group.setNetworkId(WifiP2pGroup.NETWORK_ID_PERSISTENT); 5845 group.setNetworkName("DIRECT-xy-NEW"); 5846 group.setOwner(new WifiP2pDevice("thisDeviceMac")); 5847 group.setIsGroupOwner(true); 5848 group.setInterface(IFACE_NAME_P2P); 5849 sendGroupStartedMsg(group); 5850 simulateTetherReady(); 5851 5852 // Send Frequency changed event. 5853 sendSimpleMsg(null, 5854 WifiP2pMonitor.P2P_FREQUENCY_CHANGED_EVENT, 5855 TEST_GROUP_FREQUENCY); 5856 5857 // send WifiP2pManager.REQUEST_GROUP_INFO and check the updated frequency. 5858 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 5859 sendRequestGroupInfoMsg(mClientMessenger); 5860 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5861 assertEquals(WifiP2pManager.RESPONSE_GROUP_INFO, mMessageCaptor.getValue().what); 5862 WifiP2pGroup wifiP2pGroup = (WifiP2pGroup) mMessageCaptor.getValue().obj; 5863 assertEquals(TEST_GROUP_FREQUENCY, wifiP2pGroup.getFrequency()); 5864 } 5865 5866 /* 5867 * Verify the caller sends WifiP2pManager.REMOVE_CLIENT. 5868 */ 5869 @Test testRemoveClientSuccess()5870 public void testRemoveClientSuccess() throws Exception { 5871 when(mWifiNative.getSupportedFeatures()).thenReturn( 5872 WifiP2pManager.FEATURE_GROUP_CLIENT_REMOVAL); 5873 mockEnterGroupCreatedState(); 5874 5875 when(mWifiNative.removeClient(anyString())).thenReturn(true); 5876 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_CLIENT, mTestWifiP2pPeerAddress); 5877 verify(mWifiNative).removeClient(anyString()); 5878 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5879 Message message = mMessageCaptor.getValue(); 5880 assertEquals(WifiP2pManager.REMOVE_CLIENT_SUCCEEDED, message.what); 5881 } 5882 5883 /** 5884 * Verify WifiP2pManager.REMOVE_CLIENT_FAILED is returned when native call failure. 5885 */ 5886 @Test testRemoveClientFailureWhenNativeCallFailure()5887 public void testRemoveClientFailureWhenNativeCallFailure() throws Exception { 5888 when(mWifiNative.getSupportedFeatures()).thenReturn( 5889 WifiP2pManager.FEATURE_GROUP_CLIENT_REMOVAL); 5890 mockEnterGroupCreatedState(); 5891 5892 when(mWifiNative.removeClient(anyString())).thenReturn(false); 5893 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_CLIENT, mTestWifiP2pPeerAddress); 5894 verify(mWifiNative).removeClient(anyString()); 5895 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5896 Message message = mMessageCaptor.getValue(); 5897 assertEquals(WifiP2pManager.REMOVE_CLIENT_FAILED, message.what); 5898 assertEquals(WifiP2pManager.ERROR, message.arg1); 5899 } 5900 5901 /** 5902 * Verify WifiP2pManager.REMOVE_CLIENT_SUCCEEDED is returned when p2p is creating group. 5903 */ 5904 @Test testRemoveClientSuccessWhenP2pCreatingGroup()5905 public void testRemoveClientSuccessWhenP2pCreatingGroup() throws Exception { 5906 when(mWifiNative.getSupportedFeatures()).thenReturn( 5907 WifiP2pManager.FEATURE_GROUP_CLIENT_REMOVAL); 5908 // Move to group creating state 5909 testConnectWithConfigValidAsGroupSuccess(); 5910 5911 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_CLIENT, mTestWifiP2pPeerAddress); 5912 verify(mClientHandler, atLeastOnce()).sendMessage(mMessageCaptor.capture()); 5913 Message message = mMessageCaptor.getValue(); 5914 assertEquals(WifiP2pManager.REMOVE_CLIENT_SUCCEEDED, message.what); 5915 } 5916 5917 /** 5918 * Verify WifiP2pManager.REMOVE_CLIENT_SUCCEEDED is returned when p2p is inactive. 5919 */ 5920 @Test testRemoveClientSuccessWhenP2pInactive()5921 public void testRemoveClientSuccessWhenP2pInactive() throws Exception { 5922 when(mWifiNative.getSupportedFeatures()).thenReturn( 5923 WifiP2pManager.FEATURE_GROUP_CLIENT_REMOVAL); 5924 // Move to inactive state 5925 forceP2pEnabled(mClient1); 5926 5927 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_CLIENT, mTestWifiP2pPeerAddress); 5928 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5929 Message message = mMessageCaptor.getValue(); 5930 assertEquals(WifiP2pManager.REMOVE_CLIENT_SUCCEEDED, message.what); 5931 } 5932 5933 /** 5934 * Verify WifiP2pManager.REMOVE_CLIENT_SUCCEEDED is returned when p2p is disabled. 5935 */ 5936 @Test testRemoveClientSuccessWhenP2pDisabled()5937 public void testRemoveClientSuccessWhenP2pDisabled() throws Exception { 5938 when(mWifiNative.getSupportedFeatures()).thenReturn( 5939 WifiP2pManager.FEATURE_GROUP_CLIENT_REMOVAL); 5940 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_CLIENT, mTestWifiP2pPeerAddress); 5941 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5942 Message message = mMessageCaptor.getValue(); 5943 assertEquals(WifiP2pManager.REMOVE_CLIENT_SUCCEEDED, message.what); 5944 } 5945 5946 /** 5947 * Verify WifiP2pManager.REMOVE_CLIENT_FAILED is returned when p2p is unsupported. 5948 */ 5949 @Test testRemoveClientFailureWhenP2pUnsupported()5950 public void testRemoveClientFailureWhenP2pUnsupported() throws Exception { 5951 setUpWifiP2pServiceImpl(false); 5952 when(mWifiNative.getSupportedFeatures()).thenReturn( 5953 WifiP2pManager.FEATURE_GROUP_CLIENT_REMOVAL); 5954 sendSimpleMsg(mClientMessenger, WifiP2pManager.REMOVE_CLIENT, mTestWifiP2pPeerAddress); 5955 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 5956 Message message = mMessageCaptor.getValue(); 5957 assertEquals(WifiP2pManager.REMOVE_CLIENT_FAILED, message.what); 5958 assertEquals(WifiP2pManager.P2P_UNSUPPORTED, message.arg1); 5959 } 5960 5961 /** 5962 * Verify attribution is passed in correctly by WifiP2pManager#getMessenger. 5963 */ 5964 @Test testGetMessenger_InvalidAttributions()5965 public void testGetMessenger_InvalidAttributions() { 5966 assumeTrue(SdkLevel.isAtLeastS()); 5967 AttributionSource attributionSource = mock(AttributionSource.class); 5968 when(attributionSource.checkCallingUid()).thenReturn(true); 5969 when(attributionSource.isTrusted(any(Context.class))).thenReturn(true); 5970 mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource); 5971 mWifiP2pServiceImpl = spy(mWifiP2pServiceImpl); 5972 lenient().when(mWifiP2pServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID); 5973 assertThrows(SecurityException.class, () -> { 5974 mWifiP2pServiceImpl.getMessenger(new Binder(), TEST_PACKAGE_NAME, null); 5975 }); 5976 5977 assertThrows(SecurityException.class, () -> { 5978 mWifiP2pServiceImpl.getMessenger(new Binder(), TEST_PACKAGE_NAME, new Bundle()); 5979 }); 5980 5981 assertThrows(SecurityException.class, () -> { 5982 Bundle nullEntry = new Bundle(); 5983 nullEntry.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, null); 5984 mWifiP2pServiceImpl.getMessenger(new Binder(), TEST_PACKAGE_NAME, nullEntry); 5985 }); 5986 5987 assertThrows(SecurityException.class, () -> { 5988 Bundle incorrectEntry = new Bundle(); 5989 incorrectEntry.putInt(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, 10); 5990 mWifiP2pServiceImpl.getMessenger(new Binder(), TEST_PACKAGE_NAME, incorrectEntry); 5991 }); 5992 5993 when(attributionSource.checkCallingUid()).thenReturn(false); 5994 assertThrows(SecurityException.class, () -> { 5995 mWifiP2pServiceImpl.getMessenger(new Binder(), TEST_PACKAGE_NAME, mAttribution); 5996 }); 5997 when(attributionSource.checkCallingUid()).thenReturn(true); // restore 5998 5999 // single first attributions should not fail - even if (theoretically, doesn't happen in 6000 // practice) are not trusted. I.e. this call checks that this method isn't called. 6001 AttributionSource freshAs = mock(AttributionSource.class); 6002 Bundle freshAttribution = new Bundle(); 6003 freshAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, freshAs); 6004 when(freshAs.checkCallingUid()).thenReturn(true); 6005 when(freshAs.isTrusted(any(Context.class))).thenReturn(false); 6006 mWifiP2pServiceImpl.getMessenger(new Binder(), TEST_PACKAGE_NAME, freshAttribution); 6007 verify(freshAs, never()).isTrusted(any()); 6008 6009 AttributionSource originalCaller = mock(AttributionSource.class); 6010 when(originalCaller.getUid()).thenReturn(12345); 6011 when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME + ".other"); 6012 when(originalCaller.isTrusted(any(Context.class))).thenReturn(false); 6013 when(attributionSource.getNext()).thenReturn(originalCaller); 6014 assertThrows(SecurityException.class, () -> { 6015 mWifiP2pServiceImpl.getMessenger(new Binder(), TEST_PACKAGE_NAME, mAttribution); 6016 }); 6017 } 6018 6019 /** 6020 * Verify p2p connection dialog triggering without any Display ID information 6021 */ 6022 @Test testInvitationReceivedDialogTrigger()6023 public void testInvitationReceivedDialogTrigger() throws Exception { 6024 forceP2pEnabled(mClient1); 6025 mockPeersList(); 6026 WifiP2pConfig config = new WifiP2pConfig(); 6027 config.deviceAddress = mTestWifiP2pDevice.deviceAddress; 6028 config.wps = new WpsInfo(); 6029 config.wps.setup = WpsInfo.PBC; 6030 6031 // "simple" client connect (no display ID) 6032 sendNegotiationRequestEvent(config); 6033 if (!SdkLevel.isAtLeastT()) { 6034 verify(mAlertDialog).show(); 6035 } else { 6036 verify(mWifiDialogManager).createP2pInvitationReceivedDialog(anyString(), anyBoolean(), 6037 any(), eq(Display.DEFAULT_DISPLAY), any(), any()); 6038 verify(mDialogHandle).launchDialog(P2P_INVITATION_RECEIVED_TIMEOUT_MS); 6039 } 6040 } 6041 6042 /** 6043 * Verify p2p connection dialog triggering with a privileged caller specifying a display ID. 6044 */ 6045 @Test testInvitationReceivedDialogTriggerWithDisplayId()6046 public void testInvitationReceivedDialogTriggerWithDisplayId() throws Exception { 6047 assumeTrue(SdkLevel.isAtLeastT()); 6048 final int someNonDefaultDisplayId = 123; 6049 6050 forceP2pEnabled(mClient1); 6051 mockPeersList(); 6052 WifiP2pConfig config = new WifiP2pConfig(); 6053 config.deviceAddress = mTestWifiP2pDevice.deviceAddress; 6054 config.wps = new WpsInfo(); 6055 config.wps.setup = WpsInfo.PBC; 6056 6057 // add a privileged client with a display ID 6058 Bundle bundle = new Bundle(); 6059 bundle.putInt(WifiP2pManager.EXTRA_PARAM_KEY_DISPLAY_ID, someNonDefaultDisplayId); 6060 when(mWifiPermissionsUtil.isSystem(eq(TEST_PACKAGE_NAME), anyInt())).thenReturn(true); 6061 mWifiP2pServiceImpl.getMessenger(mClient2, TEST_PACKAGE_NAME, bundle); 6062 6063 sendNegotiationRequestEvent(config); 6064 verify(mWifiDialogManager).createP2pInvitationReceivedDialog(anyString(), 6065 anyBoolean(), any(), eq(someNonDefaultDisplayId), any(), any()); 6066 verify(mDialogHandle).launchDialog(P2P_INVITATION_RECEIVED_TIMEOUT_MS); 6067 } 6068 6069 /** 6070 * Verify p2p connection dialog triggering with a privileged client adding a Display ID but then 6071 * closing (i.e. removing itself). 6072 */ 6073 @Test testInvitationReceivedDialogTriggerWithDisplayIdDeleted()6074 public void testInvitationReceivedDialogTriggerWithDisplayIdDeleted() throws Exception { 6075 assumeTrue(SdkLevel.isAtLeastT()); 6076 forceP2pEnabled(mClient1); 6077 mockPeersList(); 6078 WifiP2pConfig config = new WifiP2pConfig(); 6079 config.deviceAddress = mTestWifiP2pDevice.deviceAddress; 6080 config.wps = new WpsInfo(); 6081 config.wps.setup = WpsInfo.PBC; 6082 6083 // add a privileged client with a display ID 6084 Bundle bundle = new Bundle(); 6085 bundle.putInt(WifiP2pManager.EXTRA_PARAM_KEY_DISPLAY_ID, 123); 6086 when(mWifiPermissionsUtil.isSystem(eq(TEST_PACKAGE_NAME), anyInt())).thenReturn(true); 6087 mWifiP2pServiceImpl.getMessenger(mClient2, TEST_PACKAGE_NAME, bundle); 6088 mWifiP2pServiceImpl.close(mClient2); 6089 6090 // "simple" client connect (no display ID) 6091 sendNegotiationRequestEvent(config); 6092 verify(mWifiDialogManager).createP2pInvitationReceivedDialog(anyString(), anyBoolean(), 6093 any(), eq(Display.DEFAULT_DISPLAY), any(), any()); 6094 verify(mDialogHandle).launchDialog(P2P_INVITATION_RECEIVED_TIMEOUT_MS); 6095 } 6096 verifySetVendorElement(boolean isP2pActivated, boolean shouldSucceed, boolean hasPermission, boolean shouldSetToNative)6097 private void verifySetVendorElement(boolean isP2pActivated, boolean shouldSucceed, 6098 boolean hasPermission, boolean shouldSetToNative) throws Exception { 6099 6100 when(mWifiNative.getSupportedFeatures()).thenReturn( 6101 WifiP2pManager.FEATURE_SET_VENDOR_ELEMENTS); 6102 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 6103 .thenReturn(hasPermission); 6104 when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())) 6105 .thenReturn(hasPermission); 6106 6107 simulateWifiStateChange(true); 6108 simulateLocationModeChange(true); 6109 checkIsP2pInitWhenClientConnected(isP2pActivated, mClient1, 6110 new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME)); 6111 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 6112 6113 ArrayList<ScanResult.InformationElement> ies = new ArrayList<>(); 6114 ies.add(new ScanResult.InformationElement( 6115 ScanResult.InformationElement.EID_VSA, 0, 6116 new byte[]{(byte) 0xa, (byte) 0xb})); 6117 HashSet<ScanResult.InformationElement> expectedIes = new HashSet<>(); 6118 expectedIes.add(ies.get(0)); 6119 6120 sendSetVendorElementsMsg(mClientMessenger, ies); 6121 6122 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 6123 Message message = mMessageCaptor.getValue(); 6124 if (shouldSucceed) { 6125 assertEquals(WifiP2pManager.SET_VENDOR_ELEMENTS_SUCCEEDED, message.what); 6126 } else { 6127 assertEquals(WifiP2pManager.SET_VENDOR_ELEMENTS_FAILED, message.what); 6128 } 6129 6130 // Launch a peer discovery to set cached VSIEs to the native service. 6131 sendDiscoverPeersMsg(mClientMessenger); 6132 if (shouldSetToNative) { 6133 if (shouldSucceed) { 6134 verify(mWifiNative).setVendorElements(eq(expectedIes)); 6135 } else { 6136 // If failed to set vendor elements, there is no entry in the list. 6137 verify(mWifiNative).setVendorElements(eq( 6138 new HashSet<ScanResult.InformationElement>())); 6139 } 6140 } else { 6141 verify(mWifiNative, never()).setVendorElements(any()); 6142 } 6143 } 6144 /** 6145 * Verify sunny scenario for setVendorElements when P2P is not in EnabledState. 6146 */ 6147 @Test testSetVendorElementsSuccessForIdleShutdown()6148 public void testSetVendorElementsSuccessForIdleShutdown() throws Exception { 6149 assumeTrue(SdkLevel.isAtLeastT()); 6150 boolean isP2pActivated = false, shouldSucceed = true; 6151 boolean hasPermission = true, shouldSetToNative = true; 6152 verifySetVendorElement(isP2pActivated, shouldSucceed, 6153 hasPermission, shouldSetToNative); 6154 } 6155 6156 /** 6157 * Verify sunny scenario for setVendorElements when P2P is in EnabledState. 6158 */ 6159 @Test testSetVendorElementsSuccessForActiveP2p()6160 public void testSetVendorElementsSuccessForActiveP2p() throws Exception { 6161 assumeTrue(SdkLevel.isAtLeastT()); 6162 boolean isP2pActivated = true, shouldSucceed = true; 6163 boolean hasPermission = true, shouldSetToNative = true; 6164 verifySetVendorElement(isP2pActivated, shouldSucceed, 6165 hasPermission, shouldSetToNative); 6166 } 6167 6168 /** 6169 * Verify failure scenario for setVendorElements when no NEARBY permission. 6170 */ 6171 @Test testSetVendorElementsFailureWithoutNearbyPermission()6172 public void testSetVendorElementsFailureWithoutNearbyPermission() throws Exception { 6173 assumeTrue(SdkLevel.isAtLeastT()); 6174 boolean isP2pActivated = false, shouldSucceed = false; 6175 boolean hasPermission = false, shouldSetToNative = true; 6176 verifySetVendorElement(isP2pActivated, shouldSucceed, 6177 hasPermission, shouldSetToNative); 6178 } 6179 verifyAddExternalApprover(boolean hasPermission, boolean shouldSucceed)6180 private void verifyAddExternalApprover(boolean hasPermission, 6181 boolean shouldSucceed) throws Exception { 6182 verifyAddExternalApprover(new Binder(), hasPermission, shouldSucceed); 6183 } 6184 verifyAddExternalApprover(Binder binder, boolean hasPermission, boolean shouldSucceed)6185 private void verifyAddExternalApprover(Binder binder, boolean hasPermission, 6186 boolean shouldSucceed) throws Exception { 6187 verifyAddExternalApprover(binder, hasPermission, 6188 shouldSucceed, 6189 MacAddress.fromString(mTestWifiP2pDevice.deviceAddress)); 6190 } 6191 verifyAddExternalApprover(Binder binder, boolean hasPermission, boolean shouldSucceed, MacAddress devAddr)6192 private void verifyAddExternalApprover(Binder binder, boolean hasPermission, 6193 boolean shouldSucceed, MacAddress devAddr) throws Exception { 6194 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 6195 .thenReturn(hasPermission); 6196 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 6197 .thenReturn(hasPermission); 6198 6199 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 6200 sendAddExternalApproverMsg(mClientMessenger, devAddr, binder); 6201 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 6202 Message message = mMessageCaptor.getValue(); 6203 if (shouldSucceed) { 6204 assertEquals(WifiP2pManager.EXTERNAL_APPROVER_ATTACH, message.what); 6205 } else { 6206 assertEquals(WifiP2pManager.EXTERNAL_APPROVER_DETACH, message.what); 6207 } 6208 } 6209 6210 /** 6211 * Verify sunny scenario for addExternalApprover. 6212 */ 6213 @Test testAddExternalApproverSuccess()6214 public void testAddExternalApproverSuccess() throws Exception { 6215 assumeTrue(SdkLevel.isAtLeastS()); 6216 boolean hasPermission = true, shouldSucceed = true; 6217 verifyAddExternalApprover(hasPermission, shouldSucceed); 6218 } 6219 6220 /** 6221 * Verify failure scenario for addExternalApprover when 6222 * the caller has no proper permission. 6223 */ 6224 @Test testAddExternalApproverFailureWithoutPermission()6225 public void testAddExternalApproverFailureWithoutPermission() throws Exception { 6226 assumeTrue(SdkLevel.isAtLeastS()); 6227 boolean hasPermission = false, shouldSucceed = false; 6228 verifyAddExternalApprover(hasPermission, shouldSucceed); 6229 } 6230 verifyRemoveExternalApprover(boolean hasPermission, boolean shouldSucceed)6231 private void verifyRemoveExternalApprover(boolean hasPermission, 6232 boolean shouldSucceed) throws Exception { 6233 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 6234 .thenReturn(hasPermission); 6235 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 6236 .thenReturn(hasPermission); 6237 MacAddress devAddr = MacAddress.fromString( 6238 mTestWifiP2pDevice.deviceAddress); 6239 Binder binder = new Binder(); 6240 6241 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 6242 sendRemoveExternalApproverMsg(mClientMessenger, devAddr, binder); 6243 verify(mClientHandler).sendMessage(mMessageCaptor.capture()); 6244 Message message = mMessageCaptor.getValue(); 6245 if (shouldSucceed) { 6246 assertEquals(WifiP2pManager.REMOVE_EXTERNAL_APPROVER_SUCCEEDED, message.what); 6247 } else { 6248 assertEquals(WifiP2pManager.REMOVE_EXTERNAL_APPROVER_FAILED, message.what); 6249 } 6250 } 6251 6252 6253 /** 6254 * Verify sunny scenario for removeExternalApprover. 6255 */ 6256 @Test testRemoveExternalApproverSuccess()6257 public void testRemoveExternalApproverSuccess() throws Exception { 6258 assumeTrue(SdkLevel.isAtLeastS()); 6259 boolean hasPermission = true, shouldSucceed = true; 6260 verifyRemoveExternalApprover(hasPermission, shouldSucceed); 6261 } 6262 6263 /** 6264 * Verify failure scenario for removeExternalApprover when 6265 * the caller has no proper permission. 6266 */ 6267 @Test testRemoveExternalApproverFailureWithoutPermission()6268 public void testRemoveExternalApproverFailureWithoutPermission() throws Exception { 6269 assumeTrue(SdkLevel.isAtLeastS()); 6270 boolean hasPermission = false, shouldSucceed = false; 6271 verifyRemoveExternalApprover(hasPermission, shouldSucceed); 6272 } 6273 verifySetConnectionRequestResult(MacAddress addr, boolean hasApprover, boolean hasPermission, boolean shouldSucceed, int wpsType, int result)6274 private void verifySetConnectionRequestResult(MacAddress addr, 6275 boolean hasApprover, 6276 boolean hasPermission, boolean shouldSucceed, 6277 int wpsType, int result) throws Exception { 6278 Binder binder = new Binder(); 6279 6280 forceP2pEnabled(mClient1); 6281 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 6282 mockPeersList(); 6283 6284 if (hasApprover) { 6285 verifyAddExternalApprover(binder, true, true, addr); 6286 } 6287 6288 mockEnterUserAuthorizingNegotiationRequestState(wpsType); 6289 6290 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 6291 .thenReturn(hasPermission); 6292 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 6293 .thenReturn(hasPermission); 6294 sendSetConnectionRequestResultMsg(mClientMessenger, 6295 MacAddress.fromString(mTestWifiP2pDevice.deviceAddress), 6296 result, binder); 6297 if (shouldSucceed) { 6298 // There are 4 replies: 6299 // * EXTERNAL_APPROVER_ATTACH 6300 // * EXTERNAL_APPROVER_CONNECTION_REQUESTED 6301 // * EXTERNAL_APPROVER_DETACH 6302 // * SET_CONNECTION_REQUEST_RESULT_SUCCEEDED 6303 ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); 6304 verify(mClientHandler, times(4)).sendMessage(messageCaptor.capture()); 6305 List<Message> messages = messageCaptor.getAllValues(); 6306 assertEquals(WifiP2pManager.SET_CONNECTION_REQUEST_RESULT_SUCCEEDED, 6307 messages.get(3).what); 6308 } else { 6309 int expectedMessageCount = hasApprover ? 3 : 1; 6310 // There are 2 additional replies if having a approver. 6311 // * (With an approver) EXTERNAL_APPROVER_ATTACH 6312 // * (With an approver) EXTERNAL_APPROVER_CONNECTION_REQUESTED 6313 // * SET_CONNECTION_REQUEST_RESULT_FAILED 6314 ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); 6315 verify(mClientHandler, times(expectedMessageCount)).sendMessage( 6316 messageCaptor.capture()); 6317 List<Message> messages = messageCaptor.getAllValues(); 6318 assertEquals(WifiP2pManager.SET_CONNECTION_REQUEST_RESULT_FAILED, 6319 messages.get(expectedMessageCount - 1).what); 6320 } 6321 } 6322 6323 /** 6324 * Verify sunny scenario for setConnectionRequestResult. 6325 */ 6326 @Test testSetConnectionRequestResultSuccess()6327 public void testSetConnectionRequestResultSuccess() throws Exception { 6328 assumeTrue(SdkLevel.isAtLeastS()); 6329 boolean hasApprover = true, hasPermission = true, shouldSucceed = true; 6330 verifySetConnectionRequestResult(MacAddress.fromString(mTestWifiP2pDevice.deviceAddress), 6331 hasApprover, hasPermission, shouldSucceed, 6332 WpsInfo.PBC, WifiP2pManager.CONNECTION_REQUEST_ACCEPT); 6333 } 6334 6335 /** 6336 * Verify sunny scenario for setConnectionRequestResult with the wildcard address. 6337 */ 6338 @Test testSetConnectionRequestResultWithWildcardAddressSuccess()6339 public void testSetConnectionRequestResultWithWildcardAddressSuccess() throws Exception { 6340 assumeTrue(SdkLevel.isAtLeastS()); 6341 boolean hasApprover = true, hasPermission = true, shouldSucceed = true; 6342 verifySetConnectionRequestResult(MacAddress.BROADCAST_ADDRESS, 6343 hasApprover, hasPermission, shouldSucceed, 6344 WpsInfo.PBC, WifiP2pManager.CONNECTION_REQUEST_ACCEPT); 6345 } 6346 verifyMultiApproverMatch(List<MacAddress> addresses, MacAddress expectedMatch)6347 private void verifyMultiApproverMatch(List<MacAddress> addresses, MacAddress expectedMatch) 6348 throws Exception { 6349 when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())) 6350 .thenReturn(true); 6351 when(mWifiPermissionsUtil.checkNearbyDevicesPermission(any(), anyBoolean(), any())) 6352 .thenReturn(true); 6353 Binder binder = new Binder(); 6354 6355 forceP2pEnabled(mClient1); 6356 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 6357 mockPeersList(); 6358 6359 for (MacAddress addr: addresses) { 6360 verifyAddExternalApprover(binder, true /* hasPermission */, 6361 true /* shouldSucceed */, addr); 6362 reset(mClientHandler); 6363 } 6364 6365 // Received a request from mTestWifiP2pDevice 6366 mockEnterUserAuthorizingNegotiationRequestState(WpsInfo.PBC); 6367 6368 sendSetConnectionRequestResultMsg(mClientMessenger, 6369 MacAddress.fromString(mTestWifiP2pDevice.deviceAddress), 6370 WifiP2pManager.CONNECTION_REQUEST_ACCEPT, binder); 6371 // There are 3 replies: 6372 // * EXTERNAL_APPROVER_CONNECTION_REQUESTED 6373 // * EXTERNAL_APPROVER_DETACH 6374 // * SET_CONNECTION_REQUEST_RESULT_SUCCEEDED 6375 ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); 6376 verify(mClientHandler, times(3)).sendMessage(messageCaptor.capture()); 6377 List<Message> messages = messageCaptor.getAllValues(); 6378 6379 assertEquals(WifiP2pManager.EXTERNAL_APPROVER_CONNECTION_REQUESTED, 6380 messages.get(0).what); 6381 Bundle requestBundle = (Bundle) messages.get(0).obj; 6382 WifiP2pDevice requestDevice = requestBundle.getParcelable( 6383 WifiP2pManager.EXTRA_PARAM_KEY_DEVICE); 6384 assertEquals(mTestWifiP2pDevice.deviceAddress, requestDevice.deviceAddress); 6385 6386 assertEquals(WifiP2pManager.EXTERNAL_APPROVER_DETACH, 6387 messages.get(1).what); 6388 assertEquals(expectedMatch, (MacAddress) messages.get(1).obj); 6389 6390 assertEquals(WifiP2pManager.SET_CONNECTION_REQUEST_RESULT_SUCCEEDED, 6391 messages.get(2).what); 6392 } 6393 6394 /** 6395 * Verify that a registered address could be matched correctly 6396 * with additional wildcard address. 6397 */ 6398 @Test testDirectMatchWithWildcardAddress()6399 public void testDirectMatchWithWildcardAddress() throws Exception { 6400 assumeTrue(SdkLevel.isAtLeastS()); 6401 List<MacAddress> addresses = new ArrayList<>(); 6402 addresses.add(MacAddress.fromString(mTestWifiP2pDevice.deviceAddress)); 6403 addresses.add(MacAddress.BROADCAST_ADDRESS); 6404 verifyMultiApproverMatch(addresses, 6405 MacAddress.fromString(mTestWifiP2pDevice.deviceAddress)); 6406 } 6407 6408 /** 6409 * Verify that a unkonwn address could be matched against the wildcard address correctly 6410 * with an address and the wildcard address. 6411 */ 6412 @Test testWildcardAddressMatch()6413 public void testWildcardAddressMatch() throws Exception { 6414 assumeTrue(SdkLevel.isAtLeastS()); 6415 List<MacAddress> addresses = new ArrayList<>(); 6416 addresses.add(MacAddress.fromString("00:02:00:00:00:00")); 6417 addresses.add(MacAddress.BROADCAST_ADDRESS); 6418 verifyMultiApproverMatch(addresses, MacAddress.BROADCAST_ADDRESS); 6419 } 6420 6421 /** 6422 * Verify the failure scenario for setConnectionRequestResult without permissions. 6423 */ 6424 @Test testSetConnectionRequestResultFailureWithoutPermission()6425 public void testSetConnectionRequestResultFailureWithoutPermission() throws Exception { 6426 assumeTrue(SdkLevel.isAtLeastS()); 6427 boolean hasApprover = true, hasPermission = false, shouldSucceed = false; 6428 verifySetConnectionRequestResult(MacAddress.fromString(mTestWifiP2pDevice.deviceAddress), 6429 hasApprover, hasPermission, shouldSucceed, 6430 WpsInfo.PBC, WifiP2pManager.CONNECTION_REQUEST_ACCEPT); 6431 } 6432 6433 /** 6434 * Verify the failure scenario for setConnectionRequestResult without a registered approver. 6435 */ 6436 @Test testSetConnectionRequestResultFailureWithoutApprover()6437 public void testSetConnectionRequestResultFailureWithoutApprover() throws Exception { 6438 assumeTrue(SdkLevel.isAtLeastS()); 6439 boolean hasApprover = false, hasPermission = true, shouldSucceed = false; 6440 verifySetConnectionRequestResult(MacAddress.fromString(mTestWifiP2pDevice.deviceAddress), 6441 hasApprover, hasPermission, shouldSucceed, 6442 WpsInfo.PBC, WifiP2pManager.CONNECTION_REQUEST_ACCEPT); 6443 } 6444 6445 /** 6446 * Verify that deferring pin to the framework works normally. 6447 */ 6448 @Test testSetConnectionRequestResultDeferPinToFramework()6449 public void testSetConnectionRequestResultDeferPinToFramework() throws Exception { 6450 assumeTrue(SdkLevel.isAtLeastS()); 6451 boolean hasApprover = true, hasPermission = true, shouldSucceed = true; 6452 verifySetConnectionRequestResult(MacAddress.fromString(mTestWifiP2pDevice.deviceAddress), 6453 hasApprover, hasPermission, shouldSucceed, 6454 WpsInfo.KEYPAD, WifiP2pManager.CONNECTION_REQUEST_DEFER_SHOW_PIN_TO_SERVICE); 6455 } 6456 6457 /** 6458 * Validate p2p initialization when user approval is required. 6459 */ runTestP2pWithUserApproval(boolean userAcceptsRequest)6460 public void runTestP2pWithUserApproval(boolean userAcceptsRequest) throws Exception { 6461 ArgumentCaptor<State> mTargetStateCaptor = ArgumentCaptor.forClass(State.class); 6462 ArgumentCaptor<WaitingState> mWaitingStateCaptor = ArgumentCaptor.forClass( 6463 WaitingState.class); 6464 InOrder inOrder = inOrder(mInterfaceConflictManager); 6465 6466 simulateWifiStateChange(true); 6467 mWifiP2pServiceImpl.getMessenger(mClient1, TEST_PACKAGE_NAME, null); 6468 6469 // simulate user approval needed 6470 when(mInterfaceConflictManager.manageInterfaceConflictForStateMachine(any(), any(), any(), 6471 any(), any(), eq(HalDeviceManager.HDM_CREATE_IFACE_P2P), any())).thenAnswer( 6472 new MockAnswerUtil.AnswerWithArguments() { 6473 public int answer(String tag, Message msg, StateMachine stateMachine, 6474 WaitingState waitingState, State targetState, int createIfaceType, 6475 WorkSource requestorWs) { 6476 stateMachine.deferMessage(msg); 6477 stateMachine.transitionTo(waitingState); 6478 return InterfaceConflictManager.ICM_SKIP_COMMAND_WAIT_FOR_USER; 6479 } 6480 }); 6481 6482 sendSimpleMsg(mClientMessenger, WifiP2pManager.DISCOVER_PEERS); 6483 mLooper.dispatchAll(); 6484 inOrder.verify(mInterfaceConflictManager).manageInterfaceConflictForStateMachine(any(), 6485 any(), any(), mWaitingStateCaptor.capture(), mTargetStateCaptor.capture(), 6486 eq(HalDeviceManager.HDM_CREATE_IFACE_P2P), any()); 6487 6488 // simulate user approval triggered and granted 6489 when(mInterfaceConflictManager.manageInterfaceConflictForStateMachine(any(), any(), any(), 6490 any(), any(), eq(HalDeviceManager.HDM_CREATE_IFACE_P2P), any())).thenReturn( 6491 userAcceptsRequest ? InterfaceConflictManager.ICM_EXECUTE_COMMAND 6492 : InterfaceConflictManager.ICM_ABORT_COMMAND); 6493 mWaitingStateCaptor.getValue().sendTransitionStateCommand(mTargetStateCaptor.getValue()); 6494 mLooper.dispatchAll(); 6495 6496 verify(mWifiNative, userAcceptsRequest ? times(1) : never()).setupInterface(any(), any(), 6497 eq(new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME))); 6498 } 6499 6500 /** 6501 * Validate p2p initialization when user approval is required and granted. 6502 */ 6503 @Test testP2pWithUserApprovalAccept()6504 public void testP2pWithUserApprovalAccept() throws Exception { 6505 runTestP2pWithUserApproval(true); 6506 } 6507 6508 /** 6509 * Validate p2p initialization when user approval is required and granted. 6510 */ 6511 @Test testP2pWithUserApprovalReject()6512 public void testP2pWithUserApprovalReject() throws Exception { 6513 runTestP2pWithUserApproval(false); 6514 } 6515 6516 /* 6517 * Verify the connection event ends due to the provision discovery failure. 6518 */ 6519 @Test testProvDiscRejectEventForProvDisc()6520 public void testProvDiscRejectEventForProvDisc() throws Exception { 6521 forceP2pEnabled(mClient1); 6522 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 6523 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 6524 6525 mockEnterProvisionDiscoveryState(); 6526 6527 WifiP2pProvDiscEvent pdEvent = new WifiP2pProvDiscEvent(); 6528 pdEvent.device = mTestWifiP2pDevice; 6529 sendSimpleMsg(null, 6530 WifiP2pMonitor.P2P_PROV_DISC_FAILURE_EVENT, 6531 WifiP2pMonitor.PROV_DISC_STATUS_REJECTED, 6532 pdEvent); 6533 verify(mWifiNative).p2pCancelConnect(); 6534 6535 } 6536 6537 /** 6538 * Verify the p2p reject is sent on canceling a request. 6539 */ 6540 @Test testSendP2pRejectWhenCancelRequest()6541 public void testSendP2pRejectWhenCancelRequest() throws Exception { 6542 forceP2pEnabled(mClient1); 6543 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 6544 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 6545 6546 mockEnterProvisionDiscoveryState(); 6547 6548 WifiP2pProvDiscEvent pdEvent = new WifiP2pProvDiscEvent(); 6549 pdEvent.device = mTestWifiP2pDevice; 6550 sendSimpleMsg(null, WifiP2pManager.CANCEL_CONNECT); 6551 verify(mWifiNative).p2pReject(eq(mTestWifiP2pDevice.deviceAddress)); 6552 } 6553 6554 /** 6555 * 6556 */ 6557 @Test testSendP2pRejectOnRejectRequest()6558 public void testSendP2pRejectOnRejectRequest() throws Exception { 6559 when(mWifiNative.p2pGroupAdd(anyBoolean())).thenReturn(true); 6560 sendChannelInfoUpdateMsg("testPkg1", "testFeature", mClient1, mClientMessenger); 6561 forceP2pEnabled(mClient1); 6562 6563 mockEnterUserAuthorizingNegotiationRequestState(WpsInfo.PBC); 6564 6565 sendSimpleMsg(null, WifiP2pServiceImpl.PEER_CONNECTION_USER_REJECT); 6566 verify(mWifiNative).p2pReject(eq(mTestWifiP2pDevice.deviceAddress)); 6567 } 6568 6569 /** 6570 * Verify the tethering request is sent with TETHER_PRIVILEGED permission. 6571 */ 6572 @Test testTetheringRequestWithTetherPrivilegedPermission()6573 public void testTetheringRequestWithTetherPrivilegedPermission() throws Exception { 6574 mockEnterGroupCreatedState(); 6575 6576 String[] permission_gold = new String[] { 6577 android.Manifest.permission.TETHER_PRIVILEGED}; 6578 ArgumentCaptor<String []> permissionCaptor = ArgumentCaptor.forClass(String[].class); 6579 // 2 connection changed event: 6580 // * Enter Enabled state 6581 // * Tethering request. 6582 verify(mContext, times(2)).sendBroadcastWithMultiplePermissions( 6583 argThat(new WifiP2pServiceImplTest 6584 .P2pConnectionChangedIntentMatcherForNetworkState(IDLE)), 6585 permissionCaptor.capture()); 6586 String[] permission = permissionCaptor.getAllValues().get(1); 6587 Arrays.sort(permission); 6588 Arrays.sort(permission_gold); 6589 assertEquals(permission_gold, permission); 6590 } 6591 } 6592