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 org.junit.Assert.assertNotNull; 20 import static org.junit.Assert.assertTrue; 21 import static org.junit.Assert.fail; 22 import static org.mockito.ArgumentMatchers.anyString; 23 import static org.mockito.Matchers.anyBoolean; 24 import static org.mockito.Matchers.nullable; 25 import static org.mockito.Mockito.any; 26 import static org.mockito.Mockito.anyInt; 27 import static org.mockito.Mockito.doAnswer; 28 import static org.mockito.Mockito.doReturn; 29 import static org.mockito.Mockito.eq; 30 31 import android.app.ActivityManager; 32 import android.app.AppOpsManager; 33 import android.app.IActivityManager; 34 import android.app.usage.NetworkStatsManager; 35 import android.content.ContentResolver; 36 import android.content.Context; 37 import android.content.IIntentSender; 38 import android.content.Intent; 39 import android.content.SharedPreferences; 40 import android.content.pm.ApplicationInfo; 41 import android.content.pm.PackageInfo; 42 import android.content.pm.PackageManager; 43 import android.net.ConnectivityManager; 44 import android.os.Build; 45 import android.os.Bundle; 46 import android.os.Handler; 47 import android.os.IBinder; 48 import android.os.Looper; 49 import android.os.Message; 50 import android.os.MessageQueue; 51 import android.os.RegistrantList; 52 import android.os.ServiceManager; 53 import android.os.UserManager; 54 import android.permission.PermissionManager; 55 import android.provider.BlockedNumberContract; 56 import android.provider.DeviceConfig; 57 import android.provider.Settings; 58 import android.telephony.AccessNetworkConstants; 59 import android.telephony.CarrierConfigManager; 60 import android.telephony.NetworkRegistrationInfo; 61 import android.telephony.ServiceState; 62 import android.telephony.SubscriptionManager; 63 import android.telephony.TelephonyManager; 64 import android.telephony.TelephonyRegistryManager; 65 import android.telephony.emergency.EmergencyNumber; 66 import android.telephony.euicc.EuiccManager; 67 import android.telephony.ims.ImsCallProfile; 68 import android.test.mock.MockContentProvider; 69 import android.test.mock.MockContentResolver; 70 import android.testing.TestableLooper; 71 import android.util.Log; 72 import android.util.Singleton; 73 74 import com.android.ims.ImsCall; 75 import com.android.ims.ImsEcbm; 76 import com.android.ims.ImsManager; 77 import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager; 78 import com.android.internal.telephony.cdma.EriManager; 79 import com.android.internal.telephony.dataconnection.DataEnabledOverride; 80 import com.android.internal.telephony.dataconnection.DataEnabledSettings; 81 import com.android.internal.telephony.dataconnection.DcTracker; 82 import com.android.internal.telephony.dataconnection.TransportManager; 83 import com.android.internal.telephony.emergency.EmergencyNumberTracker; 84 import com.android.internal.telephony.imsphone.ImsExternalCallTracker; 85 import com.android.internal.telephony.imsphone.ImsPhone; 86 import com.android.internal.telephony.imsphone.ImsPhoneCallTracker; 87 import com.android.internal.telephony.metrics.MetricsCollector; 88 import com.android.internal.telephony.metrics.PersistAtomsStorage; 89 import com.android.internal.telephony.metrics.VoiceCallSessionStats; 90 import com.android.internal.telephony.test.SimulatedCommands; 91 import com.android.internal.telephony.test.SimulatedCommandsVerifier; 92 import com.android.internal.telephony.uicc.IccCardStatus; 93 import com.android.internal.telephony.uicc.IccRecords; 94 import com.android.internal.telephony.uicc.IsimUiccRecords; 95 import com.android.internal.telephony.uicc.RuimRecords; 96 import com.android.internal.telephony.uicc.SIMRecords; 97 import com.android.internal.telephony.uicc.UiccCard; 98 import com.android.internal.telephony.uicc.UiccCardApplication; 99 import com.android.internal.telephony.uicc.UiccController; 100 import com.android.internal.telephony.uicc.UiccProfile; 101 import com.android.server.pm.PackageManagerService; 102 import com.android.server.pm.permission.PermissionManagerService; 103 104 import org.mockito.Mock; 105 import org.mockito.Mockito; 106 import org.mockito.MockitoAnnotations; 107 import org.mockito.invocation.InvocationOnMock; 108 import org.mockito.stubbing.Answer; 109 110 import java.lang.reflect.Field; 111 import java.lang.reflect.InvocationTargetException; 112 import java.lang.reflect.Method; 113 import java.util.ArrayList; 114 import java.util.HashMap; 115 import java.util.HashSet; 116 import java.util.Iterator; 117 import java.util.LinkedList; 118 import java.util.List; 119 import java.util.Set; 120 import java.util.concurrent.CountDownLatch; 121 import java.util.concurrent.TimeUnit; 122 123 public abstract class TelephonyTest { 124 protected static String TAG; 125 126 private static final int MAX_INIT_WAIT_MS = 30000; // 30 seconds 127 128 private static final EmergencyNumber SAMPLE_EMERGENCY_NUMBER = 129 new EmergencyNumber("911", "us", "30", 130 EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED, 131 new ArrayList<String>(), EmergencyNumber.EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING, 132 EmergencyNumber.EMERGENCY_CALL_ROUTING_NORMAL); 133 134 private static final Field MESSAGE_QUEUE_FIELD; 135 private static final Field MESSAGE_WHEN_FIELD; 136 private static final Field MESSAGE_NEXT_FIELD; 137 138 static { 139 try { 140 MESSAGE_QUEUE_FIELD = MessageQueue.class.getDeclaredField("mMessages"); 141 MESSAGE_QUEUE_FIELD.setAccessible(true); 142 MESSAGE_WHEN_FIELD = Message.class.getDeclaredField("when"); 143 MESSAGE_WHEN_FIELD.setAccessible(true); 144 MESSAGE_NEXT_FIELD = Message.class.getDeclaredField("next"); 145 MESSAGE_NEXT_FIELD.setAccessible(true); 146 } catch (NoSuchFieldException e) { 147 throw new RuntimeException("Failed to initialize TelephonyTest", e); 148 } 149 } 150 151 @Mock 152 protected GsmCdmaPhone mPhone; 153 @Mock 154 protected ImsPhone mImsPhone; 155 @Mock 156 protected ServiceStateTracker mSST; 157 @Mock 158 protected EmergencyNumberTracker mEmergencyNumberTracker; 159 @Mock 160 protected GsmCdmaCallTracker mCT; 161 @Mock 162 protected ImsPhoneCallTracker mImsCT; 163 @Mock 164 protected UiccController mUiccController; 165 @Mock 166 protected UiccProfile mUiccProfile; 167 @Mock 168 protected CallManager mCallManager; 169 @Mock 170 protected PhoneNotifier mNotifier; 171 @Mock 172 protected TelephonyComponentFactory mTelephonyComponentFactory; 173 @Mock 174 protected CdmaSubscriptionSourceManager mCdmaSSM; 175 @Mock 176 protected RegistrantList mRegistrantList; 177 @Mock 178 protected IccPhoneBookInterfaceManager mIccPhoneBookIntManager; 179 @Mock 180 protected ImsManager mImsManager; 181 @Mock 182 protected DcTracker mDcTracker; 183 @Mock 184 protected DisplayInfoController mDisplayInfoController; 185 @Mock 186 protected GsmCdmaCall mGsmCdmaCall; 187 @Mock 188 protected ImsCall mImsCall; 189 @Mock 190 protected ImsEcbm mImsEcbm; 191 @Mock 192 protected SubscriptionController mSubscriptionController; 193 @Mock 194 protected ServiceState mServiceState; 195 @Mock 196 protected PackageManagerService mMockPackageManager; 197 @Mock 198 protected PermissionManagerService mMockPermissionManager; 199 200 protected NetworkRegistrationInfo mNetworkRegistrationInfo = 201 new NetworkRegistrationInfo.Builder() 202 .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE) 203 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME) 204 .build(); 205 @Mock 206 protected SimulatedCommandsVerifier mSimulatedCommandsVerifier; 207 @Mock 208 protected InboundSmsHandler mInboundSmsHandler; 209 @Mock 210 protected WspTypeDecoder mWspTypeDecoder; 211 @Mock 212 protected UiccCardApplication mUiccCardApplication3gpp; 213 @Mock 214 protected UiccCardApplication mUiccCardApplication3gpp2; 215 @Mock 216 protected UiccCardApplication mUiccCardApplicationIms; 217 @Mock 218 protected SIMRecords mSimRecords; 219 @Mock 220 protected RuimRecords mRuimRecords; 221 @Mock 222 protected IsimUiccRecords mIsimUiccRecords; 223 @Mock 224 protected ProxyController mProxyController; 225 @Mock 226 protected Singleton<IActivityManager> mIActivityManagerSingleton; 227 @Mock 228 protected IActivityManager mIActivityManager; 229 @Mock 230 protected IIntentSender mIIntentSender; 231 @Mock 232 protected IBinder mIBinder; 233 @Mock 234 protected SmsStorageMonitor mSmsStorageMonitor; 235 @Mock 236 protected SmsUsageMonitor mSmsUsageMonitor; 237 @Mock 238 protected PackageInfo mPackageInfo; 239 @Mock 240 protected ApplicationInfo mApplicationInfo; 241 @Mock 242 protected EriManager mEriManager; 243 @Mock 244 protected IBinder mConnMetLoggerBinder; 245 @Mock 246 protected CarrierSignalAgent mCarrierSignalAgent; 247 @Mock 248 protected CarrierActionAgent mCarrierActionAgent; 249 @Mock 250 protected ImsExternalCallTracker mImsExternalCallTracker; 251 @Mock 252 protected AppSmsManager mAppSmsManager; 253 @Mock 254 protected IccSmsInterfaceManager mIccSmsInterfaceManager; 255 @Mock 256 protected SmsDispatchersController mSmsDispatchersController; 257 @Mock 258 protected DeviceStateMonitor mDeviceStateMonitor; 259 @Mock 260 protected TransportManager mTransportManager; 261 @Mock 262 protected IntentBroadcaster mIntentBroadcaster; 263 @Mock 264 protected NitzStateMachine mNitzStateMachine; 265 @Mock 266 protected RadioConfig mMockRadioConfig; 267 @Mock 268 protected SubscriptionInfoUpdater mSubInfoRecordUpdater; 269 @Mock 270 protected LocaleTracker mLocaleTracker; 271 @Mock 272 protected RestrictedState mRestrictedState; 273 @Mock 274 protected DataEnabledSettings mDataEnabledSettings; 275 @Mock 276 protected DataEnabledOverride mDataEnabledOverride; 277 @Mock 278 protected PhoneConfigurationManager mPhoneConfigurationManager; 279 @Mock 280 protected CellularNetworkValidator mCellularNetworkValidator; 281 @Mock 282 protected UiccCard mUiccCard; 283 @Mock 284 protected MultiSimSettingController mMultiSimSettingController; 285 @Mock 286 protected IccCard mIccCard; 287 @Mock 288 protected NetworkStatsManager mStatsManager; 289 @Mock 290 protected CarrierPrivilegesTracker mCarrierPrivilegesTracker; 291 @Mock 292 protected VoiceCallSessionStats mVoiceCallSessionStats; 293 @Mock 294 protected PersistAtomsStorage mPersistAtomsStorage; 295 @Mock 296 protected MetricsCollector mMetricsCollector; 297 298 protected ActivityManager mActivityManager; 299 protected ImsCallProfile mImsCallProfile; 300 protected TelephonyManager mTelephonyManager; 301 protected TelephonyRegistryManager mTelephonyRegistryManager; 302 protected SubscriptionManager mSubscriptionManager; 303 protected EuiccManager mEuiccManager; 304 protected PackageManager mPackageManager; 305 protected ConnectivityManager mConnectivityManager; 306 protected AppOpsManager mAppOpsManager; 307 protected CarrierConfigManager mCarrierConfigManager; 308 protected UserManager mUserManager; 309 protected SimulatedCommands mSimulatedCommands; 310 protected ContextFixture mContextFixture; 311 protected Context mContext; 312 protected FakeBlockedNumberContentProvider mFakeBlockedNumberContentProvider; 313 private Object mLock = new Object(); 314 private boolean mReady; 315 protected HashMap<String, IBinder> mServiceManagerMockedServices = new HashMap<>(); 316 protected Phone[] mPhones; 317 protected List<TestableLooper> mTestableLoopers = new ArrayList<>(); 318 protected TestableLooper mTestableLooper; 319 320 protected HashMap<Integer, ImsManager> mImsManagerInstances = new HashMap<>(); 321 private HashMap<InstanceKey, Object> mOldInstances = new HashMap<InstanceKey, Object>(); 322 323 private LinkedList<InstanceKey> mInstanceKeys = new LinkedList<InstanceKey>(); 324 325 private class InstanceKey { 326 public final Class mClass; 327 public final String mInstName; 328 public final Object mObj; InstanceKey(final Class c, final String instName, final Object obj)329 InstanceKey(final Class c, final String instName, final Object obj) { 330 mClass = c; 331 mInstName = instName; 332 mObj = obj; 333 } 334 335 @Override hashCode()336 public int hashCode() { 337 return (mClass.getName().hashCode() * 31 + mInstName.hashCode()) * 31; 338 } 339 340 @Override equals(Object obj)341 public boolean equals(Object obj) { 342 if (obj == null || obj.getClass() != getClass()) { 343 return false; 344 } 345 346 InstanceKey other = (InstanceKey) obj; 347 return (other.mClass == mClass && other.mInstName.equals(mInstName) 348 && other.mObj == mObj); 349 } 350 } 351 waitUntilReady()352 protected void waitUntilReady() { 353 synchronized (mLock) { 354 if (!mReady) { 355 try { 356 mLock.wait(MAX_INIT_WAIT_MS); 357 } catch (InterruptedException ie) { 358 } 359 360 if (!mReady) { 361 fail("Telephony tests failed to initialize"); 362 } 363 } 364 } 365 } 366 setReady(boolean ready)367 protected void setReady(boolean ready) { 368 synchronized (mLock) { 369 mReady = ready; 370 mLock.notifyAll(); 371 } 372 } 373 replaceInstance(final Class c, final String instanceName, final Object obj, final Object newValue)374 protected synchronized void replaceInstance(final Class c, final String instanceName, 375 final Object obj, final Object newValue) 376 throws Exception { 377 Field field = c.getDeclaredField(instanceName); 378 field.setAccessible(true); 379 380 InstanceKey key = new InstanceKey(c, instanceName, obj); 381 if (!mOldInstances.containsKey(key)) { 382 mOldInstances.put(key, field.get(obj)); 383 mInstanceKeys.add(key); 384 } 385 field.set(obj, newValue); 386 } 387 restoreInstance(final Class c, final String instanceName, final Object obj)388 protected synchronized void restoreInstance(final Class c, final String instanceName, 389 final Object obj) throws Exception { 390 InstanceKey key = new InstanceKey(c, instanceName, obj); 391 if (mOldInstances.containsKey(key)) { 392 Field field = c.getDeclaredField(instanceName); 393 field.setAccessible(true); 394 field.set(obj, mOldInstances.get(key)); 395 mOldInstances.remove(key); 396 mInstanceKeys.remove(key); 397 } 398 } 399 restoreInstances()400 protected synchronized void restoreInstances() throws Exception { 401 Iterator<InstanceKey> it = mInstanceKeys.descendingIterator(); 402 403 while (it.hasNext()) { 404 InstanceKey key = it.next(); 405 Field field = key.mClass.getDeclaredField(key.mInstName); 406 field.setAccessible(true); 407 field.set(key.mObj, mOldInstances.get(key)); 408 } 409 410 mInstanceKeys.clear(); 411 mOldInstances.clear(); 412 } 413 setUp(String tag)414 protected void setUp(String tag) throws Exception { 415 TAG = tag; 416 MockitoAnnotations.initMocks(this); 417 TelephonyManager.disableServiceHandleCaching(); 418 SubscriptionController.disableCaching(); 419 420 mPhones = new Phone[] {mPhone}; 421 mImsCallProfile = new ImsCallProfile(); 422 mImsCallProfile.setCallerNumberVerificationStatus( 423 ImsCallProfile.VERIFICATION_STATUS_PASSED); 424 mSimulatedCommands = new SimulatedCommands(); 425 mContextFixture = new ContextFixture(); 426 mContext = mContextFixture.getTestDouble(); 427 mFakeBlockedNumberContentProvider = new FakeBlockedNumberContentProvider(); 428 ((MockContentResolver)mContext.getContentResolver()).addProvider( 429 BlockedNumberContract.AUTHORITY, mFakeBlockedNumberContentProvider); 430 mPhone.mCi = mSimulatedCommands; 431 mCT.mCi = mSimulatedCommands; 432 doReturn(mUiccCard).when(mPhone).getUiccCard(); 433 doReturn(mUiccProfile).when(mUiccCard).getUiccProfile(); 434 435 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 436 mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); 437 mTelephonyRegistryManager = (TelephonyRegistryManager) mContext.getSystemService( 438 Context.TELEPHONY_REGISTRY_SERVICE); 439 mSubscriptionManager = (SubscriptionManager) mContext.getSystemService( 440 Context.TELEPHONY_SUBSCRIPTION_SERVICE); 441 mEuiccManager = (EuiccManager) mContext.getSystemService(Context.EUICC_SERVICE); 442 mConnectivityManager = (ConnectivityManager) 443 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 444 mPackageManager = mContext.getPackageManager(); 445 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE); 446 mCarrierConfigManager = 447 (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE); 448 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); 449 450 //mTelephonyComponentFactory 451 doReturn(mTelephonyComponentFactory).when(mTelephonyComponentFactory).inject(anyString()); 452 doReturn(mSST).when(mTelephonyComponentFactory) 453 .makeServiceStateTracker(nullable(GsmCdmaPhone.class), 454 nullable(CommandsInterface.class)); 455 doReturn(mEmergencyNumberTracker).when(mTelephonyComponentFactory) 456 .makeEmergencyNumberTracker(nullable(Phone.class), 457 nullable(CommandsInterface.class)); 458 doReturn(getTestEmergencyNumber()).when(mEmergencyNumberTracker) 459 .getEmergencyNumber(any()); 460 doReturn(mUiccProfile).when(mTelephonyComponentFactory) 461 .makeUiccProfile(nullable(Context.class), nullable(CommandsInterface.class), 462 nullable(IccCardStatus.class), anyInt(), nullable(UiccCard.class), 463 nullable(Object.class)); 464 doReturn(mCT).when(mTelephonyComponentFactory) 465 .makeGsmCdmaCallTracker(nullable(GsmCdmaPhone.class)); 466 doReturn(mIccPhoneBookIntManager).when(mTelephonyComponentFactory) 467 .makeIccPhoneBookInterfaceManager(nullable(Phone.class)); 468 doReturn(mDcTracker).when(mTelephonyComponentFactory) 469 .makeDcTracker(nullable(Phone.class), anyInt()); 470 doReturn(mDisplayInfoController).when(mTelephonyComponentFactory) 471 .makeDisplayInfoController(nullable(Phone.class)); 472 doReturn(mWspTypeDecoder).when(mTelephonyComponentFactory) 473 .makeWspTypeDecoder(nullable(byte[].class)); 474 doReturn(mImsCT).when(mTelephonyComponentFactory) 475 .makeImsPhoneCallTracker(nullable(ImsPhone.class)); 476 doReturn(mCdmaSSM).when(mTelephonyComponentFactory) 477 .getCdmaSubscriptionSourceManagerInstance(nullable(Context.class), 478 nullable(CommandsInterface.class), nullable(Handler.class), 479 anyInt(), nullable(Object.class)); 480 doReturn(mImsExternalCallTracker).when(mTelephonyComponentFactory) 481 .makeImsExternalCallTracker(nullable(ImsPhone.class)); 482 doReturn(mAppSmsManager).when(mTelephonyComponentFactory) 483 .makeAppSmsManager(nullable(Context.class)); 484 doReturn(mCarrierSignalAgent).when(mTelephonyComponentFactory) 485 .makeCarrierSignalAgent(nullable(Phone.class)); 486 doReturn(mCarrierActionAgent).when(mTelephonyComponentFactory) 487 .makeCarrierActionAgent(nullable(Phone.class)); 488 doReturn(mDeviceStateMonitor).when(mTelephonyComponentFactory) 489 .makeDeviceStateMonitor(nullable(Phone.class)); 490 doReturn(mTransportManager).when(mTelephonyComponentFactory) 491 .makeTransportManager(nullable(Phone.class)); 492 doReturn(mNitzStateMachine).when(mTelephonyComponentFactory) 493 .makeNitzStateMachine(nullable(GsmCdmaPhone.class)); 494 doReturn(mLocaleTracker).when(mTelephonyComponentFactory) 495 .makeLocaleTracker(nullable(Phone.class), nullable(NitzStateMachine.class), 496 nullable(Looper.class)); 497 doReturn(mDataEnabledSettings).when(mTelephonyComponentFactory) 498 .makeDataEnabledSettings(nullable(Phone.class)); 499 doReturn(mEriManager).when(mTelephonyComponentFactory) 500 .makeEriManager(nullable(Phone.class), anyInt()); 501 502 //mPhone 503 doReturn(mContext).when(mPhone).getContext(); 504 doReturn(mContext).when(mImsPhone).getContext(); 505 doReturn(true).when(mPhone).getUnitTestMode(); 506 doReturn(mUiccProfile).when(mPhone).getIccCard(); 507 doReturn(mServiceState).when(mPhone).getServiceState(); 508 doReturn(mServiceState).when(mImsPhone).getServiceState(); 509 doReturn(mPhone).when(mImsPhone).getDefaultPhone(); 510 doReturn(true).when(mPhone).isPhoneTypeGsm(); 511 doReturn(PhoneConstants.PHONE_TYPE_GSM).when(mPhone).getPhoneType(); 512 doReturn(mCT).when(mPhone).getCallTracker(); 513 doReturn(mSST).when(mPhone).getServiceStateTracker(); 514 doReturn(mDeviceStateMonitor).when(mPhone).getDeviceStateMonitor(); 515 doReturn(mDisplayInfoController).when(mPhone).getDisplayInfoController(); 516 doReturn(mEmergencyNumberTracker).when(mPhone).getEmergencyNumberTracker(); 517 doReturn(mCarrierSignalAgent).when(mPhone).getCarrierSignalAgent(); 518 doReturn(mCarrierActionAgent).when(mPhone).getCarrierActionAgent(); 519 doReturn(mAppSmsManager).when(mPhone).getAppSmsManager(); 520 doReturn(mIccSmsInterfaceManager).when(mPhone).getIccSmsInterfaceManager(); 521 doReturn(mTransportManager).when(mPhone).getTransportManager(); 522 doReturn(mDataEnabledSettings).when(mPhone).getDataEnabledSettings(); 523 doReturn(mDcTracker).when(mPhone).getDcTracker(anyInt()); 524 doReturn(mCarrierPrivilegesTracker).when(mPhone).getCarrierPrivilegesTracker(); 525 doReturn(mVoiceCallSessionStats).when(mPhone).getVoiceCallSessionStats(); 526 doReturn(mVoiceCallSessionStats).when(mImsPhone).getVoiceCallSessionStats(); 527 mIccSmsInterfaceManager.mDispatchersController = mSmsDispatchersController; 528 529 //mUiccController 530 doReturn(mUiccCardApplication3gpp).when(mUiccController).getUiccCardApplication(anyInt(), 531 eq(UiccController.APP_FAM_3GPP)); 532 doReturn(mUiccCardApplication3gpp2).when(mUiccController).getUiccCardApplication(anyInt(), 533 eq(UiccController.APP_FAM_3GPP2)); 534 doReturn(mUiccCardApplicationIms).when(mUiccController).getUiccCardApplication(anyInt(), 535 eq(UiccController.APP_FAM_IMS)); 536 537 doAnswer(new Answer<IccRecords>() { 538 public IccRecords answer(InvocationOnMock invocation) { 539 switch ((Integer) invocation.getArguments()[1]) { 540 case UiccController.APP_FAM_3GPP: 541 return mSimRecords; 542 case UiccController.APP_FAM_3GPP2: 543 return mRuimRecords; 544 case UiccController.APP_FAM_IMS: 545 return mIsimUiccRecords; 546 default: 547 logd("Unrecognized family " + invocation.getArguments()[1]); 548 return null; 549 } 550 } 551 }).when(mUiccController).getIccRecords(anyInt(), anyInt()); 552 553 //UiccCardApplication 554 doReturn(mSimRecords).when(mUiccCardApplication3gpp).getIccRecords(); 555 doReturn(mRuimRecords).when(mUiccCardApplication3gpp2).getIccRecords(); 556 doReturn(mIsimUiccRecords).when(mUiccCardApplicationIms).getIccRecords(); 557 558 //mUiccProfile 559 doReturn(mSimRecords).when(mUiccProfile).getIccRecords(); 560 doAnswer(new Answer<IccRecords>() { 561 public IccRecords answer(InvocationOnMock invocation) { 562 return (mPhone.isPhoneTypeGsm()) ? mSimRecords : mRuimRecords; 563 } 564 }).when(mUiccProfile).getIccRecords(); 565 566 //mUiccProfile 567 doReturn(mUiccCardApplication3gpp).when(mUiccProfile).getApplication( 568 eq(UiccController.APP_FAM_3GPP)); 569 doReturn(mUiccCardApplication3gpp2).when(mUiccProfile).getApplication( 570 eq(UiccController.APP_FAM_3GPP2)); 571 doReturn(mUiccCardApplicationIms).when(mUiccProfile).getApplication( 572 eq(UiccController.APP_FAM_IMS)); 573 574 //SMS 575 doReturn(true).when(mSmsStorageMonitor).isStorageAvailable(); 576 doReturn(true).when(mSmsUsageMonitor).check(nullable(String.class), anyInt()); 577 doReturn(true).when(mTelephonyManager).getSmsReceiveCapableForPhone(anyInt(), anyBoolean()); 578 doReturn(true).when(mTelephonyManager).getSmsSendCapableForPhone( 579 anyInt(), anyBoolean()); 580 581 //Misc 582 doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_UMTS).when(mServiceState). 583 getRilDataRadioTechnology(); 584 doReturn(mPhone).when(mCT).getPhone(); 585 mImsManagerInstances.put(mPhone.getPhoneId(), mImsManager); 586 doReturn(mImsEcbm).when(mImsManager).getEcbmInterface(); 587 doReturn(mPhone).when(mInboundSmsHandler).getPhone(); 588 doReturn(mImsCallProfile).when(mImsCall).getCallProfile(); 589 doReturn(mIBinder).when(mIIntentSender).asBinder(); 590 doReturn(mIIntentSender).when(mIActivityManager).getIntentSenderWithFeature(anyInt(), 591 nullable(String.class), nullable(String.class), nullable(IBinder.class), 592 nullable(String.class), anyInt(), nullable(Intent[].class), 593 nullable(String[].class), anyInt(), nullable(Bundle.class), anyInt()); 594 doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(anyInt()); 595 doReturn(true).when(mTelephonyManager).isDataCapable(); 596 597 doReturn(TelephonyManager.PHONE_TYPE_GSM).when(mTelephonyManager).getPhoneType(); 598 doReturn(mServiceState).when(mSST).getServiceState(); 599 mSST.mSS = mServiceState; 600 mSST.mRestrictedState = mRestrictedState; 601 mServiceManagerMockedServices.put("connectivity_metrics_logger", mConnMetLoggerBinder); 602 mServiceManagerMockedServices.put("package", mMockPackageManager); 603 mServiceManagerMockedServices.put("permissionmgr", mMockPermissionManager); 604 logd("mMockPermissionManager replaced"); 605 doReturn(new int[]{AccessNetworkConstants.TRANSPORT_TYPE_WWAN, 606 AccessNetworkConstants.TRANSPORT_TYPE_WLAN}) 607 .when(mTransportManager).getAvailableTransports(); 608 doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mTransportManager) 609 .getCurrentTransport(anyInt()); 610 doReturn(true).when(mDataEnabledSettings).isDataEnabled(); 611 doReturn(true).when(mDataEnabledSettings).isDataEnabled(anyInt()); 612 doReturn(true).when(mDataEnabledSettings).isInternalDataEnabled(); 613 doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo( 614 anyInt(), anyInt()); 615 doReturn(new HalVersion(1, 4)).when(mPhone).getHalVersion(); 616 617 //SIM 618 doReturn(1).when(mTelephonyManager).getSimCount(); 619 doReturn(1).when(mTelephonyManager).getPhoneCount(); 620 doReturn(1).when(mTelephonyManager).getActiveModemCount(); 621 // Have getMaxPhoneCount always return the same value with getPhoneCount by default. 622 doAnswer((invocation)->Math.max(mTelephonyManager.getActiveModemCount(), 623 mTelephonyManager.getPhoneCount())) 624 .when(mTelephonyManager).getSupportedModemCount(); 625 doReturn(mStatsManager).when(mContext).getSystemService(eq(Context.NETWORK_STATS_SERVICE)); 626 627 //Data 628 //Initial state is: userData enabled, provisioned. 629 ContentResolver resolver = mContext.getContentResolver(); 630 Settings.Global.putInt(resolver, Settings.Global.MOBILE_DATA, 1); 631 Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 1); 632 Settings.Global.putInt(resolver, 633 Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED, 1); 634 635 // CellularNetworkValidator 636 doReturn(SubscriptionManager.INVALID_PHONE_INDEX) 637 .when(mCellularNetworkValidator).getSubIdInValidation(); 638 doReturn(true).when(mCellularNetworkValidator).isValidationFeatureSupported(); 639 640 // Metrics 641 doReturn(null).when(mContext).getFileStreamPath(anyString()); 642 doReturn(mPersistAtomsStorage).when(mMetricsCollector).getAtomsStorage(); 643 644 //Use reflection to mock singletons 645 replaceInstance(CallManager.class, "INSTANCE", null, mCallManager); 646 replaceInstance(TelephonyComponentFactory.class, "sInstance", null, 647 mTelephonyComponentFactory); 648 replaceInstance(UiccController.class, "mInstance", null, mUiccController); 649 replaceInstance(CdmaSubscriptionSourceManager.class, "sInstance", null, mCdmaSSM); 650 replaceInstance(ImsManager.class, "sImsManagerInstances", null, mImsManagerInstances); 651 replaceInstance(SubscriptionController.class, "sInstance", null, mSubscriptionController); 652 replaceInstance(ProxyController.class, "sProxyController", null, mProxyController); 653 replaceInstance(ActivityManager.class, "IActivityManagerSingleton", null, 654 mIActivityManagerSingleton); 655 replaceInstance(CdmaSubscriptionSourceManager.class, 656 "mCdmaSubscriptionSourceChangedRegistrants", mCdmaSSM, mRegistrantList); 657 replaceInstance(SimulatedCommandsVerifier.class, "sInstance", null, 658 mSimulatedCommandsVerifier); 659 replaceInstance(Singleton.class, "mInstance", mIActivityManagerSingleton, 660 mIActivityManager); 661 replaceInstance(ServiceManager.class, "sCache", null, mServiceManagerMockedServices); 662 replaceInstance(IntentBroadcaster.class, "sIntentBroadcaster", null, mIntentBroadcaster); 663 replaceInstance(TelephonyManager.class, "sInstance", null, 664 mContext.getSystemService(Context.TELEPHONY_SERVICE)); 665 replaceInstance(TelephonyManager.class, "sServiceHandleCacheEnabled", null, false); 666 replaceInstance(PhoneFactory.class, "sMadeDefaults", null, true); 667 replaceInstance(PhoneFactory.class, "sPhone", null, mPhone); 668 replaceInstance(PhoneFactory.class, "sPhones", null, mPhones); 669 replaceInstance(PhoneFactory.class, "sSubInfoRecordUpdater", null, mSubInfoRecordUpdater); 670 replaceInstance(RadioConfig.class, "sRadioConfig", null, mMockRadioConfig); 671 replaceInstance(PhoneConfigurationManager.class, "sInstance", null, 672 mPhoneConfigurationManager); 673 replaceInstance(CellularNetworkValidator.class, "sInstance", null, 674 mCellularNetworkValidator); 675 replaceInstance(MultiSimSettingController.class, "sInstance", null, 676 mMultiSimSettingController); 677 replaceInstance(SubscriptionInfoUpdater.class, "sIsSubInfoInitialized", null, true); 678 replaceInstance(PhoneFactory.class, "sCommandsInterfaces", null, 679 new CommandsInterface[] {mSimulatedCommands}); 680 replaceInstance(PhoneFactory.class, "sMetricsCollector", null, mMetricsCollector); 681 682 assertNotNull("Failed to set up SubscriptionController singleton", 683 SubscriptionController.getInstance()); 684 setReady(false); 685 // create default TestableLooper for test and add to list of monitored loopers 686 mTestableLooper = TestableLooper.get(TelephonyTest.this); 687 if (mTestableLooper != null) { 688 monitorTestableLooper(mTestableLooper); 689 } 690 } 691 tearDown()692 protected void tearDown() throws Exception { 693 // Ensure there are no references to handlers between tests. 694 PhoneConfigurationManager.unregisterAllMultiSimConfigChangeRegistrants(); 695 // unmonitor TestableLooper for TelephonyTest class 696 if (mTestableLooper != null) { 697 unmonitorTestableLooper(mTestableLooper); 698 } 699 // destroy all newly created TestableLoopers so they can be reused 700 for (TestableLooper looper : mTestableLoopers) { 701 looper.destroy(); 702 } 703 TestableLooper.remove(TelephonyTest.this); 704 705 mSimulatedCommands.dispose(); 706 SharedPreferences sharedPreferences = mContext.getSharedPreferences((String) null, 0); 707 sharedPreferences.edit().clear().commit(); 708 709 restoreInstances(); 710 TelephonyManager.enableServiceHandleCaching(); 711 SubscriptionController.enableCaching(); 712 } 713 logd(String s)714 protected static void logd(String s) { 715 Log.d(TAG, s); 716 } 717 718 public static class FakeBlockedNumberContentProvider extends MockContentProvider { 719 public Set<String> mBlockedNumbers = new HashSet<>(); 720 public int mNumEmergencyContactNotifications = 0; 721 722 @Override call(String method, String arg, Bundle extras)723 public Bundle call(String method, String arg, Bundle extras) { 724 switch (method) { 725 case BlockedNumberContract.SystemContract.METHOD_SHOULD_SYSTEM_BLOCK_NUMBER: 726 Bundle bundle = new Bundle(); 727 int blockStatus = mBlockedNumbers.contains(arg) 728 ? BlockedNumberContract.STATUS_BLOCKED_IN_LIST 729 : BlockedNumberContract.STATUS_NOT_BLOCKED; 730 bundle.putInt(BlockedNumberContract.RES_BLOCK_STATUS, blockStatus); 731 return bundle; 732 case BlockedNumberContract.SystemContract.METHOD_NOTIFY_EMERGENCY_CONTACT: 733 mNumEmergencyContactNotifications++; 734 return new Bundle(); 735 default: 736 fail("Method not expected: " + method); 737 } 738 return null; 739 } 740 } 741 742 public static class FakeSettingsConfigProvider extends MockContentProvider { 743 private static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED = 744 DeviceConfig.NAMESPACE_PRIVACY + "/" 745 + "device_identifier_access_restrictions_disabled"; 746 747 @Override call(String method, String arg, Bundle extras)748 public Bundle call(String method, String arg, Bundle extras) { 749 switch (method) { 750 case Settings.CALL_METHOD_GET_CONFIG: { 751 switch (arg) { 752 case PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED: { 753 Bundle bundle = new Bundle(); 754 bundle.putString( 755 PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED, 756 "0"); 757 return bundle; 758 } 759 default: { 760 fail("arg not expected: " + arg); 761 } 762 } 763 break; 764 } 765 default: 766 fail("Method not expected: " + method); 767 } 768 return null; 769 } 770 } 771 setupMockPackagePermissionChecks()772 protected void setupMockPackagePermissionChecks() throws Exception { 773 doReturn(new String[]{TAG}).when(mPackageManager).getPackagesForUid(anyInt()); 774 doReturn(mPackageInfo).when(mPackageManager).getPackageInfo(eq(TAG), anyInt()); 775 } 776 setupMocksForTelephonyPermissions()777 protected void setupMocksForTelephonyPermissions() throws Exception { 778 setupMocksForTelephonyPermissions(Build.VERSION_CODES.Q); 779 } 780 setupMocksForTelephonyPermissions(int targetSdkVersion)781 protected void setupMocksForTelephonyPermissions(int targetSdkVersion) 782 throws Exception { 783 // If the calling package does not meet the new requirements for device identifier access 784 // TelephonyPermissions will query the PackageManager for the ApplicationInfo of the package 785 // to determine the target SDK. For apps targeting Q a SecurityException is thrown 786 // regardless of if the package satisfies the previous requirements for device ID access. 787 788 // Any tests that query for SubscriptionInfo objects will trigger a phone number access 789 // check that will first query the ApplicationInfo as apps targeting R+ can no longer 790 // access the phone number with the READ_PHONE_STATE permission and instead must meet one of 791 // the other requirements. This ApplicationInfo is generalized to any package name since 792 // some tests will simulate invocation from other packages. 793 mApplicationInfo.targetSdkVersion = targetSdkVersion; 794 doReturn(mApplicationInfo).when(mPackageManager).getApplicationInfoAsUser(anyString(), 795 anyInt(), any()); 796 797 // TelephonyPermissions uses a SystemAPI to check if the calling package meets any of the 798 // generic requirements for device identifier access (currently READ_PRIVILEGED_PHONE_STATE, 799 // appop, and device / profile owner checks. This sets up the PermissionManager to return 800 // that access requirements are met. 801 setIdentifierAccess(true); 802 PermissionManager permissionManager = new PermissionManager(mContext, null, 803 mMockPermissionManager); 804 doReturn(permissionManager).when(mContext).getSystemService(eq(Context.PERMISSION_SERVICE)); 805 806 // TelephonyPermissions queries DeviceConfig to determine if the identifier access 807 // restrictions should be enabled; this results in a NPE when DeviceConfig uses 808 // Activity.currentActivity.getContentResolver as the resolver for Settings.Config.getString 809 // since the IContentProvider in the NameValueCache's provider holder is null. 810 Class c = Class.forName("android.provider.Settings$Config"); 811 Field field = c.getDeclaredField("sNameValueCache"); 812 field.setAccessible(true); 813 Object cache = field.get(null); 814 815 c = Class.forName("android.provider.Settings$NameValueCache"); 816 field = c.getDeclaredField("mProviderHolder"); 817 field.setAccessible(true); 818 Object providerHolder = field.get(cache); 819 820 FakeSettingsConfigProvider fakeSettingsProvider = new FakeSettingsConfigProvider(); 821 field = MockContentProvider.class.getDeclaredField("mIContentProvider"); 822 field.setAccessible(true); 823 Object iContentProvider = field.get(fakeSettingsProvider); 824 825 replaceInstance(Class.forName("android.provider.Settings$ContentProviderHolder"), 826 "mContentProvider", providerHolder, iContentProvider); 827 } 828 setIdentifierAccess(boolean hasAccess)829 protected void setIdentifierAccess(boolean hasAccess) { 830 doReturn(hasAccess ? PackageManager.PERMISSION_GRANTED 831 : PackageManager.PERMISSION_DENIED).when( 832 mMockPermissionManager).checkDeviceIdentifierAccess(any(), any(), any(), anyInt(), 833 anyInt()); 834 } 835 setCarrierPrivileges(boolean hasCarrierPrivileges)836 protected void setCarrierPrivileges(boolean hasCarrierPrivileges) { 837 doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(anyInt()); 838 doReturn(hasCarrierPrivileges ? TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS 839 : TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS).when( 840 mTelephonyManager).getCarrierPrivilegeStatus(anyInt()); 841 } 842 setCarrierPrivilegesForSubId(boolean hasCarrierPrivileges, int subId)843 protected void setCarrierPrivilegesForSubId(boolean hasCarrierPrivileges, int subId) { 844 TelephonyManager mockTelephonyManager = Mockito.mock(TelephonyManager.class); 845 doReturn(mockTelephonyManager).when(mTelephonyManager).createForSubscriptionId(subId); 846 doReturn(hasCarrierPrivileges ? TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS 847 : TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS).when( 848 mockTelephonyManager).getCarrierPrivilegeStatus(anyInt()); 849 } 850 waitForHandlerAction(Handler h, long timeoutMillis)851 protected final void waitForHandlerAction(Handler h, long timeoutMillis) { 852 final CountDownLatch lock = new CountDownLatch(1); 853 h.post(lock::countDown); 854 while (lock.getCount() > 0) { 855 try { 856 lock.await(timeoutMillis, TimeUnit.MILLISECONDS); 857 } catch (InterruptedException e) { 858 // do nothing 859 } 860 } 861 } 862 863 /** 864 * Wait for up to 1 second for the handler message queue to clear. 865 */ waitForLastHandlerAction(Handler h)866 protected final void waitForLastHandlerAction(Handler h) { 867 CountDownLatch lock = new CountDownLatch(1); 868 // Allow the handler to start work on stuff. 869 h.postDelayed(lock::countDown, 100); 870 int timeoutCount = 0; 871 while (timeoutCount < 5) { 872 try { 873 if (lock.await(200, TimeUnit.MILLISECONDS)) { 874 // no messages in queue, stop waiting. 875 if (!h.hasMessagesOrCallbacks()) break; 876 lock = new CountDownLatch(1); 877 // Delay to allow the handler thread to start work on stuff. 878 h.postDelayed(lock::countDown, 100); 879 } 880 881 } catch (InterruptedException e) { 882 // do nothing 883 } 884 timeoutCount++; 885 } 886 assertTrue("Handler was not empty before timeout elapsed", timeoutCount < 5); 887 } 888 getTestEmergencyNumber()889 protected final EmergencyNumber getTestEmergencyNumber() { 890 return SAMPLE_EMERGENCY_NUMBER; 891 } 892 invokeMethod( Object instance, String methodName, Class<?>[] parameterClasses, Object[] parameters)893 public static Object invokeMethod( 894 Object instance, String methodName, Class<?>[] parameterClasses, Object[] parameters) { 895 try { 896 Method method = instance.getClass().getDeclaredMethod(methodName, parameterClasses); 897 method.setAccessible(true); 898 return method.invoke(instance, parameters); 899 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { 900 fail(instance.getClass() + " " + methodName + " " + e.getClass().getName()); 901 } 902 return null; 903 } 904 905 /** 906 * Add a TestableLooper to the list of monitored loopers 907 * @param looper added if it doesn't already exist 908 */ monitorTestableLooper(TestableLooper looper)909 public void monitorTestableLooper(TestableLooper looper) { 910 if (!mTestableLoopers.contains(looper)) { 911 mTestableLoopers.add(looper); 912 } 913 } 914 915 /** 916 * Remove a TestableLooper from the list of monitored loopers 917 * @param looper removed if it does exist 918 */ unmonitorTestableLooper(TestableLooper looper)919 public void unmonitorTestableLooper(TestableLooper looper) { 920 if (mTestableLoopers.contains(looper)) { 921 mTestableLoopers.remove(looper); 922 } 923 } 924 925 /** 926 * Handle all messages that can be processed at the current time 927 * for all monitored TestableLoopers 928 */ processAllMessages()929 public void processAllMessages() { 930 if (mTestableLoopers.isEmpty()) { 931 fail("mTestableLoopers is empty. Please make sure to add @RunWithLooper annotation"); 932 } 933 while (!areAllTestableLoopersIdle()) { 934 for (TestableLooper looper : mTestableLoopers) looper.processAllMessages(); 935 } 936 } 937 938 /** 939 * Check if there are any messages to be processed in any monitored TestableLooper 940 * Delayed messages to be handled at a later time will be ignored 941 * @return true if there are no messages that can be handled at the current time 942 * across all monitored TestableLoopers 943 */ areAllTestableLoopersIdle()944 private boolean areAllTestableLoopersIdle() { 945 for (TestableLooper looper : mTestableLoopers) { 946 if (!looper.getLooper().getQueue().isIdle()) return false; 947 } 948 return true; 949 } 950 951 /** 952 * Effectively moves time forward by reducing the time of all messages 953 * for all monitored TestableLoopers 954 * @param milliSeconds number of milliseconds to move time forward by 955 */ moveTimeForward(long milliSeconds)956 public void moveTimeForward(long milliSeconds) { 957 for (TestableLooper looper : mTestableLoopers) { 958 MessageQueue queue = looper.getLooper().getQueue(); 959 try { 960 Message msg = (Message) MESSAGE_QUEUE_FIELD.get(queue); 961 while (msg != null) { 962 long updatedWhen = msg.getWhen() - milliSeconds; 963 if (updatedWhen < 0) { 964 updatedWhen = 0; 965 } 966 MESSAGE_WHEN_FIELD.set(msg, updatedWhen); 967 msg = (Message) MESSAGE_NEXT_FIELD.get(msg); 968 } 969 } catch (IllegalAccessException e) { 970 throw new RuntimeException("Access failed in TelephonyTest", e); 971 } 972 } 973 } 974 } 975