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