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