WifiStateMachineTest.java revision 8812ab2ce5def57a6abe55719ee69892d27c70d7
1/* 2 * Copyright (C) 2015 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 17package com.android.server.wifi; 18 19import static org.junit.Assert.assertEquals; 20import static org.junit.Assert.assertFalse; 21import static org.junit.Assert.assertTrue; 22import static org.mockito.Mockito.*; 23 24import android.app.ActivityManager; 25import android.app.test.MockAnswerUtil.AnswerWithArguments; 26import android.app.test.TestAlarmManager; 27import android.content.ContentResolver; 28import android.content.Context; 29import android.content.pm.PackageManager; 30import android.content.pm.UserInfo; 31import android.content.res.Resources; 32import android.net.ConnectivityManager; 33import android.net.DhcpResults; 34import android.net.LinkProperties; 35import android.net.dhcp.DhcpClient; 36import android.net.ip.IpManager; 37import android.net.wifi.IClientInterface; 38import android.net.wifi.IWificond; 39import android.net.wifi.ScanResult; 40import android.net.wifi.SupplicantState; 41import android.net.wifi.WifiConfiguration; 42import android.net.wifi.WifiManager; 43import android.net.wifi.WifiScanner; 44import android.net.wifi.WifiSsid; 45import android.net.wifi.p2p.IWifiP2pManager; 46import android.os.BatteryStats; 47import android.os.Binder; 48import android.os.Handler; 49import android.os.HandlerThread; 50import android.os.IBinder; 51import android.os.IInterface; 52import android.os.INetworkManagementService; 53import android.os.IPowerManager; 54import android.os.Looper; 55import android.os.Message; 56import android.os.Messenger; 57import android.os.PowerManager; 58import android.os.RemoteException; 59import android.os.UserHandle; 60import android.os.UserManager; 61import android.os.test.TestLooper; 62import android.provider.Settings; 63import android.security.KeyStore; 64import android.telephony.TelephonyManager; 65import android.test.suitebuilder.annotation.SmallTest; 66import android.util.Log; 67 68import com.android.internal.R; 69import com.android.internal.app.IBatteryStats; 70import com.android.internal.util.AsyncChannel; 71import com.android.internal.util.IState; 72import com.android.internal.util.StateMachine; 73import com.android.server.wifi.hotspot2.NetworkDetail; 74import com.android.server.wifi.hotspot2.Utils; 75import com.android.server.wifi.p2p.WifiP2pServiceImpl; 76 77import org.junit.After; 78import org.junit.Before; 79import org.junit.Test; 80import org.mockito.ArgumentCaptor; 81import org.mockito.Mock; 82import org.mockito.MockitoAnnotations; 83 84import java.io.ByteArrayOutputStream; 85import java.io.PrintWriter; 86import java.lang.reflect.Field; 87import java.lang.reflect.InvocationTargetException; 88import java.lang.reflect.Method; 89import java.util.ArrayList; 90import java.util.Arrays; 91import java.util.concurrent.CountDownLatch; 92import java.util.HashMap; 93import java.util.HashSet; 94import java.util.List; 95import java.util.Map; 96import java.util.Set; 97 98/** 99 * Unit tests for {@link com.android.server.wifi.WifiStateMachine}. 100 */ 101@SmallTest 102public class WifiStateMachineTest { 103 public static final String TAG = "WifiStateMachineTest"; 104 105 private static final int MANAGED_PROFILE_UID = 1100000; 106 private static final int OTHER_USER_UID = 1200000; 107 private static final int LOG_REC_LIMIT_IN_VERBOSE_MODE = 108 (ActivityManager.isLowRamDeviceStatic() 109 ? WifiStateMachine.NUM_LOG_RECS_VERBOSE_LOW_MEMORY 110 : WifiStateMachine.NUM_LOG_RECS_VERBOSE); 111 private static final String DEFAULT_TEST_SSID = "\"GoogleGuest\""; 112 113 private long mBinderToken; 114 115 private static <T> T mockWithInterfaces(Class<T> class1, Class<?>... interfaces) { 116 return mock(class1, withSettings().extraInterfaces(interfaces)); 117 } 118 119 private static <T, I> IBinder mockService(Class<T> class1, Class<I> iface) { 120 T tImpl = mockWithInterfaces(class1, iface); 121 IBinder binder = mock(IBinder.class); 122 when(((IInterface) tImpl).asBinder()).thenReturn(binder); 123 when(binder.queryLocalInterface(iface.getCanonicalName())) 124 .thenReturn((IInterface) tImpl); 125 return binder; 126 } 127 128 private void enableDebugLogs() { 129 mWsm.enableVerboseLogging(1); 130 } 131 132 private class TestIpManager extends IpManager { 133 TestIpManager(Context context, String ifname, IpManager.Callback callback) { 134 // Call dependency-injection superclass constructor. 135 super(context, ifname, callback, mock(INetworkManagementService.class)); 136 } 137 138 @Override 139 public void startProvisioning(IpManager.ProvisioningConfiguration config) {} 140 141 @Override 142 public void stop() {} 143 144 @Override 145 public void confirmConfiguration() {} 146 147 void injectDhcpSuccess(DhcpResults dhcpResults) { 148 mCallback.onNewDhcpResults(dhcpResults); 149 mCallback.onProvisioningSuccess(new LinkProperties()); 150 } 151 152 void injectDhcpFailure() { 153 mCallback.onNewDhcpResults(null); 154 mCallback.onProvisioningFailure(new LinkProperties()); 155 } 156 } 157 158 private FrameworkFacade getFrameworkFacade() throws Exception { 159 FrameworkFacade facade = mock(FrameworkFacade.class); 160 161 when(facade.makeWifiScanner(any(Context.class), any(Looper.class))) 162 .thenReturn(mWifiScanner); 163 when(facade.getService(Context.NETWORKMANAGEMENT_SERVICE)).thenReturn( 164 mockWithInterfaces(IBinder.class, INetworkManagementService.class)); 165 166 IBinder p2pBinder = mockService(WifiP2pServiceImpl.class, IWifiP2pManager.class); 167 when(facade.getService(Context.WIFI_P2P_SERVICE)).thenReturn(p2pBinder); 168 169 WifiP2pServiceImpl p2pm = (WifiP2pServiceImpl) p2pBinder.queryLocalInterface( 170 IWifiP2pManager.class.getCanonicalName()); 171 172 final CountDownLatch untilDone = new CountDownLatch(1); 173 mP2pThread = new HandlerThread("WifiP2pMockThread") { 174 @Override 175 protected void onLooperPrepared() { 176 untilDone.countDown(); 177 } 178 }; 179 180 mP2pThread.start(); 181 untilDone.await(); 182 183 Handler handler = new Handler(mP2pThread.getLooper()); 184 when(p2pm.getP2pStateMachineMessenger()).thenReturn(new Messenger(handler)); 185 186 IBinder batteryStatsBinder = mockService(BatteryStats.class, IBatteryStats.class); 187 when(facade.getService(BatteryStats.SERVICE_NAME)).thenReturn(batteryStatsBinder); 188 189 when(facade.makeIpManager(any(Context.class), anyString(), any(IpManager.Callback.class))) 190 .then(new AnswerWithArguments() { 191 public IpManager answer( 192 Context context, String ifname, IpManager.Callback callback) { 193 mTestIpManager = new TestIpManager(context, ifname, callback); 194 return mTestIpManager; 195 } 196 }); 197 198 when(facade.checkUidPermission(eq(android.Manifest.permission.OVERRIDE_WIFI_CONFIG), 199 anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 200 201 when(facade.makeWifiConfigManager(any(Context.class), any(WifiNative.class), 202 any(FrameworkFacade.class), any(Clock.class), 203 any(UserManager.class), any(KeyStore.class))).then(new AnswerWithArguments() { 204 public WifiConfigManager answer(Context context, WifiNative wifiNative, 205 FrameworkFacade frameworkFacade, Clock clock, 206 UserManager userManager, KeyStore keyStore){ 207 mWifiConfigManager = new WifiConfigManager(context, wifiNative, frameworkFacade, 208 clock, userManager, keyStore); 209 return mWifiConfigManager; 210 } 211 }); 212 return facade; 213 } 214 215 private Context getContext() throws Exception { 216 PackageManager pkgMgr = mock(PackageManager.class); 217 when(pkgMgr.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)).thenReturn(true); 218 219 Context context = mock(Context.class); 220 when(context.getPackageManager()).thenReturn(pkgMgr); 221 when(context.getContentResolver()).thenReturn(mock(ContentResolver.class)); 222 223 MockResources resources = new com.android.server.wifi.MockResources(); 224 when(context.getResources()).thenReturn(resources); 225 226 ContentResolver cr = mock(ContentResolver.class); 227 when(context.getContentResolver()).thenReturn(cr); 228 229 when(context.getSystemService(Context.POWER_SERVICE)).thenReturn( 230 new PowerManager(context, mock(IPowerManager.class), new Handler())); 231 232 mAlarmManager = new TestAlarmManager(); 233 when(context.getSystemService(Context.ALARM_SERVICE)).thenReturn( 234 mAlarmManager.getAlarmManager()); 235 236 when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn( 237 mock(ConnectivityManager.class)); 238 239 return context; 240 } 241 242 private Resources getMockResources() { 243 MockResources resources = new MockResources(); 244 resources.setBoolean(R.bool.config_wifi_enable_wifi_firmware_debugging, false); 245 return resources; 246 } 247 248 private IState getCurrentState() throws 249 NoSuchMethodException, InvocationTargetException, IllegalAccessException { 250 Method method = StateMachine.class.getDeclaredMethod("getCurrentState"); 251 method.setAccessible(true); 252 return (IState) method.invoke(mWsm); 253 } 254 255 private static HandlerThread getWsmHandlerThread(WifiStateMachine wsm) throws 256 NoSuchFieldException, InvocationTargetException, IllegalAccessException { 257 Field field = StateMachine.class.getDeclaredField("mSmThread"); 258 field.setAccessible(true); 259 return (HandlerThread) field.get(wsm); 260 } 261 262 private static void stopLooper(final Looper looper) throws Exception { 263 new Handler(looper).post(new Runnable() { 264 @Override 265 public void run() { 266 looper.quitSafely(); 267 } 268 }); 269 } 270 271 private void dumpState() { 272 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 273 PrintWriter writer = new PrintWriter(stream); 274 mWsm.dump(null, writer, null); 275 writer.flush(); 276 Log.d(TAG, "WifiStateMachine state -" + stream.toString()); 277 } 278 279 private static ScanDetail getGoogleGuestScanDetail(int rssi) { 280 ScanResult.InformationElement ie[] = new ScanResult.InformationElement[1]; 281 ie[0] = ScanResults.generateSsidIe(sSSID); 282 NetworkDetail nd = new NetworkDetail(sBSSID, ie, new ArrayList<String>(), sFreq); 283 ScanDetail detail = new ScanDetail(nd, sWifiSsid, sBSSID, "", rssi, sFreq, 284 Long.MAX_VALUE, /* needed so that scan results aren't rejected because 285 there older than scan start */ 286 ie, new ArrayList<String>()); 287 return detail; 288 } 289 290 private ArrayList<ScanDetail> getMockScanResults() { 291 ScanResults sr = ScanResults.create(0, 2412, 2437, 2462, 5180, 5220, 5745, 5825); 292 ArrayList<ScanDetail> list = sr.getScanDetailArrayList(); 293 294 int rssi = -65; 295 list.add(getGoogleGuestScanDetail(rssi)); 296 return list; 297 } 298 299 static final String sSSID = "\"GoogleGuest\""; 300 static final WifiSsid sWifiSsid = WifiSsid.createFromAsciiEncoded(sSSID); 301 static final String sHexSSID = sWifiSsid.getHexString().replace("0x", "").replace("22", ""); 302 static final String sBSSID = "01:02:03:04:05:06"; 303 static final int sFreq = 2437; 304 305 WifiStateMachine mWsm; 306 HandlerThread mWsmThread; 307 HandlerThread mP2pThread; 308 HandlerThread mSyncThread; 309 AsyncChannel mWsmAsyncChannel; 310 TestAlarmManager mAlarmManager; 311 MockWifiMonitor mWifiMonitor; 312 TestIpManager mTestIpManager; 313 TestLooper mLooper; 314 WifiConfigManager mWifiConfigManager; 315 316 @Mock WifiNative mWifiNative; 317 @Mock WifiScanner mWifiScanner; 318 @Mock SupplicantStateTracker mSupplicantStateTracker; 319 @Mock WifiMetrics mWifiMetrics; 320 @Mock UserManager mUserManager; 321 @Mock WifiApConfigStore mApConfigStore; 322 @Mock BackupManagerProxy mBackupManagerProxy; 323 @Mock WifiCountryCode mCountryCode; 324 @Mock WifiInjector mWifiInjector; 325 @Mock WifiLastResortWatchdog mWifiLastResortWatchdog; 326 @Mock PropertyService mPropertyService; 327 @Mock BuildProperties mBuildProperties; 328 @Mock IWificond mWificond; 329 @Mock IClientInterface mClientInterface; 330 @Mock IBinder mClientInterfaceBinder; 331 332 public WifiStateMachineTest() throws Exception { 333 } 334 335 @Before 336 public void setUp() throws Exception { 337 Log.d(TAG, "Setting up ..."); 338 339 // Ensure looper exists 340 mLooper = new TestLooper(); 341 342 MockitoAnnotations.initMocks(this); 343 344 /** uncomment this to enable logs from WifiStateMachines */ 345 // enableDebugLogs(); 346 347 TestUtil.installWlanWifiNative(mWifiNative); 348 mWifiMonitor = new MockWifiMonitor(); 349 when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics); 350 when(mWifiInjector.getClock()).thenReturn(mock(Clock.class)); 351 when(mWifiInjector.getWifiLastResortWatchdog()).thenReturn(mWifiLastResortWatchdog); 352 when(mWifiInjector.getPropertyService()).thenReturn(mPropertyService); 353 when(mWifiInjector.getBuildProperties()).thenReturn(mBuildProperties); 354 when(mWifiInjector.getKeyStore()).thenReturn(mock(KeyStore.class)); 355 when(mWifiInjector.getWifiBackupRestore()).thenReturn(mock(WifiBackupRestore.class)); 356 when(mWifiInjector.makeWifiDiagnostics(anyObject())).thenReturn( 357 mock(BaseWifiDiagnostics.class)); 358 when(mWifiInjector.makeWificond()).thenReturn(mWificond); 359 360 FrameworkFacade factory = getFrameworkFacade(); 361 Context context = getContext(); 362 363 Resources resources = getMockResources(); 364 when(context.getResources()).thenReturn(resources); 365 366 when(factory.getIntegerSetting(context, 367 Settings.Global.WIFI_FREQUENCY_BAND, 368 WifiManager.WIFI_FREQUENCY_BAND_AUTO)).thenReturn( 369 WifiManager.WIFI_FREQUENCY_BAND_AUTO); 370 371 when(factory.makeApConfigStore(eq(context), eq(mBackupManagerProxy))) 372 .thenReturn(mApConfigStore); 373 374 when(factory.makeSupplicantStateTracker( 375 any(Context.class), any(WifiConfigManager.class), 376 any(Handler.class))).thenReturn(mSupplicantStateTracker); 377 378 when(mUserManager.getProfileParent(11)) 379 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "owner", 0)); 380 when(mUserManager.getProfiles(UserHandle.USER_SYSTEM)).thenReturn(Arrays.asList( 381 new UserInfo(UserHandle.USER_SYSTEM, "owner", 0), 382 new UserInfo(11, "managed profile", 0))); 383 384 when(mWificond.createClientInterface()).thenReturn(mClientInterface); 385 when(mClientInterface.asBinder()).thenReturn(mClientInterfaceBinder); 386 387 mWsm = new WifiStateMachine(context, factory, mLooper.getLooper(), 388 mUserManager, mWifiInjector, mBackupManagerProxy, mCountryCode); 389 mWsmThread = getWsmHandlerThread(mWsm); 390 391 final AsyncChannel channel = new AsyncChannel(); 392 Handler handler = new Handler(mLooper.getLooper()) { 393 @Override 394 public void handleMessage(Message msg) { 395 switch (msg.what) { 396 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 397 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 398 mWsmAsyncChannel = channel; 399 } else { 400 Log.d(TAG, "Failed to connect Command channel " + this); 401 } 402 break; 403 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 404 Log.d(TAG, "Command channel disconnected" + this); 405 break; 406 } 407 } 408 }; 409 410 channel.connect(context, handler, mWsm.getMessenger()); 411 mLooper.dispatchAll(); 412 /* Now channel is supposed to be connected */ 413 414 mBinderToken = Binder.clearCallingIdentity(); 415 } 416 417 @After 418 public void cleanUp() throws Exception { 419 Binder.restoreCallingIdentity(mBinderToken); 420 421 if (mSyncThread != null) stopLooper(mSyncThread.getLooper()); 422 if (mWsmThread != null) stopLooper(mWsmThread.getLooper()); 423 if (mP2pThread != null) stopLooper(mP2pThread.getLooper()); 424 425 mWsmThread = null; 426 mP2pThread = null; 427 mSyncThread = null; 428 mWsmAsyncChannel = null; 429 mWsm = null; 430 } 431 432 @Test 433 public void createNew() throws Exception { 434 assertEquals("InitialState", getCurrentState().getName()); 435 436 mWsm.sendMessage(WifiStateMachine.CMD_BOOT_COMPLETED); 437 mLooper.dispatchAll(); 438 assertEquals("InitialState", getCurrentState().getName()); 439 } 440 441 @Test 442 public void loadComponents() throws Exception { 443 when(mWifiNative.startHal()).thenReturn(true); 444 when(mWifiNative.startSupplicant()).thenReturn(true); 445 mWsm.setSupplicantRunning(true); 446 mLooper.dispatchAll(); 447 448 assertEquals("SupplicantStartingState", getCurrentState().getName()); 449 450 when(mWifiNative.setBand(anyInt())).thenReturn(true); 451 when(mWifiNative.setDeviceName(anyString())).thenReturn(true); 452 when(mWifiNative.setManufacturer(anyString())).thenReturn(true); 453 when(mWifiNative.setModelName(anyString())).thenReturn(true); 454 when(mWifiNative.setModelNumber(anyString())).thenReturn(true); 455 when(mWifiNative.setSerialNumber(anyString())).thenReturn(true); 456 when(mWifiNative.setConfigMethods(anyString())).thenReturn(true); 457 when(mWifiNative.setDeviceType(anyString())).thenReturn(true); 458 when(mWifiNative.setSerialNumber(anyString())).thenReturn(true); 459 when(mWifiNative.setScanningMacOui(any(byte[].class))).thenReturn(true); 460 461 mWsm.sendMessage(WifiMonitor.SUP_CONNECTION_EVENT); 462 mLooper.dispatchAll(); 463 464 assertEquals("DisconnectedState", getCurrentState().getName()); 465 } 466 467 @Test 468 public void shouldRequireHalToLeaveInitialState() throws Exception { 469 when(mWifiNative.startHal()).thenReturn(false); 470 mWsm.setSupplicantRunning(true); 471 mLooper.dispatchAll(); 472 assertEquals("InitialState", getCurrentState().getName()); 473 } 474 475 @Test 476 public void shouldRequireSupplicantStartupToLeaveInitialState() throws Exception { 477 when(mWifiNative.startSupplicant()).thenReturn(false); 478 mWsm.setSupplicantRunning(true); 479 mLooper.dispatchAll(); 480 assertEquals("InitialState", getCurrentState().getName()); 481 } 482 483 @Test 484 public void shouldRequireWificondToLeaveInitialState() throws Exception { 485 // We start out with valid default values, break them going backwards so that 486 // we test all the bailout cases. 487 488 // ClientInterface dies after creation. 489 doThrow(new RemoteException()).when(mClientInterfaceBinder).linkToDeath(any(), anyInt()); 490 mWsm.setSupplicantRunning(true); 491 mLooper.dispatchAll(); 492 assertEquals("InitialState", getCurrentState().getName()); 493 494 // Failed to even create the client interface. 495 when(mWificond.createClientInterface()).thenReturn(null); 496 mWsm.setSupplicantRunning(true); 497 mLooper.dispatchAll(); 498 assertEquals("InitialState", getCurrentState().getName()); 499 500 // Failed to get wificond proxy. 501 when(mWifiInjector.makeWificond()).thenReturn(null); 502 mWsm.setSupplicantRunning(true); 503 mLooper.dispatchAll(); 504 assertEquals("InitialState", getCurrentState().getName()); 505 } 506 507 @Test 508 public void loadComponentsFailure() throws Exception { 509 when(mWifiNative.startHal()).thenReturn(false); 510 when(mWifiNative.startSupplicant()).thenReturn(false); 511 512 mWsm.setSupplicantRunning(true); 513 mLooper.dispatchAll(); 514 assertEquals("InitialState", getCurrentState().getName()); 515 516 when(mWifiNative.startHal()).thenReturn(true); 517 mWsm.setSupplicantRunning(true); 518 mLooper.dispatchAll(); 519 assertEquals("InitialState", getCurrentState().getName()); 520 } 521 522 @Test 523 public void checkInitialStateStickyWhenDisabledMode() throws Exception { 524 mLooper.dispatchAll(); 525 assertEquals("InitialState", getCurrentState().getName()); 526 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 527 528 mWsm.setOperationalMode(WifiStateMachine.DISABLED_MODE); 529 mLooper.dispatchAll(); 530 assertEquals(WifiStateMachine.DISABLED_MODE, mWsm.getOperationalModeForTest()); 531 assertEquals("InitialState", getCurrentState().getName()); 532 } 533 534 @Test 535 public void shouldStartSupplicantWhenConnectModeRequested() throws Exception { 536 when(mWifiNative.startHal()).thenReturn(true); 537 when(mWifiNative.startSupplicant()).thenReturn(true); 538 539 // The first time we start out in InitialState, we sit around here. 540 mLooper.dispatchAll(); 541 assertEquals("InitialState", getCurrentState().getName()); 542 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 543 544 // But if someone tells us to enter connect mode, we start up supplicant 545 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 546 mLooper.dispatchAll(); 547 assertEquals("SupplicantStartingState", getCurrentState().getName()); 548 } 549 550 /** 551 * Test that mode changes for WifiStateMachine in the InitialState are realized when supplicant 552 * is started. 553 */ 554 @Test 555 public void checkStartInCorrectStateAfterChangingInitialState() throws Exception { 556 when(mWifiNative.startHal()).thenReturn(true); 557 when(mWifiNative.startSupplicant()).thenReturn(true); 558 559 // Check initial state 560 mLooper.dispatchAll(); 561 assertEquals("InitialState", getCurrentState().getName()); 562 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 563 564 // Update the mode 565 mWsm.setOperationalMode(WifiStateMachine.SCAN_ONLY_MODE); 566 mLooper.dispatchAll(); 567 assertEquals(WifiStateMachine.SCAN_ONLY_MODE, mWsm.getOperationalModeForTest()); 568 569 // Start supplicant so we move to the next state 570 mWsm.setSupplicantRunning(true); 571 mLooper.dispatchAll(); 572 assertEquals("SupplicantStartingState", getCurrentState().getName()); 573 when(mWifiNative.setBand(anyInt())).thenReturn(true); 574 when(mWifiNative.setDeviceName(anyString())).thenReturn(true); 575 when(mWifiNative.setManufacturer(anyString())).thenReturn(true); 576 when(mWifiNative.setModelName(anyString())).thenReturn(true); 577 when(mWifiNative.setModelNumber(anyString())).thenReturn(true); 578 when(mWifiNative.setSerialNumber(anyString())).thenReturn(true); 579 when(mWifiNative.setConfigMethods(anyString())).thenReturn(true); 580 when(mWifiNative.setDeviceType(anyString())).thenReturn(true); 581 when(mWifiNative.setSerialNumber(anyString())).thenReturn(true); 582 when(mWifiNative.setScanningMacOui(any(byte[].class))).thenReturn(true); 583 584 mWsm.sendMessage(WifiMonitor.SUP_CONNECTION_EVENT); 585 mLooper.dispatchAll(); 586 587 assertEquals("ScanModeState", getCurrentState().getName()); 588 } 589 590 private void addNetworkAndVerifySuccess() throws Exception { 591 addNetworkAndVerifySuccess(false); 592 } 593 594 private void addNetworkAndVerifySuccess(boolean isHidden) throws Exception { 595 loadComponents(); 596 597 final HashMap<String, String> nameToValue = new HashMap<>(); 598 599 when(mWifiNative.addNetwork()).thenReturn(0); 600 when(mWifiNative.setNetworkVariable(anyInt(), anyString(), anyString())) 601 .then(new AnswerWithArguments() { 602 public boolean answer(int netId, String name, String value) { 603 if (netId != 0) { 604 Log.d(TAG, "Can't set var " + name + " for " + netId); 605 return false; 606 } 607 608 Log.d(TAG, "Setting var " + name + " to " + value + " for " + netId); 609 nameToValue.put(name, value); 610 return true; 611 } 612 }); 613 614 when(mWifiNative.setNetworkExtra(anyInt(), anyString(), (Map<String, String>) anyObject())) 615 .then(new AnswerWithArguments() { 616 public boolean answer(int netId, String name, Map<String, String> values) { 617 if (netId != 0) { 618 Log.d(TAG, "Can't set extra " + name + " for " + netId); 619 return false; 620 } 621 622 Log.d(TAG, "Setting extra for " + netId); 623 return true; 624 } 625 }); 626 627 when(mWifiNative.getNetworkVariable(anyInt(), anyString())) 628 .then(new AnswerWithArguments() { 629 public String answer(int netId, String name) throws Throwable { 630 if (netId != 0) { 631 Log.d(TAG, "Can't find var " + name + " for " + netId); 632 return null; 633 } 634 String value = nameToValue.get(name); 635 if (value != null) { 636 Log.d(TAG, "Returning var " + name + " to " + value + " for " + netId); 637 } else { 638 Log.d(TAG, "Can't find var " + name + " for " + netId); 639 } 640 return value; 641 } 642 }); 643 644 WifiConfiguration config = new WifiConfiguration(); 645 config.SSID = sSSID; 646 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 647 config.hiddenSSID = isHidden; 648 mLooper.startAutoDispatch(); 649 mWsm.syncAddOrUpdateNetwork(mWsmAsyncChannel, config); 650 mLooper.stopAutoDispatch(); 651 652 verify(mWifiNative).addNetwork(); 653 verify(mWifiNative).setNetworkVariable(0, "ssid", sHexSSID); 654 if (isHidden) { 655 verify(mWifiNative).setNetworkVariable(0, "scan_ssid", Integer.toString(1)); 656 } 657 658 mLooper.startAutoDispatch(); 659 List<WifiConfiguration> configs = mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel); 660 mLooper.stopAutoDispatch(); 661 assertEquals(1, configs.size()); 662 663 WifiConfiguration config2 = configs.get(0); 664 assertEquals("\"GoogleGuest\"", config2.SSID); 665 assertTrue(config2.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)); 666 } 667 668 private void addNetworkAndVerifyFailure() throws Exception { 669 loadComponents(); 670 671 final WifiConfiguration config = new WifiConfiguration(); 672 config.SSID = sSSID; 673 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 674 675 mLooper.startAutoDispatch(); 676 mWsm.syncAddOrUpdateNetwork(mWsmAsyncChannel, config); 677 mLooper.stopAutoDispatch(); 678 679 verify(mWifiNative, never()).addNetwork(); 680 verify(mWifiNative, never()).setNetworkVariable(anyInt(), anyString(), anyString()); 681 682 mLooper.startAutoDispatch(); 683 assertTrue(mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).isEmpty()); 684 mLooper.stopAutoDispatch(); 685 } 686 687 /** 688 * Verifies that the current foreground user is allowed to add a network. 689 */ 690 @Test 691 public void addNetworkAsCurrentUser() throws Exception { 692 addNetworkAndVerifySuccess(); 693 } 694 695 /** 696 * Verifies that a managed profile of the current foreground user is allowed to add a network. 697 */ 698 @Test 699 public void addNetworkAsCurrentUsersManagedProfile() throws Exception { 700 BinderUtil.setUid(MANAGED_PROFILE_UID); 701 addNetworkAndVerifySuccess(); 702 } 703 704 /** 705 * Verifies that a background user is not allowed to add a network. 706 */ 707 @Test 708 public void addNetworkAsOtherUser() throws Exception { 709 BinderUtil.setUid(OTHER_USER_UID); 710 addNetworkAndVerifyFailure(); 711 } 712 713 private void removeNetworkAndVerifySuccess() throws Exception { 714 when(mWifiNative.removeNetwork(0)).thenReturn(true); 715 mLooper.startAutoDispatch(); 716 assertTrue(mWsm.syncRemoveNetwork(mWsmAsyncChannel, 0)); 717 mLooper.stopAutoDispatch(); 718 719 mLooper.startAutoDispatch(); 720 assertTrue(mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).isEmpty()); 721 mLooper.stopAutoDispatch(); 722 } 723 724 private void removeNetworkAndVerifyFailure() throws Exception { 725 mLooper.startAutoDispatch(); 726 assertFalse(mWsm.syncRemoveNetwork(mWsmAsyncChannel, 0)); 727 mLooper.stopAutoDispatch(); 728 729 mLooper.startAutoDispatch(); 730 assertEquals(1, mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).size()); 731 mLooper.stopAutoDispatch(); 732 verify(mWifiNative, never()).removeNetwork(anyInt()); 733 } 734 735 /** 736 * Verifies that the current foreground user is allowed to remove a network. 737 */ 738 @Test 739 public void removeNetworkAsCurrentUser() throws Exception { 740 addNetworkAndVerifySuccess(); 741 removeNetworkAndVerifySuccess(); 742 } 743 744 /** 745 * Verifies that a managed profile of the current foreground user is allowed to remove a 746 * network. 747 */ 748 @Test 749 public void removeNetworkAsCurrentUsersManagedProfile() throws Exception { 750 addNetworkAndVerifySuccess(); 751 BinderUtil.setUid(MANAGED_PROFILE_UID); 752 removeNetworkAndVerifySuccess(); 753 } 754 755 /** 756 * Verifies that a background user is not allowed to remove a network. 757 */ 758 @Test 759 public void removeNetworkAsOtherUser() throws Exception { 760 addNetworkAndVerifySuccess(); 761 BinderUtil.setUid(OTHER_USER_UID); 762 removeNetworkAndVerifyFailure(); 763 } 764 765 private void enableNetworkAndVerifySuccess() throws Exception { 766 when(mWifiNative.selectNetwork(0)).thenReturn(true); 767 768 mLooper.startAutoDispatch(); 769 assertTrue(mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true)); 770 mLooper.stopAutoDispatch(); 771 772 verify(mWifiNative).selectNetwork(0); 773 } 774 775 private void enableNetworkAndVerifyFailure() throws Exception { 776 mLooper.startAutoDispatch(); 777 assertFalse(mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true)); 778 mLooper.stopAutoDispatch(); 779 780 verify(mWifiNative, never()).selectNetwork(anyInt()); 781 } 782 783 /** 784 * Verifies that the current foreground user is allowed to enable a network. 785 */ 786 @Test 787 public void enableNetworkAsCurrentUser() throws Exception { 788 addNetworkAndVerifySuccess(); 789 enableNetworkAndVerifySuccess(); 790 } 791 792 /** 793 * Verifies that a managed profile of the current foreground user is allowed to enable a 794 * network. 795 */ 796 @Test 797 public void enableNetworkAsCurrentUsersManagedProfile() throws Exception { 798 addNetworkAndVerifySuccess(); 799 BinderUtil.setUid(MANAGED_PROFILE_UID); 800 enableNetworkAndVerifySuccess(); 801 } 802 803 /** 804 * Verifies that a background user is not allowed to enable a network. 805 */ 806 @Test 807 public void enableNetworkAsOtherUser() throws Exception { 808 addNetworkAndVerifySuccess(); 809 BinderUtil.setUid(OTHER_USER_UID); 810 enableNetworkAndVerifyFailure(); 811 } 812 813 private void forgetNetworkAndVerifySuccess() throws Exception { 814 when(mWifiNative.removeNetwork(0)).thenReturn(true); 815 mLooper.startAutoDispatch(); 816 final Message result = 817 mWsmAsyncChannel.sendMessageSynchronously(WifiManager.FORGET_NETWORK, 0); 818 mLooper.stopAutoDispatch(); 819 assertEquals(WifiManager.FORGET_NETWORK_SUCCEEDED, result.what); 820 result.recycle(); 821 mLooper.startAutoDispatch(); 822 assertTrue(mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).isEmpty()); 823 mLooper.stopAutoDispatch(); 824 } 825 826 private void forgetNetworkAndVerifyFailure() throws Exception { 827 mLooper.startAutoDispatch(); 828 final Message result = 829 mWsmAsyncChannel.sendMessageSynchronously(WifiManager.FORGET_NETWORK, 0); 830 mLooper.stopAutoDispatch(); 831 assertEquals(WifiManager.FORGET_NETWORK_FAILED, result.what); 832 result.recycle(); 833 mLooper.startAutoDispatch(); 834 assertEquals(1, mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).size()); 835 mLooper.stopAutoDispatch(); 836 verify(mWifiNative, never()).removeNetwork(anyInt()); 837 } 838 839 /** 840 * Helper method to retrieve WifiConfiguration by SSID. 841 * 842 * Returns the associated WifiConfiguration if it is found, null otherwise. 843 */ 844 private WifiConfiguration getWifiConfigurationForNetwork(String ssid) { 845 mLooper.startAutoDispatch(); 846 List<WifiConfiguration> configs = mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel); 847 mLooper.stopAutoDispatch(); 848 849 for (WifiConfiguration checkConfig : configs) { 850 if (checkConfig.SSID.equals(ssid)) { 851 return checkConfig; 852 } 853 } 854 return null; 855 } 856 857 /** 858 * Verifies that the current foreground user is allowed to forget a network. 859 */ 860 @Test 861 public void forgetNetworkAsCurrentUser() throws Exception { 862 addNetworkAndVerifySuccess(); 863 forgetNetworkAndVerifySuccess(); 864 } 865 866 /** 867 * Verifies that a managed profile of the current foreground user is allowed to forget a 868 * network. 869 */ 870 @Test 871 public void forgetNetworkAsCurrentUsersManagedProfile() throws Exception { 872 addNetworkAndVerifySuccess(); 873 BinderUtil.setUid(MANAGED_PROFILE_UID); 874 forgetNetworkAndVerifySuccess(); 875 } 876 877 /** 878 * Verifies that a background user is not allowed to forget a network. 879 */ 880 @Test 881 public void forgetNetworkAsOtherUser() throws Exception { 882 addNetworkAndVerifySuccess(); 883 BinderUtil.setUid(OTHER_USER_UID); 884 forgetNetworkAndVerifyFailure(); 885 } 886 887 private void verifyScan(int band, int reportEvents, Set<Integer> configuredNetworkIds) { 888 ArgumentCaptor<WifiScanner.ScanSettings> scanSettingsCaptor = 889 ArgumentCaptor.forClass(WifiScanner.ScanSettings.class); 890 ArgumentCaptor<WifiScanner.ScanListener> scanListenerCaptor = 891 ArgumentCaptor.forClass(WifiScanner.ScanListener.class); 892 verify(mWifiScanner).startScan(scanSettingsCaptor.capture(), scanListenerCaptor.capture(), 893 eq(null)); 894 WifiScanner.ScanSettings actualSettings = scanSettingsCaptor.getValue(); 895 assertEquals("band", band, actualSettings.band); 896 assertEquals("reportEvents", reportEvents, actualSettings.reportEvents); 897 898 if (configuredNetworkIds == null) { 899 configuredNetworkIds = new HashSet<>(); 900 } 901 Set<Integer> actualConfiguredNetworkIds = new HashSet<>(); 902 if (actualSettings.hiddenNetworkIds != null) { 903 for (int i = 0; i < actualSettings.hiddenNetworkIds.length; ++i) { 904 actualConfiguredNetworkIds.add(actualSettings.hiddenNetworkIds[i]); 905 } 906 } 907 assertEquals("configured networks", configuredNetworkIds, actualConfiguredNetworkIds); 908 909 when(mWifiNative.getScanResults()).thenReturn(getMockScanResults()); 910 mWsm.sendMessage(WifiMonitor.SCAN_RESULTS_EVENT); 911 912 mLooper.dispatchAll(); 913 914 List<ScanResult> reportedResults = mWsm.syncGetScanResultsList(); 915 assertEquals(8, reportedResults.size()); 916 } 917 918 @Test 919 public void scan() throws Exception { 920 addNetworkAndVerifySuccess(); 921 922 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 923 mWsm.startScan(-1, 0, null, null); 924 mLooper.dispatchAll(); 925 926 verifyScan(WifiScanner.WIFI_BAND_BOTH_WITH_DFS, 927 WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN 928 | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT, null); 929 } 930 931 @Test 932 public void scanWithHiddenNetwork() throws Exception { 933 addNetworkAndVerifySuccess(true); 934 935 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 936 mWsm.startScan(-1, 0, null, null); 937 mLooper.dispatchAll(); 938 939 verifyScan(WifiScanner.WIFI_BAND_BOTH_WITH_DFS, 940 WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN 941 | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT, 942 mWifiConfigManager.getHiddenConfiguredNetworkIds()); 943 } 944 945 @Test 946 public void connect() throws Exception { 947 addNetworkAndVerifySuccess(); 948 949 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 950 mLooper.dispatchAll(); 951 952 mLooper.startAutoDispatch(); 953 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 954 mLooper.stopAutoDispatch(); 955 956 verify(mWifiNative).selectNetwork(0); 957 958 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID); 959 mLooper.dispatchAll(); 960 961 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 962 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 963 mLooper.dispatchAll(); 964 965 assertEquals("ObtainingIpState", getCurrentState().getName()); 966 967 DhcpResults dhcpResults = new DhcpResults(); 968 dhcpResults.setGateway("1.2.3.4"); 969 dhcpResults.setIpAddress("192.168.1.100", 0); 970 dhcpResults.addDns("8.8.8.8"); 971 dhcpResults.setLeaseDuration(3600); 972 973 mTestIpManager.injectDhcpSuccess(dhcpResults); 974 mLooper.dispatchAll(); 975 976 assertEquals("ConnectedState", getCurrentState().getName()); 977 } 978 979 @Test 980 public void testDhcpFailure() throws Exception { 981 addNetworkAndVerifySuccess(); 982 983 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 984 mLooper.dispatchAll(); 985 986 mLooper.startAutoDispatch(); 987 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 988 mLooper.stopAutoDispatch(); 989 990 verify(mWifiNative).selectNetwork(0); 991 992 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID); 993 mLooper.dispatchAll(); 994 995 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 996 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 997 mLooper.dispatchAll(); 998 999 assertEquals("ObtainingIpState", getCurrentState().getName()); 1000 1001 mTestIpManager.injectDhcpFailure(); 1002 mLooper.dispatchAll(); 1003 1004 assertEquals("DisconnectingState", getCurrentState().getName()); 1005 } 1006 1007 @Test 1008 public void testBadNetworkEvent() throws Exception { 1009 addNetworkAndVerifySuccess(); 1010 1011 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1012 mLooper.dispatchAll(); 1013 1014 mLooper.startAutoDispatch(); 1015 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 1016 mLooper.stopAutoDispatch(); 1017 1018 verify(mWifiNative).selectNetwork(0); 1019 1020 mWsm.sendMessage(WifiMonitor.NETWORK_DISCONNECTION_EVENT, 0, 0, sBSSID); 1021 mLooper.dispatchAll(); 1022 1023 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 1024 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 1025 mLooper.dispatchAll(); 1026 1027 assertEquals("DisconnectedState", getCurrentState().getName()); 1028 } 1029 1030 1031 @Test 1032 public void smToString() throws Exception { 1033 assertEquals("CMD_CHANNEL_HALF_CONNECTED", mWsm.smToString( 1034 AsyncChannel.CMD_CHANNEL_HALF_CONNECTED)); 1035 assertEquals("CMD_PRE_DHCP_ACTION", mWsm.smToString( 1036 DhcpClient.CMD_PRE_DHCP_ACTION)); 1037 assertEquals("CMD_IP_REACHABILITY_LOST", mWsm.smToString( 1038 WifiStateMachine.CMD_IP_REACHABILITY_LOST)); 1039 } 1040 1041 @Test 1042 public void disconnect() throws Exception { 1043 connect(); 1044 1045 mWsm.sendMessage(WifiMonitor.NETWORK_DISCONNECTION_EVENT, -1, 3, "01:02:03:04:05:06"); 1046 mLooper.dispatchAll(); 1047 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 1048 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.DISCONNECTED)); 1049 mLooper.dispatchAll(); 1050 1051 assertEquals("DisconnectedState", getCurrentState().getName()); 1052 } 1053 1054 /** 1055 * WifiConfigurations default to HasEverConnected to false, creating and adding a config should 1056 * not update this value to true. 1057 * 1058 * Test: Successfully add a network. Check the config and verify 1059 * WifiConfiguration.getHasEverConnected() is false. 1060 */ 1061 @Test 1062 public void addNetworkDoesNotSetHasEverConnectedTrue() throws Exception { 1063 addNetworkAndVerifySuccess(); 1064 1065 WifiConfiguration checkConfig = getWifiConfigurationForNetwork(DEFAULT_TEST_SSID); 1066 assertFalse(checkConfig.getNetworkSelectionStatus().getHasEverConnected()); 1067 } 1068 1069 /** 1070 * Successfully connecting to a network will set WifiConfiguration's value of HasEverConnected 1071 * to true. 1072 * 1073 * Test: Successfully create and connect to a network. Check the config and verify 1074 * WifiConfiguration.getHasEverConnected() is true. 1075 */ 1076 @Test 1077 public void setHasEverConnectedTrueOnConnect() throws Exception { 1078 connect(); 1079 1080 WifiConfiguration checkConfig = getWifiConfigurationForNetwork(DEFAULT_TEST_SSID); 1081 assertTrue(checkConfig.getNetworkSelectionStatus().getHasEverConnected()); 1082 } 1083 1084 /** 1085 * Fail network connection attempt and verify HasEverConnected remains false. 1086 * 1087 * Test: Successfully create a network but fail when connecting. Check the config and verify 1088 * WifiConfiguration.getHasEverConnected() is false. 1089 */ 1090 @Test 1091 public void connectionFailureDoesNotSetHasEverConnectedTrue() throws Exception { 1092 testDhcpFailure(); 1093 1094 WifiConfiguration checkConfig = getWifiConfigurationForNetwork(DEFAULT_TEST_SSID); 1095 assertFalse(checkConfig.getNetworkSelectionStatus().getHasEverConnected()); 1096 } 1097 1098 @Test 1099 public void handleUserSwitch() throws Exception { 1100 assertEquals(UserHandle.USER_SYSTEM, mWifiConfigManager.getCurrentUserId()); 1101 1102 mWsm.handleUserSwitch(10); 1103 mLooper.dispatchAll(); 1104 1105 assertEquals(10, mWifiConfigManager.getCurrentUserId()); 1106 } 1107 1108 @Test 1109 public void iconQueryTest() throws Exception { 1110 /* enable wi-fi */ 1111 addNetworkAndVerifySuccess(); 1112 1113 long bssid = 0x1234567800FFL; 1114 String filename = "iconFileName.png"; 1115 String command = "REQ_HS20_ICON " + Utils.macToString(bssid) + " " + filename; 1116 1117 when(mWifiNative.doCustomSupplicantCommand(command)).thenReturn("OK"); 1118 1119 mLooper.startAutoDispatch(); 1120 boolean result = mWsm.syncQueryPasspointIcon(mWsmAsyncChannel, bssid, filename); 1121 mLooper.stopAutoDispatch(); 1122 1123 verify(mWifiNative).doCustomSupplicantCommand(command); 1124 assertEquals(true, result); 1125 } 1126 1127 /** 1128 * Verifies that, by default, we allow only the "normal" number of log records. 1129 */ 1130 @Test 1131 public void normalLogRecSizeIsUsedByDefault() { 1132 for (int i = 0; i < WifiStateMachine.NUM_LOG_RECS_NORMAL * 2; i++) { 1133 mWsm.sendMessage(WifiStateMachine.CMD_BOOT_COMPLETED); 1134 } 1135 mLooper.dispatchAll(); 1136 assertEquals(WifiStateMachine.NUM_LOG_RECS_NORMAL, mWsm.getLogRecSize()); 1137 } 1138 1139 /** 1140 * Verifies that, in verbose mode, we allow a larger number of log records. 1141 */ 1142 @Test 1143 public void enablingVerboseLoggingIncreasesLogRecSize() { 1144 assertTrue(LOG_REC_LIMIT_IN_VERBOSE_MODE > WifiStateMachine.NUM_LOG_RECS_NORMAL); 1145 mWsm.enableVerboseLogging(1); 1146 for (int i = 0; i < LOG_REC_LIMIT_IN_VERBOSE_MODE * 2; i++) { 1147 mWsm.sendMessage(WifiStateMachine.CMD_BOOT_COMPLETED); 1148 } 1149 mLooper.dispatchAll(); 1150 assertEquals(LOG_REC_LIMIT_IN_VERBOSE_MODE, mWsm.getLogRecSize()); 1151 } 1152 1153 /** 1154 * Verifies that moving from verbose mode to normal mode resets the buffer, and limits new 1155 * records to a small number of entries. 1156 */ 1157 @Test 1158 public void disablingVerboseLoggingClearsRecordsAndDecreasesLogRecSize() { 1159 mWsm.enableVerboseLogging(1); 1160 for (int i = 0; i < LOG_REC_LIMIT_IN_VERBOSE_MODE; i++) { 1161 mWsm.sendMessage(WifiStateMachine.CMD_BOOT_COMPLETED); 1162 } 1163 mLooper.dispatchAll(); 1164 assertEquals(LOG_REC_LIMIT_IN_VERBOSE_MODE, mWsm.getLogRecSize()); 1165 1166 mWsm.enableVerboseLogging(0); 1167 assertEquals(0, mWsm.getLogRecSize()); 1168 for (int i = 0; i < LOG_REC_LIMIT_IN_VERBOSE_MODE; i++) { 1169 mWsm.sendMessage(WifiStateMachine.CMD_BOOT_COMPLETED); 1170 } 1171 mLooper.dispatchAll(); 1172 assertEquals(WifiStateMachine.NUM_LOG_RECS_NORMAL, mWsm.getLogRecSize()); 1173 } 1174 1175 /** Verifies that enabling verbose logging sets the hal log property in eng builds. */ 1176 @Test 1177 public void enablingVerboseLoggingSetsHalLogPropertyInEngBuilds() { 1178 reset(mPropertyService); // Ignore calls made in setUp() 1179 when(mBuildProperties.isEngBuild()).thenReturn(true); 1180 when(mBuildProperties.isUserdebugBuild()).thenReturn(false); 1181 when(mBuildProperties.isUserBuild()).thenReturn(false); 1182 mWsm.enableVerboseLogging(1); 1183 verify(mPropertyService).set("log.tag.WifiHAL", "V"); 1184 } 1185 1186 /** Verifies that enabling verbose logging sets the hal log property in userdebug builds. */ 1187 @Test 1188 public void enablingVerboseLoggingSetsHalLogPropertyInUserdebugBuilds() { 1189 reset(mPropertyService); // Ignore calls made in setUp() 1190 when(mBuildProperties.isUserdebugBuild()).thenReturn(true); 1191 when(mBuildProperties.isEngBuild()).thenReturn(false); 1192 when(mBuildProperties.isUserBuild()).thenReturn(false); 1193 mWsm.enableVerboseLogging(1); 1194 verify(mPropertyService).set("log.tag.WifiHAL", "V"); 1195 } 1196 1197 /** Verifies that enabling verbose logging does NOT set the hal log property in user builds. */ 1198 @Test 1199 public void enablingVerboseLoggingDoeNotSetHalLogPropertyInUserBuilds() { 1200 reset(mPropertyService); // Ignore calls made in setUp() 1201 when(mBuildProperties.isUserBuild()).thenReturn(true); 1202 when(mBuildProperties.isEngBuild()).thenReturn(false); 1203 when(mBuildProperties.isUserdebugBuild()).thenReturn(false); 1204 mWsm.enableVerboseLogging(1); 1205 verify(mPropertyService, never()).set(anyString(), anyString()); 1206 } 1207} 1208