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