1 /* 2 * Copyright (C) 2016 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.internal.telephony; 18 19 import static com.android.internal.telephony.TelephonyStatsLog.CELLULAR_SERVICE_STATE__FOLD_STATE__STATE_UNKNOWN; 20 21 import static org.junit.Assert.assertTrue; 22 import static org.junit.Assert.fail; 23 import static org.mockito.ArgumentMatchers.anyString; 24 import static org.mockito.ArgumentMatchers.anyBoolean; 25 import static org.mockito.ArgumentMatchers.nullable; 26 import static org.mockito.Mockito.any; 27 import static org.mockito.Mockito.anyInt; 28 import static org.mockito.Mockito.doAnswer; 29 import static org.mockito.Mockito.doReturn; 30 import static org.mockito.Mockito.eq; 31 import static org.mockito.Mockito.lenient; 32 import static org.mockito.Mockito.spy; 33 34 import android.app.ActivityManager; 35 import android.app.AppOpsManager; 36 import android.app.IActivityManager; 37 import android.app.KeyguardManager; 38 import android.app.PropertyInvalidatedCache; 39 import android.app.admin.DevicePolicyManager; 40 import android.app.usage.NetworkStatsManager; 41 import android.content.ContentProvider; 42 import android.content.ContentResolver; 43 import android.content.Context; 44 import android.content.IIntentSender; 45 import android.content.Intent; 46 import android.content.SharedPreferences; 47 import android.content.pm.ApplicationInfo; 48 import android.content.pm.IPackageManager; 49 import android.content.pm.PackageInfo; 50 import android.content.pm.PackageManager; 51 import android.location.LocationManager; 52 import android.net.ConnectivityManager; 53 import android.net.NetworkCapabilities; 54 import android.net.NetworkPolicyManager; 55 import android.net.vcn.VcnManager; 56 import android.net.vcn.VcnNetworkPolicyResult; 57 import android.net.wifi.WifiInfo; 58 import android.net.wifi.WifiManager; 59 import android.os.Build; 60 import android.os.Bundle; 61 import android.os.Handler; 62 import android.os.IBinder; 63 import android.os.Looper; 64 import android.os.Message; 65 import android.os.MessageQueue; 66 import android.os.RegistrantList; 67 import android.os.ServiceManager; 68 import android.os.StrictMode; 69 import android.os.SystemClock; 70 import android.os.UserManager; 71 import android.permission.LegacyPermissionManager; 72 import android.provider.BlockedNumberContract; 73 import android.provider.DeviceConfig; 74 import android.provider.Settings; 75 import android.provider.Telephony; 76 import android.telecom.TelecomManager; 77 import android.telephony.AccessNetworkConstants; 78 import android.telephony.CarrierConfigManager; 79 import android.telephony.CellIdentity; 80 import android.telephony.CellLocation; 81 import android.telephony.NetworkRegistrationInfo; 82 import android.telephony.ServiceState; 83 import android.telephony.SignalStrength; 84 import android.telephony.SubscriptionManager; 85 import android.telephony.TelephonyDisplayInfo; 86 import android.telephony.TelephonyManager; 87 import android.telephony.TelephonyRegistryManager; 88 import android.telephony.emergency.EmergencyNumber; 89 import android.telephony.euicc.EuiccManager; 90 import android.telephony.ims.ImsCallProfile; 91 import android.test.mock.MockContentProvider; 92 import android.test.mock.MockContentResolver; 93 import android.testing.TestableLooper; 94 import android.util.Log; 95 import android.util.Singleton; 96 97 import com.android.ims.ImsCall; 98 import com.android.ims.ImsEcbm; 99 import com.android.ims.ImsManager; 100 import com.android.internal.telephony.analytics.TelephonyAnalytics; 101 import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager; 102 import com.android.internal.telephony.cdma.EriManager; 103 import com.android.internal.telephony.data.AccessNetworksManager; 104 import com.android.internal.telephony.data.CellularNetworkValidator; 105 import com.android.internal.telephony.data.DataConfigManager; 106 import com.android.internal.telephony.data.DataNetworkController; 107 import com.android.internal.telephony.data.DataProfileManager; 108 import com.android.internal.telephony.data.DataRetryManager; 109 import com.android.internal.telephony.data.DataServiceManager; 110 import com.android.internal.telephony.data.DataSettingsManager; 111 import com.android.internal.telephony.data.LinkBandwidthEstimator; 112 import com.android.internal.telephony.data.PhoneSwitcher; 113 import com.android.internal.telephony.domainselection.DomainSelectionResolver; 114 import com.android.internal.telephony.emergency.EmergencyNumberTracker; 115 import com.android.internal.telephony.flags.FeatureFlags; 116 import com.android.internal.telephony.imsphone.ImsExternalCallTracker; 117 import com.android.internal.telephony.imsphone.ImsNrSaModeHandler; 118 import com.android.internal.telephony.imsphone.ImsPhone; 119 import com.android.internal.telephony.imsphone.ImsPhoneCallTracker; 120 import com.android.internal.telephony.metrics.DefaultNetworkMonitor; 121 import com.android.internal.telephony.metrics.DeviceStateHelper; 122 import com.android.internal.telephony.metrics.ImsStats; 123 import com.android.internal.telephony.metrics.MetricsCollector; 124 import com.android.internal.telephony.metrics.PersistAtomsStorage; 125 import com.android.internal.telephony.metrics.ServiceStateStats; 126 import com.android.internal.telephony.metrics.SmsStats; 127 import com.android.internal.telephony.metrics.VoiceCallSessionStats; 128 import com.android.internal.telephony.satellite.SatelliteController; 129 import com.android.internal.telephony.security.CellularIdentifierDisclosureNotifier; 130 import com.android.internal.telephony.security.CellularNetworkSecuritySafetySource; 131 import com.android.internal.telephony.security.NullCipherNotifier; 132 import com.android.internal.telephony.subscription.SubscriptionManagerService; 133 import com.android.internal.telephony.test.SimulatedCommands; 134 import com.android.internal.telephony.test.SimulatedCommandsVerifier; 135 import com.android.internal.telephony.uicc.IccCardStatus; 136 import com.android.internal.telephony.uicc.IccRecords; 137 import com.android.internal.telephony.uicc.IsimUiccRecords; 138 import com.android.internal.telephony.uicc.PinStorage; 139 import com.android.internal.telephony.uicc.RuimRecords; 140 import com.android.internal.telephony.uicc.SIMRecords; 141 import com.android.internal.telephony.uicc.UiccCard; 142 import com.android.internal.telephony.uicc.UiccCardApplication; 143 import com.android.internal.telephony.uicc.UiccController; 144 import com.android.internal.telephony.uicc.UiccPort; 145 import com.android.internal.telephony.uicc.UiccProfile; 146 import com.android.internal.telephony.uicc.UiccSlot; 147 import com.android.internal.telephony.util.WorkerThread; 148 import com.android.server.pm.permission.LegacyPermissionManagerService; 149 150 import org.mockito.Mockito; 151 import org.mockito.invocation.InvocationOnMock; 152 import org.mockito.stubbing.Answer; 153 154 import java.lang.reflect.Field; 155 import java.lang.reflect.InvocationTargetException; 156 import java.lang.reflect.Method; 157 import java.util.ArrayList; 158 import java.util.HashMap; 159 import java.util.HashSet; 160 import java.util.List; 161 import java.util.Set; 162 import java.util.concurrent.CountDownLatch; 163 import java.util.concurrent.Semaphore; 164 import java.util.concurrent.TimeUnit; 165 import java.util.function.Consumer; 166 167 public abstract class TelephonyTest { 168 protected static String TAG; 169 170 private static final int MAX_INIT_WAIT_MS = 30000; // 30 seconds 171 172 private static final EmergencyNumber SAMPLE_EMERGENCY_NUMBER = 173 new EmergencyNumber("911", "us", "30", 174 EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED, 175 new ArrayList<String>(), EmergencyNumber.EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING, 176 EmergencyNumber.EMERGENCY_CALL_ROUTING_NORMAL); 177 178 // Mocked classes 179 protected FeatureFlags mFeatureFlags; 180 protected GsmCdmaPhone mPhone; 181 protected GsmCdmaPhone mPhone2; 182 protected ImsPhone mImsPhone; 183 protected ServiceStateTracker mSST; 184 protected EmergencyNumberTracker mEmergencyNumberTracker; 185 protected GsmCdmaCallTracker mCT; 186 protected ImsPhoneCallTracker mImsCT; 187 protected UiccController mUiccController; 188 protected UiccProfile mUiccProfile; 189 protected UiccSlot mUiccSlot; 190 protected CallManager mCallManager; 191 protected PhoneNotifier mNotifier; 192 protected TelephonyComponentFactory mTelephonyComponentFactory; 193 protected CdmaSubscriptionSourceManager mCdmaSSM; 194 protected RegistrantList mRegistrantList; 195 protected IccPhoneBookInterfaceManager mIccPhoneBookIntManager; 196 protected ImsManager mImsManager; 197 protected DataNetworkController mDataNetworkController; 198 protected DataRetryManager mDataRetryManager; 199 protected DataSettingsManager mDataSettingsManager; 200 protected DataConfigManager mDataConfigManager; 201 protected DataProfileManager mDataProfileManager; 202 protected DisplayInfoController mDisplayInfoController; 203 protected GsmCdmaCall mGsmCdmaCall; 204 protected ImsCall mImsCall; 205 protected ImsEcbm mImsEcbm; 206 protected SubscriptionManagerService mSubscriptionManagerService; 207 protected ServiceState mServiceState; 208 protected IPackageManager.Stub mMockPackageManager; 209 protected LegacyPermissionManagerService mMockLegacyPermissionManager; 210 protected SimulatedCommandsVerifier mSimulatedCommandsVerifier; 211 protected InboundSmsHandler mInboundSmsHandler; 212 protected WspTypeDecoder mWspTypeDecoder; 213 protected UiccCardApplication mUiccCardApplication3gpp; 214 protected UiccCardApplication mUiccCardApplication3gpp2; 215 protected UiccCardApplication mUiccCardApplicationIms; 216 protected SIMRecords mSimRecords; 217 protected SignalStrengthController mSignalStrengthController; 218 protected RuimRecords mRuimRecords; 219 protected IsimUiccRecords mIsimUiccRecords; 220 protected ProxyController mProxyController; 221 protected PhoneSwitcher mPhoneSwitcher; 222 protected Singleton<IActivityManager> mIActivityManagerSingleton; 223 protected IActivityManager mIActivityManager; 224 protected IIntentSender mIIntentSender; 225 protected IBinder mIBinder; 226 protected SmsStorageMonitor mSmsStorageMonitor; 227 protected SmsUsageMonitor mSmsUsageMonitor; 228 protected PackageInfo mPackageInfo; 229 protected ApplicationInfo mApplicationInfo; 230 protected EriManager mEriManager; 231 protected IBinder mConnMetLoggerBinder; 232 protected CarrierSignalAgent mCarrierSignalAgent; 233 protected CarrierActionAgent mCarrierActionAgent; 234 protected ImsExternalCallTracker mImsExternalCallTracker; 235 protected ImsNrSaModeHandler mImsNrSaModeHandler; 236 protected AppSmsManager mAppSmsManager; 237 protected IccSmsInterfaceManager mIccSmsInterfaceManager; 238 protected SmsDispatchersController mSmsDispatchersController; 239 protected DeviceStateMonitor mDeviceStateMonitor; 240 protected AccessNetworksManager mAccessNetworksManager; 241 protected IntentBroadcaster mIntentBroadcaster; 242 protected NitzStateMachine mNitzStateMachine; 243 protected RadioConfig mMockRadioConfig; 244 protected RadioConfigProxy mMockRadioConfigProxy; 245 protected LocaleTracker mLocaleTracker; 246 protected RestrictedState mRestrictedState; 247 protected PhoneConfigurationManager mPhoneConfigurationManager; 248 protected CellularNetworkValidator mCellularNetworkValidator; 249 protected UiccCard mUiccCard; 250 protected UiccPort mUiccPort; 251 protected MultiSimSettingController mMultiSimSettingController; 252 protected IccCard mIccCard; 253 protected NetworkStatsManager mStatsManager; 254 protected CarrierPrivilegesTracker mCarrierPrivilegesTracker; 255 protected VoiceCallSessionStats mVoiceCallSessionStats; 256 protected PersistAtomsStorage mPersistAtomsStorage; 257 protected DefaultNetworkMonitor mDefaultNetworkMonitor; 258 protected MetricsCollector mMetricsCollector; 259 protected SmsStats mSmsStats; 260 protected TelephonyAnalytics mTelephonyAnalytics; 261 protected SignalStrength mSignalStrength; 262 protected WifiManager mWifiManager; 263 protected WifiInfo mWifiInfo; 264 protected ImsStats mImsStats; 265 protected LinkBandwidthEstimator mLinkBandwidthEstimator; 266 protected PinStorage mPinStorage; 267 protected LocationManager mLocationManager; 268 protected CellIdentity mCellIdentity; 269 protected CellLocation mCellLocation; 270 protected DataServiceManager mMockedWwanDataServiceManager; 271 protected DataServiceManager mMockedWlanDataServiceManager; 272 protected ServiceStateStats mServiceStateStats; 273 protected SatelliteController mSatelliteController; 274 protected DeviceStateHelper mDeviceStateHelper; 275 protected CellularNetworkSecuritySafetySource mSafetySource; 276 protected CellularIdentifierDisclosureNotifier mIdentifierDisclosureNotifier; 277 protected DomainSelectionResolver mDomainSelectionResolver; 278 protected NullCipherNotifier mNullCipherNotifier; 279 280 // Initialized classes 281 protected ActivityManager mActivityManager; 282 protected ImsCallProfile mImsCallProfile; 283 protected TelephonyManager mTelephonyManager; 284 protected TelecomManager mTelecomManager; 285 protected TelephonyRegistryManager mTelephonyRegistryManager; 286 protected SubscriptionManager mSubscriptionManager; 287 protected EuiccManager mEuiccManager; 288 protected PackageManager mPackageManager; 289 protected ConnectivityManager mConnectivityManager; 290 protected AppOpsManager mAppOpsManager; 291 protected CarrierConfigManager mCarrierConfigManager; 292 protected UserManager mUserManager; 293 protected DevicePolicyManager mDevicePolicyManager; 294 protected KeyguardManager mKeyguardManager; 295 protected VcnManager mVcnManager; 296 protected NetworkPolicyManager mNetworkPolicyManager; 297 protected SimulatedCommands mSimulatedCommands; 298 protected ContextFixture mContextFixture; 299 protected Context mContext; 300 protected FakeBlockedNumberContentProvider mFakeBlockedNumberContentProvider; 301 private final ContentProvider mContentProvider = spy(new ContextFixture.FakeContentProvider()); 302 private final Object mLock = new Object(); 303 private boolean mReady; 304 protected HashMap<String, IBinder> mServiceManagerMockedServices = new HashMap<>(); 305 protected Phone[] mPhones; 306 protected NetworkRegistrationInfo mNetworkRegistrationInfo = 307 new NetworkRegistrationInfo.Builder() 308 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE) 309 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME) 310 .build(); 311 protected List<TestableLooper> mTestableLoopers = new ArrayList<>(); 312 protected TestableLooper mTestableLooper; 313 314 private final HashMap<InstanceKey, Object> mOldInstances = new HashMap<>(); 315 316 private final List<InstanceKey> mInstanceKeys = new ArrayList<>(); 317 318 protected int mIntegerConsumerResult; 319 protected Semaphore mIntegerConsumerSemaphore = new Semaphore(0); 320 protected Consumer<Integer> mIntegerConsumer = new Consumer<Integer>() { 321 @Override 322 public void accept(Integer integer) { 323 logd("mIIntegerConsumer: result=" + integer); 324 mIntegerConsumerResult = integer; 325 try { 326 mIntegerConsumerSemaphore.release(); 327 } catch (Exception ex) { 328 logd("mIIntegerConsumer: Got exception in releasing semaphore, ex=" + ex); 329 } 330 } 331 }; 332 waitForIntegerConsumerResponse(int expectedNumberOfEvents)333 protected boolean waitForIntegerConsumerResponse(int expectedNumberOfEvents) { 334 for (int i = 0; i < expectedNumberOfEvents; i++) { 335 try { 336 if (!mIntegerConsumerSemaphore.tryAcquire(500 /*Timeout*/, TimeUnit.MILLISECONDS)) { 337 logd("Timeout to receive IIntegerConsumer() callback"); 338 return false; 339 } 340 } catch (Exception ex) { 341 logd("waitForIIntegerConsumerResult: Got exception=" + ex); 342 return false; 343 } 344 } 345 return true; 346 } 347 348 private class InstanceKey { 349 public final Class mClass; 350 public final String mInstName; 351 public final Object mObj; InstanceKey(final Class c, final String instName, final Object obj)352 InstanceKey(final Class c, final String instName, final Object obj) { 353 mClass = c; 354 mInstName = instName; 355 mObj = obj; 356 } 357 358 @Override hashCode()359 public int hashCode() { 360 return (mClass.getName().hashCode() * 31 + mInstName.hashCode()) * 31; 361 } 362 363 @Override equals(Object obj)364 public boolean equals(Object obj) { 365 if (obj == null || !(obj instanceof InstanceKey)) { 366 return false; 367 } 368 369 InstanceKey other = (InstanceKey) obj; 370 return (other.mClass == mClass && other.mInstName.equals(mInstName) 371 && other.mObj == mObj); 372 } 373 } 374 waitUntilReady()375 protected void waitUntilReady() { 376 synchronized (mLock) { 377 long now = SystemClock.elapsedRealtime(); 378 long deadline = now + MAX_INIT_WAIT_MS; 379 while (!mReady && now < deadline) { 380 try { 381 mLock.wait(MAX_INIT_WAIT_MS); 382 } catch (Exception e) { 383 fail("Telephony tests failed to initialize: e=" + e); 384 } 385 now = SystemClock.elapsedRealtime(); 386 } 387 if (!mReady) { 388 fail("Telephony tests failed to initialize"); 389 } 390 } 391 } 392 setReady(boolean ready)393 protected void setReady(boolean ready) { 394 synchronized (mLock) { 395 mReady = ready; 396 mLock.notifyAll(); 397 } 398 } 399 replaceInstance(final Class c, final String instanceName, final Object obj, final Object newValue)400 protected synchronized void replaceInstance(final Class c, final String instanceName, 401 final Object obj, final Object newValue) 402 throws Exception { 403 Field field = c.getDeclaredField(instanceName); 404 field.setAccessible(true); 405 406 InstanceKey key = new InstanceKey(c, instanceName, obj); 407 if (!mOldInstances.containsKey(key)) { 408 mOldInstances.put(key, field.get(obj)); 409 mInstanceKeys.add(key); 410 } 411 field.set(obj, newValue); 412 } 413 getPrivateField(Object object, String fieldName, Class<T> fieldType)414 protected static <T> T getPrivateField(Object object, String fieldName, Class<T> fieldType) 415 throws Exception { 416 417 Class<?> clazz = object.getClass(); 418 Field field = clazz.getDeclaredField(fieldName); 419 field.setAccessible(true); 420 421 return fieldType.cast(field.get(object)); 422 } 423 restoreInstance(final Class c, final String instanceName, final Object obj)424 protected synchronized void restoreInstance(final Class c, final String instanceName, 425 final Object obj) throws Exception { 426 InstanceKey key = new InstanceKey(c, instanceName, obj); 427 if (mOldInstances.containsKey(key)) { 428 Field field = c.getDeclaredField(instanceName); 429 field.setAccessible(true); 430 field.set(obj, mOldInstances.get(key)); 431 mOldInstances.remove(key); 432 mInstanceKeys.remove(key); 433 } 434 } 435 restoreInstances()436 protected synchronized void restoreInstances() throws Exception { 437 for (int i = mInstanceKeys.size() - 1; i >= 0; i--) { 438 InstanceKey key = mInstanceKeys.get(i); 439 Field field = key.mClass.getDeclaredField(key.mInstName); 440 field.setAccessible(true); 441 field.set(key.mObj, mOldInstances.get(key)); 442 } 443 444 mInstanceKeys.clear(); 445 mOldInstances.clear(); 446 } 447 448 // TODO: Unit tests that do not extend TelephonyTest or ImsTestBase should enable strict mode 449 // by calling this method. enableStrictMode()450 public static void enableStrictMode() { 451 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 452 .detectLeakedSqlLiteObjects() 453 .detectLeakedClosableObjects() 454 .detectIncorrectContextUse() 455 .detectLeakedRegistrationObjects() 456 .detectUnsafeIntentLaunch() 457 .detectActivityLeaks() 458 .penaltyLog() 459 .penaltyDeath() 460 .build()); 461 } 462 setUp(String tag)463 protected void setUp(String tag) throws Exception { 464 TAG = tag; 465 enableStrictMode(); 466 mFeatureFlags = Mockito.mock(FeatureFlags.class); 467 mPhone = Mockito.mock(GsmCdmaPhone.class); 468 mPhone2 = Mockito.mock(GsmCdmaPhone.class); 469 mImsPhone = Mockito.mock(ImsPhone.class); 470 mSST = Mockito.mock(ServiceStateTracker.class); 471 mEmergencyNumberTracker = Mockito.mock(EmergencyNumberTracker.class); 472 mCT = Mockito.mock(GsmCdmaCallTracker.class); 473 mImsCT = Mockito.mock(ImsPhoneCallTracker.class); 474 mUiccController = Mockito.mock(UiccController.class); 475 mUiccProfile = Mockito.mock(UiccProfile.class); 476 mUiccSlot = Mockito.mock(UiccSlot.class); 477 mCallManager = Mockito.mock(CallManager.class); 478 mNotifier = Mockito.mock(PhoneNotifier.class); 479 mTelephonyComponentFactory = Mockito.mock(TelephonyComponentFactory.class); 480 mCdmaSSM = Mockito.mock(CdmaSubscriptionSourceManager.class); 481 mRegistrantList = Mockito.mock(RegistrantList.class); 482 mIccPhoneBookIntManager = Mockito.mock(IccPhoneBookInterfaceManager.class); 483 mImsManager = Mockito.mock(ImsManager.class); 484 mDataNetworkController = Mockito.mock(DataNetworkController.class); 485 mDataRetryManager = Mockito.mock(DataRetryManager.class); 486 mDataSettingsManager = Mockito.mock(DataSettingsManager.class); 487 mDataConfigManager = Mockito.mock(DataConfigManager.class); 488 mDataProfileManager = Mockito.mock(DataProfileManager.class); 489 mDisplayInfoController = Mockito.mock(DisplayInfoController.class); 490 mGsmCdmaCall = Mockito.mock(GsmCdmaCall.class); 491 mImsCall = Mockito.mock(ImsCall.class); 492 mImsEcbm = Mockito.mock(ImsEcbm.class); 493 mSubscriptionManagerService = Mockito.mock(SubscriptionManagerService.class); 494 mServiceState = Mockito.mock(ServiceState.class); 495 mMockPackageManager = Mockito.mock(IPackageManager.Stub.class); 496 mMockLegacyPermissionManager = Mockito.mock(LegacyPermissionManagerService.class); 497 mSimulatedCommandsVerifier = Mockito.mock(SimulatedCommandsVerifier.class); 498 mInboundSmsHandler = Mockito.mock(InboundSmsHandler.class); 499 mWspTypeDecoder = Mockito.mock(WspTypeDecoder.class); 500 mUiccCardApplication3gpp = Mockito.mock(UiccCardApplication.class); 501 mUiccCardApplication3gpp2 = Mockito.mock(UiccCardApplication.class); 502 mUiccCardApplicationIms = Mockito.mock(UiccCardApplication.class); 503 mSimRecords = Mockito.mock(SIMRecords.class); 504 mSignalStrengthController = Mockito.mock(SignalStrengthController.class); 505 mRuimRecords = Mockito.mock(RuimRecords.class); 506 mIsimUiccRecords = Mockito.mock(IsimUiccRecords.class); 507 mProxyController = Mockito.mock(ProxyController.class); 508 mPhoneSwitcher = Mockito.mock(PhoneSwitcher.class); 509 mIActivityManagerSingleton = Mockito.mock(Singleton.class); 510 mIActivityManager = Mockito.mock(IActivityManager.class); 511 mIIntentSender = Mockito.mock(IIntentSender.class); 512 mIBinder = Mockito.mock(IBinder.class); 513 mSmsStorageMonitor = Mockito.mock(SmsStorageMonitor.class); 514 mSmsUsageMonitor = Mockito.mock(SmsUsageMonitor.class); 515 mPackageInfo = Mockito.mock(PackageInfo.class); 516 mApplicationInfo = Mockito.mock(ApplicationInfo.class); 517 mEriManager = Mockito.mock(EriManager.class); 518 mConnMetLoggerBinder = Mockito.mock(IBinder.class); 519 mCarrierSignalAgent = Mockito.mock(CarrierSignalAgent.class); 520 mCarrierActionAgent = Mockito.mock(CarrierActionAgent.class); 521 mImsExternalCallTracker = Mockito.mock(ImsExternalCallTracker.class); 522 mImsNrSaModeHandler = Mockito.mock(ImsNrSaModeHandler.class); 523 mAppSmsManager = Mockito.mock(AppSmsManager.class); 524 mIccSmsInterfaceManager = Mockito.mock(IccSmsInterfaceManager.class); 525 mSmsDispatchersController = Mockito.mock(SmsDispatchersController.class); 526 mDeviceStateMonitor = Mockito.mock(DeviceStateMonitor.class); 527 mAccessNetworksManager = Mockito.mock(AccessNetworksManager.class); 528 mIntentBroadcaster = Mockito.mock(IntentBroadcaster.class); 529 mNitzStateMachine = Mockito.mock(NitzStateMachine.class); 530 mMockRadioConfig = Mockito.mock(RadioConfig.class); 531 mMockRadioConfigProxy = Mockito.mock(RadioConfigProxy.class); 532 mLocaleTracker = Mockito.mock(LocaleTracker.class); 533 mRestrictedState = Mockito.mock(RestrictedState.class); 534 mPhoneConfigurationManager = Mockito.mock(PhoneConfigurationManager.class); 535 mCellularNetworkValidator = Mockito.mock(CellularNetworkValidator.class); 536 mUiccCard = Mockito.mock(UiccCard.class); 537 mUiccPort = Mockito.mock(UiccPort.class); 538 mMultiSimSettingController = Mockito.mock(MultiSimSettingController.class); 539 mIccCard = Mockito.mock(IccCard.class); 540 mStatsManager = Mockito.mock(NetworkStatsManager.class); 541 mCarrierPrivilegesTracker = Mockito.mock(CarrierPrivilegesTracker.class); 542 mVoiceCallSessionStats = Mockito.mock(VoiceCallSessionStats.class); 543 mPersistAtomsStorage = Mockito.mock(PersistAtomsStorage.class); 544 mDefaultNetworkMonitor = Mockito.mock(DefaultNetworkMonitor.class); 545 mMetricsCollector = Mockito.mock(MetricsCollector.class); 546 mSmsStats = Mockito.mock(SmsStats.class); 547 mTelephonyAnalytics = Mockito.mock(TelephonyAnalytics.class); 548 mSignalStrength = Mockito.mock(SignalStrength.class); 549 mWifiManager = Mockito.mock(WifiManager.class); 550 mWifiInfo = Mockito.mock(WifiInfo.class); 551 mImsStats = Mockito.mock(ImsStats.class); 552 mLinkBandwidthEstimator = Mockito.mock(LinkBandwidthEstimator.class); 553 mPinStorage = Mockito.mock(PinStorage.class); 554 mLocationManager = Mockito.mock(LocationManager.class); 555 mCellIdentity = Mockito.mock(CellIdentity.class); 556 mCellLocation = Mockito.mock(CellLocation.class); 557 mMockedWwanDataServiceManager = Mockito.mock(DataServiceManager.class); 558 mMockedWlanDataServiceManager = Mockito.mock(DataServiceManager.class); 559 mServiceStateStats = Mockito.mock(ServiceStateStats.class); 560 mSatelliteController = Mockito.mock(SatelliteController.class); 561 mDeviceStateHelper = Mockito.mock(DeviceStateHelper.class); 562 mSafetySource = Mockito.mock(CellularNetworkSecuritySafetySource.class); 563 mIdentifierDisclosureNotifier = Mockito.mock(CellularIdentifierDisclosureNotifier.class); 564 mDomainSelectionResolver = Mockito.mock(DomainSelectionResolver.class); 565 mNullCipherNotifier = Mockito.mock(NullCipherNotifier.class); 566 567 lenient().doReturn(true).when(mFeatureFlags).hsumBroadcast(); 568 lenient().doReturn(true).when(mFeatureFlags).hsumPackageManager(); 569 lenient().doReturn(true).when(mFeatureFlags).dataServiceCheck(); 570 lenient().doReturn(true).when(mFeatureFlags).phoneTypeCleanup(); 571 lenient().doReturn(true).when(mFeatureFlags).cleanupCdma(); 572 573 WorkerThread.reset(); 574 TelephonyManager.disableServiceHandleCaching(); 575 PropertyInvalidatedCache.disableForTestMode(); 576 // For testing do not allow Log.WTF as it can cause test process to crash 577 Log.setWtfHandler((tagString, what, system) -> Log.d(TAG, "WTF captured, ignoring. Tag: " 578 + tagString + ", exception: " + what)); 579 580 mPhones = new Phone[] {mPhone}; 581 mImsCallProfile = new ImsCallProfile(); 582 mImsCallProfile.setCallerNumberVerificationStatus( 583 ImsCallProfile.VERIFICATION_STATUS_PASSED); 584 mSimulatedCommands = new SimulatedCommands(); 585 mContextFixture = new ContextFixture(); 586 mContext = mContextFixture.getTestDouble(); 587 mFakeBlockedNumberContentProvider = new FakeBlockedNumberContentProvider(); 588 ((MockContentResolver)mContext.getContentResolver()).addProvider( 589 BlockedNumberContract.AUTHORITY, mFakeBlockedNumberContentProvider); 590 ((MockContentResolver) mContext.getContentResolver()).addProvider( 591 Settings.AUTHORITY, mContentProvider); 592 ((MockContentResolver) mContext.getContentResolver()).addProvider( 593 Telephony.ServiceStateTable.AUTHORITY, mContentProvider); 594 replaceContentProvider(mContentProvider); 595 596 Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0); 597 598 mServiceManagerMockedServices.put("isub", mSubscriptionManagerService); 599 lenient().doReturn(mSubscriptionManagerService).when(mSubscriptionManagerService) 600 .queryLocalInterface(anyString()); 601 602 mPhone.mCi = mSimulatedCommands; 603 mCT.mCi = mSimulatedCommands; 604 lenient().doReturn(mUiccCard).when(mPhone).getUiccCard(); 605 lenient().doReturn(mUiccCard).when(mUiccSlot).getUiccCard(); 606 lenient().doReturn(mUiccCard).when(mUiccController).getUiccCardForPhone(anyInt()); 607 lenient().doReturn(mUiccPort).when(mPhone).getUiccPort(); 608 lenient().doReturn(mUiccProfile).when(mUiccPort).getUiccProfile(); 609 610 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 611 mTelecomManager = mContext.getSystemService(TelecomManager.class); 612 mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); 613 mTelephonyRegistryManager = (TelephonyRegistryManager) mContext.getSystemService( 614 Context.TELEPHONY_REGISTRY_SERVICE); 615 mSubscriptionManager = (SubscriptionManager) mContext.getSystemService( 616 Context.TELEPHONY_SUBSCRIPTION_SERVICE); 617 mEuiccManager = (EuiccManager) mContext.getSystemService(Context.EUICC_SERVICE); 618 mConnectivityManager = (ConnectivityManager) 619 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 620 mPackageManager = mContext.getPackageManager(); 621 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE); 622 mCarrierConfigManager = 623 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE); 624 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); 625 mDevicePolicyManager = (DevicePolicyManager) mContext.getSystemService( 626 Context.DEVICE_POLICY_SERVICE); 627 mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE); 628 mVcnManager = mContext.getSystemService(VcnManager.class); 629 mNetworkPolicyManager = mContext.getSystemService(NetworkPolicyManager.class); 630 mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); 631 632 //mTelephonyComponentFactory 633 lenient().doReturn(mTelephonyComponentFactory).when(mTelephonyComponentFactory) 634 .inject(anyString()); 635 lenient().doReturn(mSST).when(mTelephonyComponentFactory) 636 .makeServiceStateTracker(nullable(GsmCdmaPhone.class), 637 nullable(CommandsInterface.class), nullable(FeatureFlags.class)); 638 lenient().doReturn(mEmergencyNumberTracker).when(mTelephonyComponentFactory) 639 .makeEmergencyNumberTracker(nullable(Phone.class), 640 nullable(CommandsInterface.class), any(FeatureFlags.class)); 641 lenient().doReturn(getTestEmergencyNumber()).when(mEmergencyNumberTracker) 642 .getEmergencyNumber(any()); 643 lenient().doReturn(mUiccProfile).when(mTelephonyComponentFactory) 644 .makeUiccProfile(nullable(Context.class), nullable(CommandsInterface.class), 645 nullable(IccCardStatus.class), anyInt(), nullable(UiccCard.class), 646 nullable(Object.class), any(FeatureFlags.class)); 647 lenient().doReturn(mCT).when(mTelephonyComponentFactory) 648 .makeGsmCdmaCallTracker(nullable(GsmCdmaPhone.class), any(FeatureFlags.class)); 649 lenient().doReturn(mIccPhoneBookIntManager).when(mTelephonyComponentFactory) 650 .makeIccPhoneBookInterfaceManager(nullable(Phone.class)); 651 lenient().doReturn(mDisplayInfoController).when(mTelephonyComponentFactory) 652 .makeDisplayInfoController(nullable(Phone.class), any(FeatureFlags.class)); 653 lenient().doReturn(mWspTypeDecoder).when(mTelephonyComponentFactory) 654 .makeWspTypeDecoder(nullable(byte[].class)); 655 lenient().doReturn(mImsCT).when(mTelephonyComponentFactory) 656 .makeImsPhoneCallTracker(nullable(ImsPhone.class), any(FeatureFlags.class)); 657 lenient().doReturn(mCdmaSSM).when(mTelephonyComponentFactory) 658 .getCdmaSubscriptionSourceManagerInstance(nullable(Context.class), 659 nullable(CommandsInterface.class), nullable(Handler.class), 660 anyInt(), nullable(Object.class)); 661 lenient().doReturn(mImsExternalCallTracker).when(mTelephonyComponentFactory) 662 .makeImsExternalCallTracker(nullable(ImsPhone.class)); 663 lenient().doReturn(mImsNrSaModeHandler).when(mTelephonyComponentFactory) 664 .makeImsNrSaModeHandler(nullable(ImsPhone.class)); 665 lenient().doReturn(mAppSmsManager).when(mTelephonyComponentFactory) 666 .makeAppSmsManager(nullable(Context.class)); 667 lenient().doReturn(mCarrierSignalAgent).when(mTelephonyComponentFactory) 668 .makeCarrierSignalAgent(nullable(Phone.class)); 669 lenient().doReturn(mCarrierActionAgent).when(mTelephonyComponentFactory) 670 .makeCarrierActionAgent(nullable(Phone.class)); 671 lenient().doReturn(mDeviceStateMonitor).when(mTelephonyComponentFactory) 672 .makeDeviceStateMonitor(nullable(Phone.class), any(FeatureFlags.class)); 673 lenient().doReturn(mAccessNetworksManager).when(mTelephonyComponentFactory) 674 .makeAccessNetworksManager(nullable(Phone.class), any(Looper.class)); 675 lenient().doReturn(mNitzStateMachine).when(mTelephonyComponentFactory) 676 .makeNitzStateMachine(nullable(GsmCdmaPhone.class)); 677 lenient().doReturn(mLocaleTracker).when(mTelephonyComponentFactory) 678 .makeLocaleTracker(nullable(Phone.class), nullable(NitzStateMachine.class), 679 nullable(Looper.class), any(FeatureFlags.class)); 680 lenient().doReturn(mEriManager).when(mTelephonyComponentFactory) 681 .makeEriManager(nullable(Phone.class), anyInt()); 682 lenient().doReturn(mLinkBandwidthEstimator).when(mTelephonyComponentFactory) 683 .makeLinkBandwidthEstimator(nullable(Phone.class), any(Looper.class)); 684 lenient().doReturn(mDataProfileManager).when(mTelephonyComponentFactory) 685 .makeDataProfileManager(any(Phone.class), any(DataNetworkController.class), 686 any(DataServiceManager.class), any(Looper.class), 687 any(FeatureFlags.class), 688 any(DataProfileManager.DataProfileManagerCallback.class)); 689 lenient().doReturn(mSafetySource).when(mTelephonyComponentFactory) 690 .makeCellularNetworkSecuritySafetySource(any(Context.class)); 691 lenient().doReturn(mIdentifierDisclosureNotifier) 692 .when(mTelephonyComponentFactory) 693 .makeIdentifierDisclosureNotifier( 694 nullable(CellularNetworkSecuritySafetySource.class)); 695 lenient().doReturn(mNullCipherNotifier) 696 .when(mTelephonyComponentFactory) 697 .makeNullCipherNotifier(nullable(CellularNetworkSecuritySafetySource.class)); 698 699 //mPhone 700 lenient().doReturn(mContext).when(mPhone).getContext(); 701 lenient().doReturn(mContext).when(mPhone2).getContext(); 702 lenient().doReturn(mContext).when(mImsPhone).getContext(); 703 lenient().doReturn(true).when(mPhone).getUnitTestMode(); 704 lenient().doReturn(mUiccProfile).when(mPhone).getIccCard(); 705 lenient().doReturn(mServiceState).when(mPhone).getServiceState(); 706 lenient().doReturn(mServiceState).when(mImsPhone).getServiceState(); 707 lenient().doReturn(mPhone).when(mImsPhone).getDefaultPhone(); 708 lenient().doReturn(true).when(mPhone).isPhoneTypeGsm(); 709 lenient().doReturn(PhoneConstants.PHONE_TYPE_GSM).when(mPhone).getPhoneType(); 710 lenient().doReturn(mCT).when(mPhone).getCallTracker(); 711 lenient().doReturn(mSST).when(mPhone).getServiceStateTracker(); 712 lenient().doReturn(mDeviceStateMonitor).when(mPhone).getDeviceStateMonitor(); 713 lenient().doReturn(mDisplayInfoController).when(mPhone).getDisplayInfoController(); 714 lenient().doReturn(mSignalStrengthController).when(mPhone).getSignalStrengthController(); 715 lenient().doReturn(mEmergencyNumberTracker).when(mPhone).getEmergencyNumberTracker(); 716 lenient().doReturn(mCarrierSignalAgent).when(mPhone).getCarrierSignalAgent(); 717 lenient().doReturn(mCarrierActionAgent).when(mPhone).getCarrierActionAgent(); 718 lenient().doReturn(mAppSmsManager).when(mPhone).getAppSmsManager(); 719 lenient().doReturn(mIccSmsInterfaceManager).when(mPhone).getIccSmsInterfaceManager(); 720 lenient().doReturn(mAccessNetworksManager).when(mPhone).getAccessNetworksManager(); 721 lenient().doReturn(mDataSettingsManager).when(mDataNetworkController) 722 .getDataSettingsManager(); 723 lenient().doReturn(mDataNetworkController).when(mPhone).getDataNetworkController(); 724 lenient().doReturn(mDataSettingsManager).when(mPhone).getDataSettingsManager(); 725 lenient().doReturn(mCarrierPrivilegesTracker).when(mPhone).getCarrierPrivilegesTracker(); 726 lenient().doReturn(mSignalStrength).when(mPhone).getSignalStrength(); 727 lenient().doReturn(mVoiceCallSessionStats).when(mPhone).getVoiceCallSessionStats(); 728 lenient().doReturn(mVoiceCallSessionStats).when(mImsPhone).getVoiceCallSessionStats(); 729 lenient().doReturn(mSmsStats).when(mPhone).getSmsStats(); 730 lenient().doReturn(mTelephonyAnalytics).when(mPhone).getTelephonyAnalytics(); 731 lenient().doReturn(mImsStats).when(mImsPhone).getImsStats(); 732 mIccSmsInterfaceManager.mDispatchersController = mSmsDispatchersController; 733 lenient().doReturn(mLinkBandwidthEstimator).when(mPhone).getLinkBandwidthEstimator(); 734 lenient().doReturn(mCellIdentity).when(mPhone).getCurrentCellIdentity(); 735 lenient().doReturn(mCellLocation).when(mCellIdentity).asCellLocation(); 736 lenient().doReturn(mDataConfigManager).when(mDataNetworkController).getDataConfigManager(); 737 lenient().doReturn(mDataProfileManager).when(mDataNetworkController) 738 .getDataProfileManager(); 739 lenient().doReturn(mDataRetryManager).when(mDataNetworkController).getDataRetryManager(); 740 lenient().doReturn(mCarrierPrivilegesTracker).when(mPhone).getCarrierPrivilegesTracker(); 741 lenient().doReturn(0).when(mPhone).getPhoneId(); 742 lenient().doReturn(1).when(mPhone2).getPhoneId(); 743 lenient().doReturn(true).when(mPhone).hasCalling(); 744 lenient().doReturn(true).when(mPhone2).hasCalling(); 745 746 //mUiccController 747 lenient().doReturn(mUiccCardApplication3gpp).when(mUiccController).getUiccCardApplication( 748 anyInt(), eq(UiccController.APP_FAM_3GPP)); 749 lenient().doReturn(mUiccCardApplication3gpp2).when(mUiccController).getUiccCardApplication( 750 anyInt(), eq(UiccController.APP_FAM_3GPP2)); 751 lenient().doReturn(mUiccCardApplicationIms).when(mUiccController).getUiccCardApplication( 752 anyInt(), eq(UiccController.APP_FAM_IMS)); 753 lenient().doReturn(mUiccCard).when(mUiccController).getUiccCard(anyInt()); 754 lenient().doReturn(mUiccPort).when(mUiccController).getUiccPort(anyInt()); 755 756 lenient().doAnswer(new Answer<IccRecords>() { 757 public IccRecords answer(InvocationOnMock invocation) { 758 switch ((Integer) invocation.getArguments()[1]) { 759 case UiccController.APP_FAM_3GPP: 760 return mSimRecords; 761 case UiccController.APP_FAM_3GPP2: 762 return mRuimRecords; 763 case UiccController.APP_FAM_IMS: 764 return mIsimUiccRecords; 765 default: 766 logd("Unrecognized family " + invocation.getArguments()[1]); 767 return null; 768 } 769 } 770 }).when(mUiccController).getIccRecords(anyInt(), anyInt()); 771 lenient().doReturn(new UiccSlot[] {mUiccSlot}).when(mUiccController).getUiccSlots(); 772 lenient().doReturn(mUiccSlot).when(mUiccController).getUiccSlotForPhone(anyInt()); 773 lenient().doReturn(mPinStorage).when(mUiccController).getPinStorage(); 774 775 //UiccCardApplication 776 lenient().doReturn(mSimRecords).when(mUiccCardApplication3gpp).getIccRecords(); 777 lenient().doReturn(mRuimRecords).when(mUiccCardApplication3gpp2).getIccRecords(); 778 lenient().doReturn(mIsimUiccRecords).when(mUiccCardApplicationIms).getIccRecords(); 779 780 //mUiccProfile 781 lenient().doReturn(mSimRecords).when(mUiccProfile).getIccRecords(); 782 lenient().doAnswer(new Answer<IccRecords>() { 783 public IccRecords answer(InvocationOnMock invocation) { 784 return mSimRecords; 785 } 786 }).when(mUiccProfile).getIccRecords(); 787 788 //mUiccProfile 789 lenient().doReturn(mUiccCardApplication3gpp).when(mUiccProfile).getApplication( 790 eq(UiccController.APP_FAM_3GPP)); 791 lenient().doReturn(mUiccCardApplication3gpp2).when(mUiccProfile).getApplication( 792 eq(UiccController.APP_FAM_3GPP2)); 793 lenient().doReturn(mUiccCardApplicationIms).when(mUiccProfile).getApplication( 794 eq(UiccController.APP_FAM_IMS)); 795 796 //SMS 797 lenient().doReturn(true).when(mSmsStorageMonitor).isStorageAvailable(); 798 lenient().doReturn(true).when(mSmsUsageMonitor).check(nullable(String.class), anyInt()); 799 lenient().doReturn(true).when(mTelephonyManager).getSmsReceiveCapableForPhone(anyInt(), 800 anyBoolean()); 801 lenient().doReturn(true).when(mTelephonyManager).getSmsSendCapableForPhone( 802 anyInt(), anyBoolean()); 803 804 //Misc 805 lenient().doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_LTE).when(mServiceState) 806 .getRilDataRadioTechnology(); 807 lenient().doReturn(new TelephonyDisplayInfo(TelephonyManager.NETWORK_TYPE_LTE, 808 TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE, false, false, false)) 809 .when(mDisplayInfoController).getTelephonyDisplayInfo(); 810 lenient().doReturn(mPhone).when(mCT).getPhone(); 811 lenient().doReturn(mImsEcbm).when(mImsManager).getEcbmInterface(); 812 lenient().doReturn(mPhone).when(mInboundSmsHandler).getPhone(); 813 lenient().doReturn(mImsCallProfile).when(mImsCall).getCallProfile(); 814 lenient().doReturn(mIBinder).when(mIIntentSender).asBinder(); 815 doAnswer(invocation -> { 816 Intent[] intents = invocation.getArgument(6); 817 if (intents != null && intents.length > 0) { 818 lenient().doReturn(intents[0]).when(mIActivityManager) 819 .getIntentForIntentSender(mIIntentSender); 820 } 821 return mIIntentSender; 822 }).when(mIActivityManager).getIntentSenderWithFeature(anyInt(), 823 nullable(String.class), nullable(String.class), nullable(IBinder.class), 824 nullable(String.class), anyInt(), nullable(Intent[].class), 825 nullable(String[].class), anyInt(), nullable(Bundle.class), anyInt()); 826 lenient().doReturn(mTelephonyManager).when(mTelephonyManager) 827 .createForSubscriptionId(anyInt()); 828 lenient().doReturn(true).when(mTelephonyManager).isDataCapable(); 829 830 mContextFixture.addSystemFeature(PackageManager.FEATURE_TELECOM); 831 mContextFixture.addSystemFeature(PackageManager.FEATURE_TELEPHONY_CALLING); 832 mContextFixture.addSystemFeature(PackageManager.FEATURE_TELEPHONY_DATA); 833 mContextFixture.addSystemFeature(PackageManager.FEATURE_TELEPHONY_EUICC); 834 mContextFixture.addSystemFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING); 835 836 lenient().doReturn(TelephonyManager.PHONE_TYPE_GSM).when(mTelephonyManager).getPhoneType(); 837 lenient().doReturn(mServiceState).when(mSST).getServiceState(); 838 lenient().doReturn(mServiceStateStats).when(mSST).getServiceStateStats(); 839 mSST.mSS = mServiceState; 840 mSST.mRestrictedState = mRestrictedState; 841 mServiceManagerMockedServices.put("connectivity_metrics_logger", mConnMetLoggerBinder); 842 mServiceManagerMockedServices.put("package", mMockPackageManager); 843 mServiceManagerMockedServices.put("legacy_permission", mMockLegacyPermissionManager); 844 logd("mMockLegacyPermissionManager replaced"); 845 lenient().doReturn(new int[]{AccessNetworkConstants.TRANSPORT_TYPE_WWAN, 846 AccessNetworkConstants.TRANSPORT_TYPE_WLAN}) 847 .when(mAccessNetworksManager).getAvailableTransports(); 848 lenient().doReturn(true).when(mDataSettingsManager).isDataEnabled(); 849 lenient().doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo( 850 anyInt(), anyInt()); 851 lenient().doReturn(RIL.RADIO_HAL_VERSION_2_0).when(mPhone).getHalVersion(anyInt()); 852 lenient().doReturn(2).when(mSignalStrength).getLevel(); 853 lenient().doReturn(mMockRadioConfigProxy).when(mMockRadioConfig).getRadioConfigProxy(any()); 854 855 // WiFi 856 lenient().doReturn(mWifiInfo).when(mWifiManager).getConnectionInfo(); 857 lenient().doReturn(2).when(mWifiManager).calculateSignalLevel(anyInt()); 858 lenient().doReturn(4).when(mWifiManager).getMaxSignalLevel(); 859 860 lenient().doAnswer(invocation -> { 861 NetworkCapabilities nc = invocation.getArgument(0); 862 return new VcnNetworkPolicyResult( 863 false /* isTearDownRequested */, nc); 864 }).when(mVcnManager).applyVcnNetworkPolicy(any(), any()); 865 866 //SIM 867 lenient().doReturn(1).when(mTelephonyManager).getSimCount(); 868 lenient().doReturn(1).when(mTelephonyManager).getPhoneCount(); 869 lenient().doReturn(1).when(mTelephonyManager).getActiveModemCount(); 870 // Have getMaxPhoneCount always return the same value with getPhoneCount by default. 871 lenient().doAnswer((invocation)->Math.max(mTelephonyManager.getActiveModemCount(), 872 mTelephonyManager.getPhoneCount())) 873 .when(mTelephonyManager).getSupportedModemCount(); 874 lenient().doReturn(mStatsManager).when(mContext) 875 .getSystemService(eq(Context.NETWORK_STATS_SERVICE)); 876 877 //Data 878 //Initial state is: userData enabled, provisioned. 879 ContentResolver resolver = mContext.getContentResolver(); 880 Settings.Global.putInt(resolver, Settings.Global.MOBILE_DATA, 1); 881 Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 1); 882 Settings.Global.putInt(resolver, 883 Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED, 1); 884 Settings.Global.putInt(resolver, Settings.Global.DATA_ROAMING, 0); 885 886 lenient().doReturn(90).when(mDataConfigManager).getNetworkCapabilityPriority( 887 eq(NetworkCapabilities.NET_CAPABILITY_EIMS)); 888 lenient().doReturn(80).when(mDataConfigManager).getNetworkCapabilityPriority( 889 eq(NetworkCapabilities.NET_CAPABILITY_SUPL)); 890 lenient().doReturn(70).when(mDataConfigManager).getNetworkCapabilityPriority( 891 eq(NetworkCapabilities.NET_CAPABILITY_MMS)); 892 lenient().doReturn(70).when(mDataConfigManager).getNetworkCapabilityPriority( 893 eq(NetworkCapabilities.NET_CAPABILITY_XCAP)); 894 lenient().doReturn(50).when(mDataConfigManager).getNetworkCapabilityPriority( 895 eq(NetworkCapabilities.NET_CAPABILITY_CBS)); 896 lenient().doReturn(50).when(mDataConfigManager).getNetworkCapabilityPriority( 897 eq(NetworkCapabilities.NET_CAPABILITY_MCX)); 898 lenient().doReturn(50).when(mDataConfigManager).getNetworkCapabilityPriority( 899 eq(NetworkCapabilities.NET_CAPABILITY_FOTA)); 900 lenient().doReturn(40).when(mDataConfigManager).getNetworkCapabilityPriority( 901 eq(NetworkCapabilities.NET_CAPABILITY_IMS)); 902 lenient().doReturn(30).when(mDataConfigManager).getNetworkCapabilityPriority( 903 eq(NetworkCapabilities.NET_CAPABILITY_DUN)); 904 lenient().doReturn(20).when(mDataConfigManager).getNetworkCapabilityPriority( 905 eq(NetworkCapabilities.NET_CAPABILITY_ENTERPRISE)); 906 lenient().doReturn(20).when(mDataConfigManager).getNetworkCapabilityPriority( 907 eq(NetworkCapabilities.NET_CAPABILITY_INTERNET)); 908 lenient().doReturn(60000).when(mDataConfigManager).getAnomalyNetworkConnectingTimeoutMs(); 909 lenient().doReturn(60000).when(mDataConfigManager) 910 .getAnomalyNetworkDisconnectingTimeoutMs(); 911 lenient().doReturn(60000).when(mDataConfigManager).getNetworkHandoverTimeoutMs(); 912 lenient().doReturn(new DataConfigManager.EventFrequency(300000, 12)) 913 .when(mDataConfigManager).getAnomalySetupDataCallThreshold(); 914 lenient().doReturn(new DataConfigManager.EventFrequency(0, 2)) 915 .when(mDataConfigManager).getAnomalyImsReleaseRequestThreshold(); 916 lenient().doReturn(new DataConfigManager.EventFrequency(300000, 12)) 917 .when(mDataConfigManager).getAnomalyNetworkUnwantedThreshold(); 918 919 // CellularNetworkValidator 920 lenient().doReturn(SubscriptionManager.INVALID_PHONE_INDEX) 921 .when(mCellularNetworkValidator).getSubIdInValidation(); 922 lenient().doReturn(true).when(mCellularNetworkValidator).isValidationFeatureSupported(); 923 924 // Metrics 925 lenient().doReturn(null).when(mContext).getFileStreamPath(anyString()); 926 lenient().doReturn(mPersistAtomsStorage).when(mMetricsCollector).getAtomsStorage(); 927 lenient().doReturn(mDefaultNetworkMonitor).when(mMetricsCollector) 928 .getDefaultNetworkMonitor(); 929 lenient().doReturn(mWifiManager).when(mContext).getSystemService(eq(Context.WIFI_SERVICE)); 930 lenient().doReturn(mDeviceStateHelper).when(mMetricsCollector).getDeviceStateHelper(); 931 lenient().doReturn(CELLULAR_SERVICE_STATE__FOLD_STATE__STATE_UNKNOWN) 932 .when(mDeviceStateHelper) 933 .getFoldState(); 934 lenient().doReturn(null).when(mContext).getSystemService(eq(Context.DEVICE_STATE_SERVICE)); 935 936 lenient().doReturn(false).when(mDomainSelectionResolver).isDomainSelectionSupported(); 937 DomainSelectionResolver.setDomainSelectionResolver(mDomainSelectionResolver); 938 939 //Use reflection to mock singletons 940 replaceInstance(CallManager.class, "INSTANCE", null, mCallManager); 941 replaceInstance(TelephonyComponentFactory.class, "sInstance", null, 942 mTelephonyComponentFactory); 943 replaceInstance(UiccController.class, "mInstance", null, mUiccController); 944 replaceInstance(CdmaSubscriptionSourceManager.class, "sInstance", null, mCdmaSSM); 945 replaceInstance(SubscriptionManagerService.class, "sInstance", null, 946 mSubscriptionManagerService); 947 replaceInstance(ProxyController.class, "sProxyController", null, mProxyController); 948 replaceInstance(PhoneSwitcher.class, "sPhoneSwitcher", null, mPhoneSwitcher); 949 replaceInstance(ActivityManager.class, "IActivityManagerSingleton", null, 950 mIActivityManagerSingleton); 951 replaceInstance(CdmaSubscriptionSourceManager.class, 952 "mCdmaSubscriptionSourceChangedRegistrants", mCdmaSSM, mRegistrantList); 953 replaceInstance(SimulatedCommandsVerifier.class, "sInstance", null, 954 mSimulatedCommandsVerifier); 955 replaceInstance(Singleton.class, "mInstance", mIActivityManagerSingleton, 956 mIActivityManager); 957 replaceInstance(ServiceManager.class, "sCache", null, mServiceManagerMockedServices); 958 replaceInstance(IntentBroadcaster.class, "sIntentBroadcaster", null, mIntentBroadcaster); 959 replaceInstance(TelephonyManager.class, "sInstance", null, 960 mContext.getSystemService(Context.TELEPHONY_SERVICE)); 961 replaceInstance(TelephonyManager.class, "sServiceHandleCacheEnabled", null, false); 962 replaceInstance(PhoneFactory.class, "sMadeDefaults", null, true); 963 replaceInstance(PhoneFactory.class, "sPhone", null, mPhone); 964 replaceInstance(PhoneFactory.class, "sPhones", null, mPhones); 965 replaceInstance(RadioConfig.class, "sRadioConfig", null, mMockRadioConfig); 966 replaceInstance(PhoneConfigurationManager.class, "sInstance", null, 967 mPhoneConfigurationManager); 968 replaceInstance(CellularNetworkValidator.class, "sInstance", null, 969 mCellularNetworkValidator); 970 replaceInstance(MultiSimSettingController.class, "sInstance", null, 971 mMultiSimSettingController); 972 replaceInstance(PhoneFactory.class, "sCommandsInterfaces", null, 973 new CommandsInterface[] {mSimulatedCommands}); 974 replaceInstance(PhoneFactory.class, "sMetricsCollector", null, mMetricsCollector); 975 replaceInstance(SatelliteController.class, "sInstance", null, mSatelliteController); 976 977 setReady(false); 978 // create default TestableLooper for test and add to list of monitored loopers 979 mTestableLooper = TestableLooper.get(TelephonyTest.this); 980 if (mTestableLooper != null) { 981 monitorTestableLooper(mTestableLooper); 982 } 983 } 984 tearDown()985 protected void tearDown() throws Exception { 986 // Clear all remaining messages 987 if (!mTestableLoopers.isEmpty()) { 988 for (TestableLooper looper : mTestableLoopers) { 989 looper.getLooper().quit(); 990 } 991 } 992 // Ensure there are no references to handlers between tests. 993 PhoneConfigurationManager.unregisterAllMultiSimConfigChangeRegistrants(); 994 // unmonitor TestableLooper for TelephonyTest class 995 if (mTestableLooper != null) { 996 unmonitorTestableLooper(mTestableLooper); 997 } 998 // destroy all newly created TestableLoopers so they can be reused 999 for (TestableLooper looper : mTestableLoopers) { 1000 looper.destroy(); 1001 } 1002 TestableLooper.remove(TelephonyTest.this); 1003 1004 if (mSimulatedCommands != null) { 1005 mSimulatedCommands.dispose(); 1006 } 1007 if (mContext != null) { 1008 SharedPreferences sharedPreferences = mContext.getSharedPreferences((String) null, 0); 1009 if (sharedPreferences != null) { 1010 sharedPreferences.edit().clear().commit(); 1011 } 1012 } 1013 restoreInstances(); 1014 TelephonyManager.enableServiceHandleCaching(); 1015 1016 mNetworkRegistrationInfo = null; 1017 mActivityManager = null; 1018 mImsCallProfile = null; 1019 mTelephonyManager = null; 1020 mTelephonyRegistryManager = null; 1021 mSubscriptionManager = null; 1022 mEuiccManager = null; 1023 mPackageManager = null; 1024 mConnectivityManager = null; 1025 mAppOpsManager = null; 1026 mCarrierConfigManager = null; 1027 mUserManager = null; 1028 mKeyguardManager = null; 1029 mVcnManager = null; 1030 mNetworkPolicyManager = null; 1031 mSimulatedCommands = null; 1032 mContextFixture = null; 1033 mContext = null; 1034 mFakeBlockedNumberContentProvider = null; 1035 mServiceManagerMockedServices.clear(); 1036 mServiceManagerMockedServices = null; 1037 mPhone = null; 1038 mTestableLoopers.clear(); 1039 mTestableLoopers = null; 1040 mTestableLooper = null; 1041 DomainSelectionResolver.setDomainSelectionResolver(null); 1042 } 1043 logd(String s)1044 protected static void logd(String s) { 1045 Log.d(TAG, s); 1046 } 1047 unmockActivityManager()1048 protected void unmockActivityManager() throws Exception { 1049 // Normally, these two should suffice. But we're having some flakiness due to restored 1050 // instances being mocks... 1051 restoreInstance(Singleton.class, "mInstance", mIActivityManagerSingleton); 1052 restoreInstance(ActivityManager.class, "IActivityManagerSingleton", null); 1053 1054 // Copy-paste from android.app.ActivityManager.IActivityManagerSingleton 1055 Singleton<IActivityManager> amSingleton = new Singleton<IActivityManager>() { 1056 @Override 1057 protected IActivityManager create() { 1058 final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); 1059 final IActivityManager am = IActivityManager.Stub.asInterface(b); 1060 return am; 1061 } 1062 }; 1063 1064 // ...so we're setting correct values explicitly, to be sure and not let the flake propagate 1065 // to other tests. 1066 replaceInstance(Singleton.class, "mInstance", mIActivityManagerSingleton, null); 1067 replaceInstance(ActivityManager.class, "IActivityManagerSingleton", null, amSingleton); 1068 } 1069 1070 public static class FakeBlockedNumberContentProvider extends MockContentProvider { 1071 public Set<String> mBlockedNumbers = new HashSet<>(); 1072 public int mNumEmergencyContactNotifications = 0; 1073 1074 @Override call(String method, String arg, Bundle extras)1075 public Bundle call(String method, String arg, Bundle extras) { 1076 switch (method) { 1077 case BlockedNumberContract.SystemContract.METHOD_SHOULD_SYSTEM_BLOCK_NUMBER: 1078 Bundle bundle = new Bundle(); 1079 int blockStatus = mBlockedNumbers.contains(arg) 1080 ? BlockedNumberContract.STATUS_BLOCKED_IN_LIST 1081 : BlockedNumberContract.STATUS_NOT_BLOCKED; 1082 bundle.putInt(BlockedNumberContract.RES_BLOCK_STATUS, blockStatus); 1083 return bundle; 1084 case BlockedNumberContract.SystemContract.METHOD_NOTIFY_EMERGENCY_CONTACT: 1085 mNumEmergencyContactNotifications++; 1086 return new Bundle(); 1087 default: 1088 fail("Method not expected: " + method); 1089 } 1090 return null; 1091 } 1092 } 1093 1094 public static class FakeSettingsConfigProvider extends MockContentProvider { 1095 private static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED = 1096 DeviceConfig.NAMESPACE_PRIVACY + "/" 1097 + "device_identifier_access_restrictions_disabled"; 1098 private HashMap<String, String> mFlags = new HashMap<>(); 1099 1100 @Override call(String method, String arg, Bundle extras)1101 public Bundle call(String method, String arg, Bundle extras) { 1102 logd("FakeSettingsConfigProvider: call called, method: " + method + 1103 " request: " + arg + ", args=" + extras); 1104 Bundle bundle = new Bundle(); 1105 switch (method) { 1106 case Settings.CALL_METHOD_GET_CONFIG: { 1107 switch (arg) { 1108 case PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED: { 1109 bundle.putString( 1110 PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED, 1111 "0"); 1112 return bundle; 1113 } 1114 default: { 1115 fail("arg not expected: " + arg); 1116 } 1117 } 1118 break; 1119 } 1120 case Settings.CALL_METHOD_LIST_CONFIG: 1121 logd("LIST_config: " + mFlags); 1122 Bundle result = new Bundle(); 1123 result.putSerializable(Settings.NameValueTable.VALUE, mFlags); 1124 return result; 1125 case Settings.CALL_METHOD_SET_ALL_CONFIG: 1126 mFlags = (extras != null) 1127 ? (HashMap) extras.getSerializable(Settings.CALL_METHOD_FLAGS_KEY) 1128 : new HashMap<>(); 1129 bundle.putInt(Settings.KEY_CONFIG_SET_ALL_RETURN, 1130 Settings.SET_ALL_RESULT_SUCCESS); 1131 return bundle; 1132 default: 1133 fail("Method not expected: " + method); 1134 } 1135 return null; 1136 } 1137 } 1138 setupMockPackagePermissionChecks()1139 protected void setupMockPackagePermissionChecks() throws Exception { 1140 doReturn(new String[]{TAG}).when(mPackageManager).getPackagesForUid(anyInt()); 1141 doReturn(mPackageInfo).when(mPackageManager).getPackageInfo(eq(TAG), anyInt()); 1142 } 1143 setupMocksForTelephonyPermissions()1144 protected void setupMocksForTelephonyPermissions() throws Exception { 1145 setupMocksForTelephonyPermissions(Build.VERSION_CODES.Q); 1146 } 1147 setupMocksForTelephonyPermissions(int targetSdkVersion)1148 protected void setupMocksForTelephonyPermissions(int targetSdkVersion) 1149 throws Exception { 1150 // If the calling package does not meet the new requirements for device identifier access 1151 // TelephonyPermissions will query the PackageManager for the ApplicationInfo of the package 1152 // to determine the target SDK. For apps targeting Q a SecurityException is thrown 1153 // regardless of if the package satisfies the previous requirements for device ID access. 1154 1155 // Any tests that query for SubscriptionInfo objects will trigger a phone number access 1156 // check that will first query the ApplicationInfo as apps targeting R+ can no longer 1157 // access the phone number with the READ_PHONE_STATE permission and instead must meet one of 1158 // the other requirements. This ApplicationInfo is generalized to any package name since 1159 // some tests will simulate invocation from other packages. 1160 mApplicationInfo.targetSdkVersion = targetSdkVersion; 1161 doReturn(mApplicationInfo).when(mPackageManager).getApplicationInfoAsUser(anyString(), 1162 anyInt(), any()); 1163 1164 // TelephonyPermissions uses a SystemAPI to check if the calling package meets any of the 1165 // generic requirements for device identifier access (currently READ_PRIVILEGED_PHONE_STATE, 1166 // appop, and device / profile owner checks). This sets up the PermissionManager to return 1167 // that access requirements are met. 1168 setIdentifierAccess(true); 1169 LegacyPermissionManager legacyPermissionManager = 1170 new LegacyPermissionManager(mMockLegacyPermissionManager); 1171 doReturn(legacyPermissionManager).when(mContext) 1172 .getSystemService(Context.LEGACY_PERMISSION_SERVICE); 1173 // Also make sure all appop checks fails, to not interfere tests. Tests should explicitly 1174 // mock AppOpManager to return allowed/default mode. Note by default a mock returns 0 which 1175 // is MODE_ALLOWED, hence this setup is necessary. 1176 doReturn(AppOpsManager.MODE_IGNORED).when(mAppOpsManager).noteOpNoThrow( 1177 /* op= */ anyString(), /* uid= */ anyInt(), 1178 /* packageName= */ nullable(String.class), 1179 /* attributionTag= */ nullable(String.class), 1180 /* message= */ nullable(String.class)); 1181 1182 // TelephonyPermissions queries DeviceConfig to determine if the identifier access 1183 // restrictions should be enabled; this results in a NPE when DeviceConfig uses 1184 // Activity.currentActivity.getContentResolver as the resolver for Settings.Config.getString 1185 // since the IContentProvider in the NameValueCache's provider holder is null. 1186 replaceContentProvider(new FakeSettingsConfigProvider()); 1187 } 1188 replaceContentProvider(ContentProvider contentProvider)1189 private void replaceContentProvider(ContentProvider contentProvider) throws Exception { 1190 Class c = Class.forName("android.provider.Settings$Config"); 1191 Field field = c.getDeclaredField("sNameValueCache"); 1192 field.setAccessible(true); 1193 Object cache = field.get(null); 1194 1195 c = Class.forName("android.provider.Settings$NameValueCache"); 1196 field = c.getDeclaredField("mProviderHolder"); 1197 field.setAccessible(true); 1198 Object providerHolder = field.get(cache); 1199 1200 field = MockContentProvider.class.getDeclaredField("mIContentProvider"); 1201 field.setAccessible(true); 1202 Object iContentProvider = field.get(contentProvider); 1203 1204 replaceInstance(Class.forName("android.provider.Settings$ContentProviderHolder"), 1205 "mContentProvider", providerHolder, iContentProvider); 1206 } 1207 setIdentifierAccess(boolean hasAccess)1208 protected void setIdentifierAccess(boolean hasAccess) { 1209 doReturn(hasAccess ? PackageManager.PERMISSION_GRANTED 1210 : PackageManager.PERMISSION_DENIED).when(mMockLegacyPermissionManager) 1211 .checkDeviceIdentifierAccess(any(), any(), any(), anyInt(), anyInt()); 1212 } 1213 setPhoneNumberAccess(int value)1214 protected void setPhoneNumberAccess(int value) { 1215 doReturn(value).when(mMockLegacyPermissionManager).checkPhoneNumberAccess(any(), any(), 1216 any(), anyInt(), anyInt()); 1217 } 1218 setCarrierPrivileges(boolean hasCarrierPrivileges)1219 protected void setCarrierPrivileges(boolean hasCarrierPrivileges) { 1220 doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(anyInt()); 1221 doReturn(hasCarrierPrivileges ? TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS 1222 : TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS).when( 1223 mTelephonyManager).getCarrierPrivilegeStatus(anyInt()); 1224 } 1225 setCarrierPrivilegesForSubId(boolean hasCarrierPrivileges, int subId)1226 protected void setCarrierPrivilegesForSubId(boolean hasCarrierPrivileges, int subId) { 1227 TelephonyManager mockTelephonyManager = Mockito.mock(TelephonyManager.class); 1228 doReturn(mockTelephonyManager).when(mTelephonyManager).createForSubscriptionId(subId); 1229 doReturn(hasCarrierPrivileges ? TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS 1230 : TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS).when( 1231 mockTelephonyManager).getCarrierPrivilegeStatus(anyInt()); 1232 } 1233 waitForDelayedHandlerAction(Handler h, long delayMillis, long timeoutMillis)1234 protected final void waitForDelayedHandlerAction(Handler h, long delayMillis, 1235 long timeoutMillis) { 1236 final CountDownLatch lock = new CountDownLatch(1); 1237 h.postDelayed(lock::countDown, delayMillis); 1238 while (lock.getCount() > 0) { 1239 try { 1240 lock.await(delayMillis + timeoutMillis, TimeUnit.MILLISECONDS); 1241 } catch (InterruptedException e) { 1242 // do nothing 1243 } 1244 } 1245 } 1246 waitForHandlerAction(Handler h, long timeoutMillis)1247 protected final void waitForHandlerAction(Handler h, long timeoutMillis) { 1248 final CountDownLatch lock = new CountDownLatch(1); 1249 h.post(lock::countDown); 1250 while (lock.getCount() > 0) { 1251 try { 1252 lock.await(timeoutMillis, TimeUnit.MILLISECONDS); 1253 } catch (InterruptedException e) { 1254 // do nothing 1255 } 1256 } 1257 } 1258 1259 /** 1260 * Wait for up to 1 second for the handler message queue to clear. 1261 */ waitForLastHandlerAction(Handler h)1262 protected final void waitForLastHandlerAction(Handler h) { 1263 CountDownLatch lock = new CountDownLatch(1); 1264 // Allow the handler to start work on stuff. 1265 h.postDelayed(lock::countDown, 100); 1266 int timeoutCount = 0; 1267 while (timeoutCount < 5) { 1268 try { 1269 if (lock.await(200, TimeUnit.MILLISECONDS)) { 1270 // no messages in queue, stop waiting. 1271 if (!h.hasMessagesOrCallbacks()) break; 1272 lock = new CountDownLatch(1); 1273 // Delay to allow the handler thread to start work on stuff. 1274 h.postDelayed(lock::countDown, 100); 1275 } 1276 1277 } catch (InterruptedException e) { 1278 // do nothing 1279 } 1280 timeoutCount++; 1281 } 1282 assertTrue("Handler was not empty before timeout elapsed", timeoutCount < 5); 1283 } 1284 getTestEmergencyNumber()1285 protected final EmergencyNumber getTestEmergencyNumber() { 1286 return SAMPLE_EMERGENCY_NUMBER; 1287 } 1288 invokeMethod( Object instance, String methodName, Class<?>[] parameterClasses, Object[] parameters)1289 public static Object invokeMethod( 1290 Object instance, String methodName, Class<?>[] parameterClasses, Object[] parameters) { 1291 try { 1292 Method method = instance.getClass().getDeclaredMethod(methodName, parameterClasses); 1293 method.setAccessible(true); 1294 return method.invoke(instance, parameters); 1295 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { 1296 fail(instance.getClass() + " " + methodName + " " + e.getClass().getName()); 1297 } 1298 return null; 1299 } 1300 1301 /** 1302 * Add a TestableLooper to the list of monitored loopers 1303 * @param looper added if it doesn't already exist 1304 */ monitorTestableLooper(TestableLooper looper)1305 public void monitorTestableLooper(TestableLooper looper) { 1306 if (!mTestableLoopers.contains(looper)) { 1307 mTestableLoopers.add(looper); 1308 } 1309 } 1310 1311 /** 1312 * Remove a TestableLooper from the list of monitored loopers 1313 * @param looper removed if it does exist 1314 */ unmonitorTestableLooper(TestableLooper looper)1315 private void unmonitorTestableLooper(TestableLooper looper) { 1316 if (mTestableLoopers.contains(looper)) { 1317 mTestableLoopers.remove(looper); 1318 } 1319 } 1320 1321 /** 1322 * Handle all messages that can be processed at the current time 1323 * for all monitored TestableLoopers 1324 */ processAllMessages()1325 public void processAllMessages() { 1326 if (mTestableLoopers.isEmpty()) { 1327 fail("mTestableLoopers is empty. Please make sure to add @RunWithLooper annotation"); 1328 } 1329 while (!areAllTestableLoopersIdle()) { 1330 for (TestableLooper looper : mTestableLoopers) looper.processAllMessages(); 1331 } 1332 } 1333 1334 /** 1335 * @return {@code true} if there are any messages in the queue. 1336 */ messagesExist()1337 private boolean messagesExist() { 1338 for (TestableLooper looper : mTestableLoopers) { 1339 if (looper.peekWhen() > 0) { 1340 return true; 1341 } 1342 } 1343 return false; 1344 } 1345 1346 /** 1347 * Handle all messages including the delayed messages. 1348 */ processAllFutureMessages()1349 public void processAllFutureMessages() { 1350 final long now = SystemClock.uptimeMillis(); 1351 while (messagesExist()) { 1352 for (TestableLooper looper : mTestableLoopers) { 1353 long nextDelay = looper.peekWhen() - now; 1354 if (nextDelay > 0) { 1355 looper.moveTimeForward(nextDelay); 1356 } 1357 } 1358 processAllMessages(); 1359 } 1360 } 1361 1362 /** 1363 * Check if there are any messages to be processed in any monitored TestableLooper 1364 * Delayed messages to be handled at a later time will be ignored 1365 * @return true if there are no messages that can be handled at the current time 1366 * across all monitored TestableLoopers 1367 */ areAllTestableLoopersIdle()1368 private boolean areAllTestableLoopersIdle() { 1369 for (TestableLooper looper : mTestableLoopers) { 1370 if (!looper.getLooper().getQueue().isIdle()) return false; 1371 } 1372 return true; 1373 } 1374 1375 /** 1376 * Effectively moves time forward by reducing the time of all messages 1377 * for all monitored TestableLoopers 1378 * @param milliSeconds number of milliseconds to move time forward by 1379 */ moveTimeForward(long milliSeconds)1380 public void moveTimeForward(long milliSeconds) { 1381 for (TestableLooper looper : mTestableLoopers) { 1382 looper.moveTimeForward(milliSeconds); 1383 } 1384 } 1385 } 1386