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