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.fail;
21 import static org.mockito.ArgumentMatchers.anyString;
22 import static org.mockito.Matchers.anyBoolean;
23 import static org.mockito.Matchers.nullable;
24 import static org.mockito.Mockito.any;
25 import static org.mockito.Mockito.anyInt;
26 import static org.mockito.Mockito.doAnswer;
27 import static org.mockito.Mockito.doReturn;
28 import static org.mockito.Mockito.eq;
29 
30 import android.app.ActivityManager;
31 import android.app.IActivityManager;
32 import android.content.ContentResolver;
33 import android.content.Context;
34 import android.content.IIntentSender;
35 import android.content.Intent;
36 import android.content.SharedPreferences;
37 import android.content.pm.ApplicationInfo;
38 import android.content.pm.PackageInfo;
39 import android.content.pm.PackageManager;
40 import android.os.Build;
41 import android.os.Bundle;
42 import android.os.Handler;
43 import android.os.IBinder;
44 import android.os.IDeviceIdleController;
45 import android.os.Looper;
46 import android.os.RegistrantList;
47 import android.os.ServiceManager;
48 import android.provider.BlockedNumberContract;
49 import android.provider.DeviceConfig;
50 import android.provider.Settings;
51 import android.telephony.AccessNetworkConstants;
52 import android.telephony.NetworkRegistrationInfo;
53 import android.telephony.ServiceState;
54 import android.telephony.SubscriptionManager;
55 import android.telephony.TelephonyManager;
56 import android.telephony.emergency.EmergencyNumber;
57 import android.telephony.euicc.EuiccManager;
58 import android.telephony.ims.ImsCallProfile;
59 import android.test.mock.MockContentProvider;
60 import android.test.mock.MockContentResolver;
61 import android.util.Log;
62 import android.util.Singleton;
63 
64 import com.android.ims.ImsCall;
65 import com.android.ims.ImsEcbm;
66 import com.android.ims.ImsManager;
67 import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager;
68 import com.android.internal.telephony.cdma.EriManager;
69 import com.android.internal.telephony.dataconnection.DataEnabledOverride;
70 import com.android.internal.telephony.dataconnection.DataEnabledSettings;
71 import com.android.internal.telephony.dataconnection.DcTracker;
72 import com.android.internal.telephony.dataconnection.TransportManager;
73 import com.android.internal.telephony.emergency.EmergencyNumberTracker;
74 import com.android.internal.telephony.imsphone.ImsExternalCallTracker;
75 import com.android.internal.telephony.imsphone.ImsPhone;
76 import com.android.internal.telephony.imsphone.ImsPhoneCallTracker;
77 import com.android.internal.telephony.test.SimulatedCommands;
78 import com.android.internal.telephony.test.SimulatedCommandsVerifier;
79 import com.android.internal.telephony.uicc.IccCardStatus;
80 import com.android.internal.telephony.uicc.IccRecords;
81 import com.android.internal.telephony.uicc.IsimUiccRecords;
82 import com.android.internal.telephony.uicc.RuimRecords;
83 import com.android.internal.telephony.uicc.SIMRecords;
84 import com.android.internal.telephony.uicc.UiccCard;
85 import com.android.internal.telephony.uicc.UiccCardApplication;
86 import com.android.internal.telephony.uicc.UiccController;
87 import com.android.internal.telephony.uicc.UiccProfile;
88 
89 import org.mockito.Mock;
90 import org.mockito.MockitoAnnotations;
91 import org.mockito.invocation.InvocationOnMock;
92 import org.mockito.stubbing.Answer;
93 
94 import java.lang.reflect.Field;
95 import java.lang.reflect.InvocationTargetException;
96 import java.lang.reflect.Method;
97 import java.util.ArrayList;
98 import java.util.HashMap;
99 import java.util.HashSet;
100 import java.util.Iterator;
101 import java.util.LinkedList;
102 import java.util.Set;
103 import java.util.concurrent.CountDownLatch;
104 import java.util.concurrent.TimeUnit;
105 
106 public abstract class TelephonyTest {
107     protected static String TAG;
108 
109     private static final int MAX_INIT_WAIT_MS = 30000; // 30 seconds
110 
111     private static final EmergencyNumber SAMPLE_EMERGENCY_NUMBER =
112             new EmergencyNumber("911", "us", "30",
113                     EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_UNSPECIFIED,
114             new ArrayList<String>(), EmergencyNumber.EMERGENCY_NUMBER_SOURCE_NETWORK_SIGNALING,
115             EmergencyNumber.EMERGENCY_CALL_ROUTING_NORMAL);
116 
117     @Mock
118     protected GsmCdmaPhone mPhone;
119     @Mock
120     protected ImsPhone mImsPhone;
121     @Mock
122     protected ServiceStateTracker mSST;
123     @Mock
124     protected EmergencyNumberTracker mEmergencyNumberTracker;
125     @Mock
126     protected GsmCdmaCallTracker mCT;
127     @Mock
128     protected ImsPhoneCallTracker mImsCT;
129     @Mock
130     protected UiccController mUiccController;
131     @Mock
132     protected UiccProfile mUiccProfile;
133     @Mock
134     protected CallManager mCallManager;
135     @Mock
136     protected PhoneNotifier mNotifier;
137     @Mock
138     protected TelephonyComponentFactory mTelephonyComponentFactory;
139     @Mock
140     protected CdmaSubscriptionSourceManager mCdmaSSM;
141     @Mock
142     protected RegistrantList mRegistrantList;
143     @Mock
144     protected IccPhoneBookInterfaceManager mIccPhoneBookIntManager;
145     @Mock
146     protected ImsManager mImsManager;
147     @Mock
148     protected DcTracker mDcTracker;
149     @Mock
150     protected GsmCdmaCall mGsmCdmaCall;
151     @Mock
152     protected ImsCall mImsCall;
153     @Mock
154     protected ImsEcbm mImsEcbm;
155     @Mock
156     protected SubscriptionController mSubscriptionController;
157     @Mock
158     protected ServiceState mServiceState;
159 
160     protected NetworkRegistrationInfo mNetworkRegistrationInfo =
161             new NetworkRegistrationInfo.Builder()
162             .setAccessNetworkTechnology(TelephonyManager.NETWORK_TYPE_LTE)
163             .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
164             .build();
165     @Mock
166     protected SimulatedCommandsVerifier mSimulatedCommandsVerifier;
167     @Mock
168     protected IDeviceIdleController mIDeviceIdleController;
169     @Mock
170     protected InboundSmsHandler mInboundSmsHandler;
171     @Mock
172     protected WspTypeDecoder mWspTypeDecoder;
173     @Mock
174     protected UiccCardApplication mUiccCardApplication3gpp;
175     @Mock
176     protected UiccCardApplication mUiccCardApplication3gpp2;
177     @Mock
178     protected UiccCardApplication mUiccCardApplicationIms;
179     @Mock
180     protected SIMRecords mSimRecords;
181     @Mock
182     protected RuimRecords mRuimRecords;
183     @Mock
184     protected IsimUiccRecords mIsimUiccRecords;
185     @Mock
186     protected ProxyController mProxyController;
187     @Mock
188     protected Singleton<IActivityManager> mIActivityManagerSingleton;
189     @Mock
190     protected IActivityManager mIActivityManager;
191     @Mock
192     protected IIntentSender mIIntentSender;
193     @Mock
194     protected IBinder mIBinder;
195     @Mock
196     protected SmsStorageMonitor mSmsStorageMonitor;
197     @Mock
198     protected SmsUsageMonitor mSmsUsageMonitor;
199     @Mock
200     protected PackageInfo mPackageInfo;
201     @Mock
202     protected ApplicationInfo mApplicationInfo;
203     @Mock
204     protected EriManager mEriManager;
205     @Mock
206     protected IBinder mConnMetLoggerBinder;
207     @Mock
208     protected CarrierSignalAgent mCarrierSignalAgent;
209     @Mock
210     protected CarrierActionAgent mCarrierActionAgent;
211     @Mock
212     protected ImsExternalCallTracker mImsExternalCallTracker;
213     @Mock
214     protected AppSmsManager mAppSmsManager;
215     @Mock
216     protected IccSmsInterfaceManager mIccSmsInterfaceManager;
217     @Mock
218     protected SmsDispatchersController mSmsDispatchersController;
219     @Mock
220     protected DeviceStateMonitor mDeviceStateMonitor;
221     @Mock
222     protected TransportManager mTransportManager;
223     @Mock
224     protected IntentBroadcaster mIntentBroadcaster;
225     @Mock
226     protected NitzStateMachine mNitzStateMachine;
227     @Mock
228     protected RadioConfig mMockRadioConfig;
229     @Mock
230     protected SubscriptionInfoUpdater mSubInfoRecordUpdater;
231     @Mock
232     protected LocaleTracker mLocaleTracker;
233     @Mock
234     protected RestrictedState mRestrictedState;
235     @Mock
236     protected DataEnabledSettings mDataEnabledSettings;
237     @Mock
238     protected DataEnabledOverride mDataEnabledOverride;
239     @Mock
240     protected PhoneConfigurationManager mPhoneConfigurationManager;
241     @Mock
242     protected CellularNetworkValidator mCellularNetworkValidator;
243     @Mock
244     protected UiccCard mUiccCard;
245     @Mock
246     protected MultiSimSettingController mMultiSimSettingController;
247 
248     protected ImsCallProfile mImsCallProfile;
249     protected TelephonyManager mTelephonyManager;
250     protected SubscriptionManager mSubscriptionManager;
251     protected EuiccManager mEuiccManager;
252     protected PackageManager mPackageManager;
253     protected SimulatedCommands mSimulatedCommands;
254     protected ContextFixture mContextFixture;
255     protected Context mContext;
256     protected FakeBlockedNumberContentProvider mFakeBlockedNumberContentProvider;
257     private Object mLock = new Object();
258     private boolean mReady;
259     protected HashMap<String, IBinder> mServiceManagerMockedServices = new HashMap<>();
260     protected Phone[] mPhones;
261 
262 
263     protected HashMap<Integer, ImsManager> mImsManagerInstances = new HashMap<>();
264     private HashMap<InstanceKey, Object> mOldInstances = new HashMap<InstanceKey, Object>();
265 
266     private LinkedList<InstanceKey> mInstanceKeys = new LinkedList<InstanceKey>();
267 
268     private class InstanceKey {
269         public final Class mClass;
270         public final String mInstName;
271         public final Object mObj;
InstanceKey(final Class c, final String instName, final Object obj)272         InstanceKey(final Class c, final String instName, final Object obj) {
273             mClass = c;
274             mInstName = instName;
275             mObj = obj;
276         }
277 
278         @Override
hashCode()279         public int hashCode() {
280             return (mClass.getName().hashCode() * 31 + mInstName.hashCode()) * 31;
281         }
282 
283         @Override
equals(Object obj)284         public boolean equals(Object obj) {
285             if (obj == null || obj.getClass() != getClass()) {
286                 return false;
287             }
288 
289             InstanceKey other = (InstanceKey) obj;
290             return (other.mClass == mClass && other.mInstName.equals(mInstName)
291                     && other.mObj == mObj);
292         }
293     }
294 
waitUntilReady()295     protected void waitUntilReady() {
296         synchronized (mLock) {
297             if (!mReady) {
298                 try {
299                     mLock.wait(MAX_INIT_WAIT_MS);
300                 } catch (InterruptedException ie) {
301                 }
302 
303                 if (!mReady) {
304                     fail("Telephony tests failed to initialize");
305                 }
306             }
307         }
308     }
309 
setReady(boolean ready)310     protected void setReady(boolean ready) {
311         synchronized (mLock) {
312             mReady = ready;
313             mLock.notifyAll();
314         }
315     }
316 
replaceInstance(final Class c, final String instanceName, final Object obj, final Object newValue)317     protected synchronized void replaceInstance(final Class c, final String instanceName,
318                                                 final Object obj, final Object newValue)
319             throws Exception {
320         Field field = c.getDeclaredField(instanceName);
321         field.setAccessible(true);
322 
323         InstanceKey key = new InstanceKey(c, instanceName, obj);
324         if (!mOldInstances.containsKey(key)) {
325             mOldInstances.put(key, field.get(obj));
326             mInstanceKeys.add(key);
327         }
328         field.set(obj, newValue);
329     }
330 
restoreInstance(final Class c, final String instanceName, final Object obj)331     protected synchronized void restoreInstance(final Class c, final String instanceName,
332                                                 final Object obj) throws Exception {
333         InstanceKey key = new InstanceKey(c, instanceName, obj);
334         if (mOldInstances.containsKey(key)) {
335             Field field = c.getDeclaredField(instanceName);
336             field.setAccessible(true);
337             field.set(obj, mOldInstances.get(key));
338             mOldInstances.remove(key);
339             mInstanceKeys.remove(key);
340         }
341     }
342 
restoreInstances()343     protected synchronized void restoreInstances() throws Exception {
344         Iterator<InstanceKey> it = mInstanceKeys.descendingIterator();
345 
346         while (it.hasNext()) {
347             InstanceKey key = it.next();
348             Field field = key.mClass.getDeclaredField(key.mInstName);
349             field.setAccessible(true);
350             field.set(key.mObj, mOldInstances.get(key));
351         }
352 
353         mInstanceKeys.clear();
354         mOldInstances.clear();
355     }
356 
setUp(String tag)357     protected void setUp(String tag) throws Exception {
358         TAG = tag;
359         MockitoAnnotations.initMocks(this);
360 
361         mPhones = new Phone[] {mPhone};
362         mImsCallProfile = new ImsCallProfile();
363         mSimulatedCommands = new SimulatedCommands();
364         mContextFixture = new ContextFixture();
365         mContext = mContextFixture.getTestDouble();
366         mFakeBlockedNumberContentProvider = new FakeBlockedNumberContentProvider();
367         ((MockContentResolver)mContext.getContentResolver()).addProvider(
368                 BlockedNumberContract.AUTHORITY, mFakeBlockedNumberContentProvider);
369         mPhone.mCi = mSimulatedCommands;
370         mCT.mCi = mSimulatedCommands;
371         doReturn(mUiccCard).when(mPhone).getUiccCard();
372         doReturn(mUiccProfile).when(mUiccCard).getUiccProfile();
373 
374         mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
375         mSubscriptionManager = (SubscriptionManager) mContext.getSystemService(
376                 Context.TELEPHONY_SUBSCRIPTION_SERVICE);
377         mEuiccManager = (EuiccManager) mContext.getSystemService(Context.EUICC_SERVICE);
378         mPackageManager = mContext.getPackageManager();
379 
380         //mTelephonyComponentFactory
381         doReturn(mTelephonyComponentFactory).when(mTelephonyComponentFactory).inject(anyString());
382         doReturn(mSST).when(mTelephonyComponentFactory)
383                 .makeServiceStateTracker(nullable(GsmCdmaPhone.class),
384                         nullable(CommandsInterface.class));
385         doReturn(mEmergencyNumberTracker).when(mTelephonyComponentFactory)
386                 .makeEmergencyNumberTracker(nullable(Phone.class),
387                         nullable(CommandsInterface.class));
388         doReturn(getTestEmergencyNumber()).when(mEmergencyNumberTracker)
389                 .getEmergencyNumber(any());
390         doReturn(mUiccProfile).when(mTelephonyComponentFactory)
391                 .makeUiccProfile(nullable(Context.class), nullable(CommandsInterface.class),
392                         nullable(IccCardStatus.class), anyInt(), nullable(UiccCard.class),
393                         nullable(Object.class));
394         doReturn(mCT).when(mTelephonyComponentFactory)
395                 .makeGsmCdmaCallTracker(nullable(GsmCdmaPhone.class));
396         doReturn(mIccPhoneBookIntManager).when(mTelephonyComponentFactory)
397                 .makeIccPhoneBookInterfaceManager(nullable(Phone.class));
398         doReturn(mDcTracker).when(mTelephonyComponentFactory)
399                 .makeDcTracker(nullable(Phone.class), anyInt());
400         doReturn(mWspTypeDecoder).when(mTelephonyComponentFactory)
401                 .makeWspTypeDecoder(nullable(byte[].class));
402         doReturn(mImsCT).when(mTelephonyComponentFactory)
403                 .makeImsPhoneCallTracker(nullable(ImsPhone.class));
404         doReturn(mCdmaSSM).when(mTelephonyComponentFactory)
405                 .getCdmaSubscriptionSourceManagerInstance(nullable(Context.class),
406                         nullable(CommandsInterface.class), nullable(Handler.class),
407                         anyInt(), nullable(Object.class));
408         doReturn(mIDeviceIdleController).when(mTelephonyComponentFactory)
409                 .getIDeviceIdleController();
410         doReturn(mImsExternalCallTracker).when(mTelephonyComponentFactory)
411                 .makeImsExternalCallTracker(nullable(ImsPhone.class));
412         doReturn(mAppSmsManager).when(mTelephonyComponentFactory)
413                 .makeAppSmsManager(nullable(Context.class));
414         doReturn(mCarrierSignalAgent).when(mTelephonyComponentFactory)
415                 .makeCarrierSignalAgent(nullable(Phone.class));
416         doReturn(mCarrierActionAgent).when(mTelephonyComponentFactory)
417                 .makeCarrierActionAgent(nullable(Phone.class));
418         doReturn(mDeviceStateMonitor).when(mTelephonyComponentFactory)
419                 .makeDeviceStateMonitor(nullable(Phone.class));
420         doReturn(mTransportManager).when(mTelephonyComponentFactory)
421                 .makeTransportManager(nullable(Phone.class));
422         doReturn(mNitzStateMachine).when(mTelephonyComponentFactory)
423                 .makeNitzStateMachine(nullable(GsmCdmaPhone.class));
424         doReturn(mLocaleTracker).when(mTelephonyComponentFactory)
425                 .makeLocaleTracker(nullable(Phone.class), nullable(NitzStateMachine.class),
426                         nullable(Looper.class));
427         doReturn(mDataEnabledSettings).when(mTelephonyComponentFactory)
428                 .makeDataEnabledSettings(nullable(Phone.class));
429         doReturn(mEriManager).when(mTelephonyComponentFactory)
430                 .makeEriManager(nullable(Phone.class), anyInt());
431 
432         //mPhone
433         doReturn(mContext).when(mPhone).getContext();
434         doReturn(mContext).when(mImsPhone).getContext();
435         doReturn(true).when(mPhone).getUnitTestMode();
436         doReturn(mUiccProfile).when(mPhone).getIccCard();
437         doReturn(mServiceState).when(mPhone).getServiceState();
438         doReturn(mServiceState).when(mImsPhone).getServiceState();
439         doReturn(mPhone).when(mImsPhone).getDefaultPhone();
440         doReturn(true).when(mPhone).isPhoneTypeGsm();
441         doReturn(PhoneConstants.PHONE_TYPE_GSM).when(mPhone).getPhoneType();
442         doReturn(mCT).when(mPhone).getCallTracker();
443         doReturn(mSST).when(mPhone).getServiceStateTracker();
444         doReturn(mEmergencyNumberTracker).when(mPhone).getEmergencyNumberTracker();
445         doReturn(mCarrierSignalAgent).when(mPhone).getCarrierSignalAgent();
446         doReturn(mCarrierActionAgent).when(mPhone).getCarrierActionAgent();
447         doReturn(mAppSmsManager).when(mPhone).getAppSmsManager();
448         doReturn(mIccSmsInterfaceManager).when(mPhone).getIccSmsInterfaceManager();
449         doReturn(mTransportManager).when(mPhone).getTransportManager();
450         doReturn(mDataEnabledSettings).when(mPhone).getDataEnabledSettings();
451         doReturn(mDcTracker).when(mPhone).getDcTracker(anyInt());
452         mIccSmsInterfaceManager.mDispatchersController = mSmsDispatchersController;
453 
454         //mUiccController
455         doReturn(mUiccCardApplication3gpp).when(mUiccController).getUiccCardApplication(anyInt(),
456                 eq(UiccController.APP_FAM_3GPP));
457         doReturn(mUiccCardApplication3gpp2).when(mUiccController).getUiccCardApplication(anyInt(),
458                 eq(UiccController.APP_FAM_3GPP2));
459         doReturn(mUiccCardApplicationIms).when(mUiccController).getUiccCardApplication(anyInt(),
460                 eq(UiccController.APP_FAM_IMS));
461 
462         doAnswer(new Answer<IccRecords>() {
463             public IccRecords answer(InvocationOnMock invocation) {
464                 switch ((Integer) invocation.getArguments()[1]) {
465                     case UiccController.APP_FAM_3GPP:
466                         return mSimRecords;
467                     case UiccController.APP_FAM_3GPP2:
468                         return mRuimRecords;
469                     case UiccController.APP_FAM_IMS:
470                         return mIsimUiccRecords;
471                     default:
472                         logd("Unrecognized family " + invocation.getArguments()[1]);
473                         return null;
474                 }
475             }
476         }).when(mUiccController).getIccRecords(anyInt(), anyInt());
477 
478         //UiccCardApplication
479         doReturn(mSimRecords).when(mUiccCardApplication3gpp).getIccRecords();
480         doReturn(mRuimRecords).when(mUiccCardApplication3gpp2).getIccRecords();
481         doReturn(mIsimUiccRecords).when(mUiccCardApplicationIms).getIccRecords();
482 
483         //mUiccProfile
484         doReturn(mSimRecords).when(mUiccProfile).getIccRecords();
485         doAnswer(new Answer<IccRecords>() {
486             public IccRecords answer(InvocationOnMock invocation) {
487                 return (mPhone.isPhoneTypeGsm()) ? mSimRecords : mRuimRecords;
488             }
489         }).when(mUiccProfile).getIccRecords();
490 
491         //mUiccProfile
492         doReturn(mUiccCardApplication3gpp).when(mUiccProfile).getApplication(
493                 eq(UiccController.APP_FAM_3GPP));
494         doReturn(mUiccCardApplication3gpp2).when(mUiccProfile).getApplication(
495                 eq(UiccController.APP_FAM_3GPP2));
496         doReturn(mUiccCardApplicationIms).when(mUiccProfile).getApplication(
497                 eq(UiccController.APP_FAM_IMS));
498 
499         //SMS
500         doReturn(true).when(mSmsStorageMonitor).isStorageAvailable();
501         doReturn(true).when(mSmsUsageMonitor).check(nullable(String.class), anyInt());
502         doReturn(true).when(mTelephonyManager).getSmsReceiveCapableForPhone(anyInt(), anyBoolean());
503         doReturn(true).when(mTelephonyManager).getSmsSendCapableForPhone(
504                 anyInt(), anyBoolean());
505 
506         //Misc
507         doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_UMTS).when(mServiceState).
508                 getRilDataRadioTechnology();
509         doReturn(mPhone).when(mCT).getPhone();
510         mImsManagerInstances.put(mPhone.getPhoneId(), mImsManager);
511         doReturn(mImsEcbm).when(mImsManager).getEcbmInterface();
512         doReturn(mPhone).when(mInboundSmsHandler).getPhone();
513         doReturn(mImsCallProfile).when(mImsCall).getCallProfile();
514         doReturn(mIBinder).when(mIIntentSender).asBinder();
515         doReturn(mIIntentSender).when(mIActivityManager).getIntentSender(anyInt(),
516                 nullable(String.class), nullable(IBinder.class), nullable(String.class), anyInt(),
517                 nullable(Intent[].class), nullable(String[].class), anyInt(),
518                 nullable(Bundle.class), anyInt());
519         doReturn(mTelephonyManager).when(mTelephonyManager).createForSubscriptionId(anyInt());
520         doReturn(mServiceState).when(mSST).getServiceState();
521         mSST.mSS = mServiceState;
522         mSST.mRestrictedState = mRestrictedState;
523         mServiceManagerMockedServices.put("connectivity_metrics_logger", mConnMetLoggerBinder);
524         doReturn(new int[]{AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
525                 AccessNetworkConstants.TRANSPORT_TYPE_WLAN})
526                 .when(mTransportManager).getAvailableTransports();
527         doReturn(AccessNetworkConstants.TRANSPORT_TYPE_WWAN).when(mTransportManager)
528                 .getCurrentTransport(anyInt());
529         doReturn(true).when(mDataEnabledSettings).isDataEnabled();
530         doReturn(true).when(mDataEnabledSettings).isDataEnabled(anyInt());
531         doReturn(true).when(mDataEnabledSettings).isInternalDataEnabled();
532         doReturn(mNetworkRegistrationInfo).when(mServiceState).getNetworkRegistrationInfo(
533                 anyInt(), anyInt());
534         doReturn(new HalVersion(1, 4)).when(mPhone).getHalVersion();
535 
536         //SIM
537         doReturn(1).when(mTelephonyManager).getSimCount();
538         doReturn(1).when(mTelephonyManager).getPhoneCount();
539 
540         //Data
541         //Initial state is: userData enabled, provisioned.
542         ContentResolver resolver = mContext.getContentResolver();
543         Settings.Global.putInt(resolver, Settings.Global.MOBILE_DATA, 1);
544         Settings.Global.putInt(resolver, Settings.Global.DEVICE_PROVISIONED, 1);
545         Settings.Global.putInt(resolver,
546                 Settings.Global.DEVICE_PROVISIONING_MOBILE_DATA_ENABLED, 1);
547 
548         // CellularNetworkValidator
549         doReturn(SubscriptionManager.INVALID_PHONE_INDEX)
550                 .when(mCellularNetworkValidator).getSubIdInValidation();
551         doReturn(true).when(mCellularNetworkValidator).isValidationFeatureSupported();
552 
553         //Use reflection to mock singletons
554         replaceInstance(CallManager.class, "INSTANCE", null, mCallManager);
555         replaceInstance(TelephonyComponentFactory.class, "sInstance", null,
556                 mTelephonyComponentFactory);
557         replaceInstance(UiccController.class, "mInstance", null, mUiccController);
558         replaceInstance(CdmaSubscriptionSourceManager.class, "sInstance", null, mCdmaSSM);
559         replaceInstance(ImsManager.class, "sImsManagerInstances", null, mImsManagerInstances);
560         replaceInstance(SubscriptionController.class, "sInstance", null, mSubscriptionController);
561         replaceInstance(ProxyController.class, "sProxyController", null, mProxyController);
562         replaceInstance(ActivityManager.class, "IActivityManagerSingleton", null,
563                 mIActivityManagerSingleton);
564         replaceInstance(CdmaSubscriptionSourceManager.class,
565                 "mCdmaSubscriptionSourceChangedRegistrants", mCdmaSSM, mRegistrantList);
566         replaceInstance(SimulatedCommandsVerifier.class, "sInstance", null,
567                 mSimulatedCommandsVerifier);
568         replaceInstance(Singleton.class, "mInstance", mIActivityManagerSingleton,
569                 mIActivityManager);
570         replaceInstance(ServiceManager.class, "sCache", null, mServiceManagerMockedServices);
571         replaceInstance(IntentBroadcaster.class, "sIntentBroadcaster", null, mIntentBroadcaster);
572         replaceInstance(TelephonyManager.class, "sInstance", null,
573                 mContext.getSystemService(Context.TELEPHONY_SERVICE));
574         replaceInstance(PhoneFactory.class, "sMadeDefaults", null, true);
575         replaceInstance(PhoneFactory.class, "sPhone", null, mPhone);
576         replaceInstance(PhoneFactory.class, "sPhones", null, mPhones);
577         replaceInstance(PhoneFactory.class, "sSubInfoRecordUpdater", null, mSubInfoRecordUpdater);
578         replaceInstance(RadioConfig.class, "sRadioConfig", null, mMockRadioConfig);
579         replaceInstance(PhoneConfigurationManager.class, "sInstance", null,
580                 mPhoneConfigurationManager);
581         replaceInstance(CellularNetworkValidator.class, "sInstance", null,
582                 mCellularNetworkValidator);
583         replaceInstance(MultiSimSettingController.class, "sInstance", null,
584                 mMultiSimSettingController);
585         replaceInstance(SubscriptionInfoUpdater.class, "sIsSubInfoInitialized", null, true);
586 
587         assertNotNull("Failed to set up SubscriptionController singleton",
588                 SubscriptionController.getInstance());
589         setReady(false);
590     }
591 
tearDown()592     protected void tearDown() throws Exception {
593 
594         mSimulatedCommands.dispose();
595 
596         SharedPreferences sharedPreferences = mContext.getSharedPreferences((String) null, 0);
597         sharedPreferences.edit().clear().commit();
598 
599         restoreInstances();
600     }
601 
logd(String s)602     protected static void logd(String s) {
603         Log.d(TAG, s);
604     }
605 
606     public static class FakeBlockedNumberContentProvider extends MockContentProvider {
607         public Set<String> mBlockedNumbers = new HashSet<>();
608         public int mNumEmergencyContactNotifications = 0;
609 
610         @Override
call(String method, String arg, Bundle extras)611         public Bundle call(String method, String arg, Bundle extras) {
612             switch (method) {
613                 case BlockedNumberContract.SystemContract.METHOD_SHOULD_SYSTEM_BLOCK_NUMBER:
614                     Bundle bundle = new Bundle();
615                     int blockStatus = mBlockedNumbers.contains(arg)
616                             ? BlockedNumberContract.STATUS_BLOCKED_IN_LIST
617                             : BlockedNumberContract.STATUS_NOT_BLOCKED;
618                     bundle.putInt(BlockedNumberContract.RES_BLOCK_STATUS, blockStatus);
619                     return bundle;
620                 case BlockedNumberContract.SystemContract.METHOD_NOTIFY_EMERGENCY_CONTACT:
621                     mNumEmergencyContactNotifications++;
622                     return new Bundle();
623                 default:
624                     fail("Method not expected: " + method);
625             }
626             return null;
627         }
628     }
629 
630     public static class FakeSettingsConfigProvider extends MockContentProvider {
631         private static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED =
632                 DeviceConfig.NAMESPACE_PRIVACY + "/"
633                         + "device_identifier_access_restrictions_disabled";
634 
635         @Override
call(String method, String arg, Bundle extras)636         public Bundle call(String method, String arg, Bundle extras) {
637             switch (method) {
638                 case Settings.CALL_METHOD_GET_CONFIG: {
639                     switch (arg) {
640                         case PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED: {
641                             Bundle bundle = new Bundle();
642                             bundle.putString(
643                                     PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED,
644                                     "0");
645                             return bundle;
646                         }
647                         default: {
648                             fail("arg not expected: " + arg);
649                         }
650                     }
651                     break;
652                 }
653                 default:
654                     fail("Method not expected: " + method);
655             }
656             return null;
657         }
658     }
659 
setupMockPackagePermissionChecks()660     protected void setupMockPackagePermissionChecks() throws Exception {
661         doReturn(new String[]{TAG}).when(mPackageManager).getPackagesForUid(anyInt());
662         doReturn(mPackageInfo).when(mPackageManager).getPackageInfo(eq(TAG), anyInt());
663         doReturn(mPackageInfo).when(mPackageManager).getPackageInfoAsUser(
664                 eq(TAG), anyInt(), anyInt());
665     }
666 
setupMocksForTelephonyPermissions()667     protected void setupMocksForTelephonyPermissions() throws Exception {
668         // If the calling package does not meet the new requirements for device identifier access
669         // TelephonyPermissions will query the PackageManager for the ApplicationInfo of the package
670         // to determine the target SDK. For apps targeting Q a SecurityException is thrown
671         // regardless of if the package satisfies the previous requirements for device ID access.
672         mApplicationInfo.targetSdkVersion = Build.VERSION_CODES.Q;
673         doReturn(mApplicationInfo).when(mPackageManager).getApplicationInfoAsUser(eq(TAG), anyInt(),
674                 anyInt());
675 
676         // TelephonyPermissions queries DeviceConfig to determine if the identifier access
677         // restrictions should be enabled; this results in a NPE when DeviceConfig uses
678         // Activity.currentActivity.getContentResolver as the resolver for Settings.Config.getString
679         // since the IContentProvider in the NameValueCache's provider holder is null.
680         Class c = Class.forName("android.provider.Settings$Config");
681         Field field = c.getDeclaredField("sNameValueCache");
682         field.setAccessible(true);
683         Object cache = field.get(null);
684 
685         c = Class.forName("android.provider.Settings$NameValueCache");
686         field = c.getDeclaredField("mProviderHolder");
687         field.setAccessible(true);
688         Object providerHolder = field.get(cache);
689 
690         FakeSettingsConfigProvider fakeSettingsProvider = new FakeSettingsConfigProvider();
691         field = MockContentProvider.class.getDeclaredField("mIContentProvider");
692         field.setAccessible(true);
693         Object iContentProvider = field.get(fakeSettingsProvider);
694 
695         replaceInstance(Class.forName("android.provider.Settings$ContentProviderHolder"),
696                 "mContentProvider", providerHolder, iContentProvider);
697     }
698 
waitForHandlerAction(Handler h, long timeoutMillis)699     protected final void waitForHandlerAction(Handler h, long timeoutMillis) {
700         final CountDownLatch lock = new CountDownLatch(1);
701         h.post(lock::countDown);
702         while (lock.getCount() > 0) {
703             try {
704                 lock.await(timeoutMillis, TimeUnit.MILLISECONDS);
705             } catch (InterruptedException e) {
706                 // do nothing
707             }
708         }
709     }
710 
waitForHandlerActionDelayed(Handler h, long timeoutMillis, long delayMs)711     protected final void waitForHandlerActionDelayed(Handler h, long timeoutMillis, long delayMs) {
712         final CountDownLatch lock = new CountDownLatch(1);
713         h.postDelayed(lock::countDown, delayMs);
714         while (lock.getCount() > 0) {
715             try {
716                 lock.await(timeoutMillis, TimeUnit.MILLISECONDS);
717             } catch (InterruptedException e) {
718                 // do nothing
719             }
720         }
721     }
722 
getTestEmergencyNumber()723     protected final EmergencyNumber getTestEmergencyNumber() {
724         return SAMPLE_EMERGENCY_NUMBER;
725     }
726 
invokeMethod( Object instance, String methodName, Class<?>[] parameterClasses, Object[] parameters)727     public static Object invokeMethod(
728             Object instance, String methodName, Class<?>[] parameterClasses, Object[] parameters) {
729         try {
730             Method method = instance.getClass().getDeclaredMethod(methodName, parameterClasses);
731             method.setAccessible(true);
732             return method.invoke(instance, parameters);
733         } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
734             fail(instance.getClass() + " " + methodName + " " + e.getClass().getName());
735         }
736         return null;
737     }
738 }
739