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