ed5ca438125cab05f0888a19225d96e8388c470e
[android/platform/frameworks/opt/telephony.git] / tests / telephonytests / src / com / android / internal / telephony / TelephonyTest.java
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.fail;
20 import static org.mockito.Matchers.anyBoolean;
21 import static org.mockito.Matchers.anyLong;
22 import static org.mockito.Matchers.nullable;
23 import static org.mockito.Mockito.anyInt;
24 import static org.mockito.Mockito.doAnswer;
25 import static org.mockito.Mockito.doReturn;
26 import static org.mockito.Mockito.eq;
27
28 import android.app.ActivityManager;
29 import android.app.IActivityManager;
30 import android.content.Context;
31 import android.content.IIntentSender;
32 import android.content.Intent;
33 import android.content.SharedPreferences;
34 import android.content.pm.PackageInfo;
35 import android.content.pm.PackageManager;
36 import android.database.Cursor;
37 import android.os.Bundle;
38 import android.os.Handler;
39 import android.os.IBinder;
40 import android.os.IDeviceIdleController;
41 import android.os.RegistrantList;
42 import android.os.ServiceManager;
43 import android.provider.BlockedNumberContract;
44 import android.provider.Settings;
45 import android.telephony.ServiceState;
46 import android.telephony.SubscriptionManager;
47 import android.telephony.TelephonyManager;
48 import android.test.mock.MockContentProvider;
49 import android.test.mock.MockContentResolver;
50 import android.util.Log;
51 import android.util.Singleton;
52
53 import com.android.ims.ImsCall;
54 import com.android.ims.ImsCallProfile;
55 import com.android.ims.ImsEcbm;
56 import com.android.ims.ImsManager;
57 import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager;
58 import com.android.internal.telephony.cdma.EriManager;
59 import com.android.internal.telephony.dataconnection.DcTracker;
60 import com.android.internal.telephony.imsphone.ImsExternalCallTracker;
61 import com.android.internal.telephony.imsphone.ImsPhone;
62 import com.android.internal.telephony.imsphone.ImsPhoneCallTracker;
63 import com.android.internal.telephony.test.SimulatedCommands;
64 import com.android.internal.telephony.test.SimulatedCommandsVerifier;
65 import com.android.internal.telephony.uicc.IccCardProxy;
66 import com.android.internal.telephony.uicc.IccRecords;
67 import com.android.internal.telephony.uicc.IsimUiccRecords;
68 import com.android.internal.telephony.uicc.RuimRecords;
69 import com.android.internal.telephony.uicc.SIMRecords;
70 import com.android.internal.telephony.uicc.UiccCardApplication;
71 import com.android.internal.telephony.uicc.UiccController;
72
73 import org.mockito.Mock;
74 import org.mockito.MockitoAnnotations;
75 import org.mockito.invocation.InvocationOnMock;
76 import org.mockito.stubbing.Answer;
77
78 import java.lang.reflect.Field;
79 import java.util.HashMap;
80 import java.util.HashSet;
81 import java.util.Iterator;
82 import java.util.LinkedList;
83 import java.util.Set;
84 import java.util.concurrent.CountDownLatch;
85 import java.util.concurrent.TimeUnit;
86
87 public abstract class TelephonyTest {
88     protected static String TAG;
89
90     @Mock
91     protected GsmCdmaPhone mPhone;
92     @Mock
93     protected ImsPhone mImsPhone;
94     @Mock
95     protected ServiceStateTracker mSST;
96     @Mock
97     protected GsmCdmaCallTracker mCT;
98     @Mock
99     protected ImsPhoneCallTracker mImsCT;
100     @Mock
101     protected UiccController mUiccController;
102     @Mock
103     protected IccCardProxy mIccCardProxy;
104     @Mock
105     protected CallManager mCallManager;
106     @Mock
107     protected PhoneNotifier mNotifier;
108     @Mock
109     protected TelephonyComponentFactory mTelephonyComponentFactory;
110     @Mock
111     protected CdmaSubscriptionSourceManager mCdmaSSM;
112     @Mock
113     protected RegistrantList mRegistrantList;
114     @Mock
115     protected IccPhoneBookInterfaceManager mIccPhoneBookIntManager;
116     @Mock
117     protected ImsManager mImsManager;
118     @Mock
119     protected DcTracker mDcTracker;
120     @Mock
121     protected GsmCdmaCall mGsmCdmaCall;
122     @Mock
123     protected ImsCall mImsCall;
124     @Mock
125     protected ImsCallProfile mImsCallProfile;
126     @Mock
127     protected ImsEcbm mImsEcbm;
128     @Mock
129     protected SubscriptionController mSubscriptionController;
130     @Mock
131     protected ServiceState mServiceState;
132     @Mock
133     protected SimulatedCommandsVerifier mSimulatedCommandsVerifier;
134     @Mock
135     protected IDeviceIdleController mIDeviceIdleController;
136     @Mock
137     protected InboundSmsHandler mInboundSmsHandler;
138     @Mock
139     protected WspTypeDecoder mWspTypeDecoder;
140     @Mock
141     protected UiccCardApplication mUiccCardApplication3gpp;
142     @Mock
143     protected UiccCardApplication mUiccCardApplication3gpp2;
144     @Mock
145     protected UiccCardApplication mUiccCardApplicationIms;
146     @Mock
147     protected SIMRecords mSimRecords;
148     @Mock
149     protected RuimRecords mRuimRecords;
150     @Mock
151     protected IsimUiccRecords mIsimUiccRecords;
152     @Mock
153     protected ProxyController mProxyController;
154     @Mock
155     protected Singleton<IActivityManager> mIActivityManagerSingleton;
156     @Mock
157     protected IActivityManager mIActivityManager;
158     @Mock
159     protected InboundSmsTracker mInboundSmsTracker;
160     @Mock
161     protected IIntentSender mIIntentSender;
162     @Mock
163     protected IBinder mIBinder;
164     @Mock
165     protected SmsStorageMonitor mSmsStorageMonitor;
166     @Mock
167     protected SmsUsageMonitor mSmsUsageMonitor;
168     @Mock
169     protected PackageInfo mPackageInfo;
170     @Mock
171     protected EriManager mEriManager;
172     @Mock
173     protected IBinder mConnMetLoggerBinder;
174     @Mock
175     protected CarrierSignalAgent mCarrierSignalAgent;
176     @Mock
177     protected CarrierActionAgent mCarrierActionAgent;
178     @Mock
179     protected ImsExternalCallTracker mImsExternalCallTracker;
180     @Mock
181     protected AppSmsManager mAppSmsManager;
182     @Mock
183     protected DeviceStateMonitor mDeviceStateMonitor;
184
185     protected TelephonyManager mTelephonyManager;
186     protected SubscriptionManager mSubscriptionManager;
187     protected PackageManager mPackageManager;
188     protected SimulatedCommands mSimulatedCommands;
189     protected ContextFixture mContextFixture;
190     protected Context mContext;
191     protected FakeBlockedNumberContentProvider mFakeBlockedNumberContentProvider;
192     private Object mLock = new Object();
193     private boolean mReady;
194     protected HashMap<String, IBinder> mServiceManagerMockedServices = new HashMap<>();
195
196
197     protected HashMap<Integer, ImsManager> mImsManagerInstances = new HashMap<>();
198     private HashMap<InstanceKey, Object> mOldInstances = new HashMap<InstanceKey, Object>();
199
200     private LinkedList<InstanceKey> mInstanceKeys = new LinkedList<InstanceKey>();
201
202     private class InstanceKey {
203         public final Class mClass;
204         public final String mInstName;
205         public final Object mObj;
206         InstanceKey(final Class c, final String instName, final Object obj) {
207             mClass = c;
208             mInstName = instName;
209             mObj = obj;
210         }
211
212         @Override
213         public int hashCode() {
214             return (mClass.getName().hashCode() * 31 + mInstName.hashCode()) * 31;
215         }
216
217         @Override
218         public boolean equals(Object obj) {
219             if (obj == null || obj.getClass() != getClass()) {
220                 return false;
221             }
222
223             InstanceKey other = (InstanceKey) obj;
224             return (other.mClass == mClass && other.mInstName.equals(mInstName)
225                     && other.mObj == mObj);
226         }
227     }
228
229     protected void waitUntilReady() {
230         while (true) {
231             synchronized (mLock) {
232                 if (mReady) {
233                     break;
234                 }
235             }
236         }
237     }
238
239     protected void setReady(boolean ready) {
240         synchronized (mLock) {
241             mReady = ready;
242         }
243     }
244
245     protected synchronized void replaceInstance(final Class c, final String instanceName,
246                                                 final Object obj, final Object newValue)
247             throws Exception {
248         Field field = c.getDeclaredField(instanceName);
249         field.setAccessible(true);
250
251         InstanceKey key = new InstanceKey(c, instanceName, obj);
252         if (!mOldInstances.containsKey(key)) {
253             mOldInstances.put(key, field.get(obj));
254             mInstanceKeys.add(key);
255         }
256         field.set(obj, newValue);
257     }
258
259     protected synchronized void restoreInstance(final Class c, final String instanceName,
260                                                 final Object obj) throws Exception {
261         InstanceKey key = new InstanceKey(c, instanceName, obj);
262         if (mOldInstances.containsKey(key)) {
263             Field field = c.getDeclaredField(instanceName);
264             field.setAccessible(true);
265             field.set(obj, mOldInstances.get(key));
266             mOldInstances.remove(key);
267             mInstanceKeys.remove(key);
268         }
269     }
270
271     protected synchronized void restoreInstances() throws Exception {
272         Iterator<InstanceKey> it = mInstanceKeys.descendingIterator();
273
274         while (it.hasNext()) {
275             InstanceKey key = it.next();
276             Field field = key.mClass.getDeclaredField(key.mInstName);
277             field.setAccessible(true);
278             field.set(key.mObj, mOldInstances.get(key));
279         }
280
281         mInstanceKeys.clear();
282         mOldInstances.clear();
283     }
284
285     protected void setUp(String tag) throws Exception {
286         TAG = tag;
287         MockitoAnnotations.initMocks(this);
288
289         //Use reflection to mock singletons
290         replaceInstance(CallManager.class, "INSTANCE", null, mCallManager);
291         replaceInstance(TelephonyComponentFactory.class, "sInstance", null,
292                 mTelephonyComponentFactory);
293         replaceInstance(UiccController.class, "mInstance", null, mUiccController);
294         replaceInstance(CdmaSubscriptionSourceManager.class, "sInstance", null, mCdmaSSM);
295         replaceInstance(ImsManager.class, "sImsManagerInstances", null, mImsManagerInstances);
296         replaceInstance(SubscriptionController.class, "sInstance", null, mSubscriptionController);
297         replaceInstance(ProxyController.class, "sProxyController", null, mProxyController);
298         replaceInstance(ActivityManager.class, "IActivityManagerSingleton", null,
299                 mIActivityManagerSingleton);
300         replaceInstance(CdmaSubscriptionSourceManager.class,
301                 "mCdmaSubscriptionSourceChangedRegistrants", mCdmaSSM, mRegistrantList);
302         replaceInstance(SimulatedCommandsVerifier.class, "sInstance", null,
303                 mSimulatedCommandsVerifier);
304         replaceInstance(Singleton.class, "mInstance", mIActivityManagerSingleton,
305                 mIActivityManager);
306         replaceInstance(ServiceManager.class, "sCache", null, mServiceManagerMockedServices);
307
308         mSimulatedCommands = new SimulatedCommands();
309         mContextFixture = new ContextFixture();
310         mContext = mContextFixture.getTestDouble();
311         mFakeBlockedNumberContentProvider = new FakeBlockedNumberContentProvider();
312         ((MockContentResolver)mContext.getContentResolver()).addProvider(
313                 BlockedNumberContract.AUTHORITY, mFakeBlockedNumberContentProvider);
314         mPhone.mCi = mSimulatedCommands;
315         mCT.mCi = mSimulatedCommands;
316         mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
317         mSubscriptionManager = (SubscriptionManager) mContext.getSystemService(
318                 Context.TELEPHONY_SUBSCRIPTION_SERVICE);
319         mPackageManager = mContext.getPackageManager();
320
321         replaceInstance(TelephonyManager.class, "sInstance", null,
322                 mContext.getSystemService(Context.TELEPHONY_SERVICE));
323
324         //mTelephonyComponentFactory
325         doReturn(mSST).when(mTelephonyComponentFactory)
326                 .makeServiceStateTracker(nullable(GsmCdmaPhone.class),
327                         nullable(CommandsInterface.class));
328         doReturn(mIccCardProxy).when(mTelephonyComponentFactory)
329                 .makeIccCardProxy(nullable(Context.class), nullable(CommandsInterface.class),
330                         anyInt());
331         doReturn(mCT).when(mTelephonyComponentFactory)
332                 .makeGsmCdmaCallTracker(nullable(GsmCdmaPhone.class));
333         doReturn(mIccPhoneBookIntManager).when(mTelephonyComponentFactory)
334                 .makeIccPhoneBookInterfaceManager(nullable(Phone.class));
335         doReturn(mDcTracker).when(mTelephonyComponentFactory)
336                 .makeDcTracker(nullable(Phone.class));
337         doReturn(mWspTypeDecoder).when(mTelephonyComponentFactory)
338                 .makeWspTypeDecoder(nullable(byte[].class));
339         doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
340                 .makeInboundSmsTracker(nullable(byte[].class), anyLong(), anyInt(), anyBoolean(),
341                         anyBoolean(), nullable(String.class), nullable(String.class),
342                         nullable(String.class));
343         doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
344                 .makeInboundSmsTracker(nullable(byte[].class), anyLong(), anyInt(), anyBoolean(),
345                         nullable(String.class), nullable(String.class), anyInt(), anyInt(),
346                         anyInt(), anyBoolean(), nullable(String.class));
347         doReturn(mInboundSmsTracker).when(mTelephonyComponentFactory)
348                 .makeInboundSmsTracker(nullable(Cursor.class), anyBoolean());
349         doReturn(mImsCT).when(mTelephonyComponentFactory)
350                 .makeImsPhoneCallTracker(nullable(ImsPhone.class));
351         doReturn(mCdmaSSM).when(mTelephonyComponentFactory)
352                 .getCdmaSubscriptionSourceManagerInstance(nullable(Context.class),
353                         nullable(CommandsInterface.class), nullable(Handler.class),
354                         anyInt(), nullable(Object.class));
355         doReturn(mIDeviceIdleController).when(mTelephonyComponentFactory)
356                 .getIDeviceIdleController();
357         doReturn(mImsExternalCallTracker).when(mTelephonyComponentFactory)
358                 .makeImsExternalCallTracker(nullable(ImsPhone.class));
359         doReturn(mAppSmsManager).when(mTelephonyComponentFactory)
360                 .makeAppSmsManager(nullable(Context.class));
361         doReturn(mCarrierSignalAgent).when(mTelephonyComponentFactory)
362                 .makeCarrierSignalAgent(nullable(Phone.class));
363         doReturn(mCarrierActionAgent).when(mTelephonyComponentFactory)
364                 .makeCarrierActionAgent(nullable(Phone.class));
365         doReturn(mDeviceStateMonitor).when(mTelephonyComponentFactory)
366                 .makeDeviceStateMonitor(nullable(Phone.class));
367
368         //mPhone
369         doReturn(mContext).when(mPhone).getContext();
370         doReturn(mContext).when(mImsPhone).getContext();
371         doReturn(true).when(mPhone).getUnitTestMode();
372         doReturn(mIccCardProxy).when(mPhone).getIccCard();
373         doReturn(mServiceState).when(mPhone).getServiceState();
374         doReturn(mServiceState).when(mImsPhone).getServiceState();
375         doReturn(mPhone).when(mImsPhone).getDefaultPhone();
376         doReturn(true).when(mPhone).isPhoneTypeGsm();
377         doReturn(PhoneConstants.PHONE_TYPE_GSM).when(mPhone).getPhoneType();
378         doReturn(mCT).when(mPhone).getCallTracker();
379         doReturn(mSST).when(mPhone).getServiceStateTracker();
380         doReturn(mCarrierSignalAgent).when(mPhone).getCarrierSignalAgent();
381         doReturn(mCarrierActionAgent).when(mPhone).getCarrierActionAgent();
382         doReturn(mAppSmsManager).when(mPhone).getAppSmsManager();
383         mPhone.mEriManager = mEriManager;
384
385         //mUiccController
386         doReturn(mUiccCardApplication3gpp).when(mUiccController).getUiccCardApplication(anyInt(),
387                 eq(UiccController.APP_FAM_3GPP));
388         doReturn(mUiccCardApplication3gpp2).when(mUiccController).getUiccCardApplication(anyInt(),
389                 eq(UiccController.APP_FAM_3GPP2));
390         doReturn(mUiccCardApplicationIms).when(mUiccController).getUiccCardApplication(anyInt(),
391                 eq(UiccController.APP_FAM_IMS));
392
393         doAnswer(new Answer<IccRecords>() {
394             public IccRecords answer(InvocationOnMock invocation) {
395                 switch ((Integer) invocation.getArguments()[1]) {
396                     case UiccController.APP_FAM_3GPP:
397                         return mSimRecords;
398                     case UiccController.APP_FAM_3GPP2:
399                         return mRuimRecords;
400                     case UiccController.APP_FAM_IMS:
401                         return mIsimUiccRecords;
402                     default:
403                         logd("Unrecognized family " + invocation.getArguments()[1]);
404                         return null;
405                 }
406             }
407         }).when(mUiccController).getIccRecords(anyInt(), anyInt());
408
409         //UiccCardApplication
410         doReturn(mSimRecords).when(mUiccCardApplication3gpp).getIccRecords();
411         doReturn(mRuimRecords).when(mUiccCardApplication3gpp2).getIccRecords();
412         doReturn(mIsimUiccRecords).when(mUiccCardApplicationIms).getIccRecords();
413
414         //mIccCardProxy
415         doReturn(mSimRecords).when(mIccCardProxy).getIccRecords();
416         doAnswer(new Answer<IccRecords>() {
417             public IccRecords answer(InvocationOnMock invocation) {
418                 return (mPhone.isPhoneTypeGsm()) ? mSimRecords : mRuimRecords;
419             }
420         }).when(mIccCardProxy).getIccRecords();
421
422         //SMS
423         doReturn(true).when(mSmsStorageMonitor).isStorageAvailable();
424         doReturn(true).when(mSmsUsageMonitor).check(nullable(String.class), anyInt());
425         doReturn(true).when(mTelephonyManager).getSmsReceiveCapableForPhone(anyInt(), anyBoolean());
426         doReturn(true).when(mTelephonyManager).getSmsSendCapableForPhone(
427                 anyInt(), anyBoolean());
428
429         //Misc
430         doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_UMTS).when(mServiceState).
431                 getRilDataRadioTechnology();
432         doReturn(mPhone).when(mCT).getPhone();
433         mImsManagerInstances.put(mPhone.getPhoneId(), null);
434         doReturn(mImsEcbm).when(mImsManager).getEcbmInterface(anyInt());
435         doReturn(mPhone).when(mInboundSmsHandler).getPhone();
436         doReturn(mImsCallProfile).when(mImsCall).getCallProfile();
437         doReturn(mIBinder).when(mIIntentSender).asBinder();
438         doReturn(mIIntentSender).when(mIActivityManager).getIntentSender(anyInt(),
439                 nullable(String.class), nullable(IBinder.class), nullable(String.class), anyInt(),
440                 nullable(Intent[].class), nullable(String[].class), anyInt(),
441                 nullable(Bundle.class), anyInt());
442         mSST.mSS = mServiceState;
443         mServiceManagerMockedServices.put("connectivity_metrics_logger", mConnMetLoggerBinder);
444
445         Settings.Global.putInt(mContext.getContentResolver(),
446                 Settings.Global.ENABLE_CELLULAR_ON_BOOT, 1);
447
448         setReady(false);
449     }
450
451     protected void tearDown() throws Exception {
452
453         SharedPreferences sharedPreferences = mContext.getSharedPreferences((String) null, 0);
454         sharedPreferences.edit().clear().commit();
455
456         restoreInstances();
457     }
458
459     protected static void logd(String s) {
460         Log.d(TAG, s);
461     }
462
463     public static class FakeBlockedNumberContentProvider extends MockContentProvider {
464         public Set<String> mBlockedNumbers = new HashSet<>();
465         public int mNumEmergencyContactNotifications = 0;
466
467         @Override
468         public Bundle call(String method, String arg, Bundle extras) {
469             switch (method) {
470                 case BlockedNumberContract.SystemContract.METHOD_SHOULD_SYSTEM_BLOCK_NUMBER:
471                     Bundle bundle = new Bundle();
472                     bundle.putBoolean(BlockedNumberContract.RES_NUMBER_IS_BLOCKED,
473                             mBlockedNumbers.contains(arg));
474                     return bundle;
475                 case BlockedNumberContract.SystemContract.METHOD_NOTIFY_EMERGENCY_CONTACT:
476                     mNumEmergencyContactNotifications++;
477                     return new Bundle();
478                 default:
479                     fail("Method not expected: " + method);
480             }
481             return null;
482         }
483     }
484
485     protected void setupMockPackagePermissionChecks() throws Exception {
486         doReturn(new String[]{TAG}).when(mPackageManager).getPackagesForUid(anyInt());
487         doReturn(mPackageInfo).when(mPackageManager).getPackageInfo(eq(TAG), anyInt());
488         doReturn(mPackageInfo).when(mPackageManager).getPackageInfoAsUser(
489                 eq(TAG), anyInt(), anyInt());
490     }
491
492
493     protected final void waitForHandlerAction(Handler h, long timeoutMillis) {
494         final CountDownLatch lock = new CountDownLatch(1);
495         h.post(lock::countDown);
496         while (lock.getCount() > 0) {
497             try {
498                 lock.await(timeoutMillis, TimeUnit.MILLISECONDS);
499             } catch (InterruptedException e) {
500                 // do nothing
501             }
502         }
503     }
504
505     protected final void waitForHandlerActionDelayed(Handler h, long timeoutMillis, long delayMs) {
506         final CountDownLatch lock = new CountDownLatch(1);
507         h.postDelayed(lock::countDown, delayMs);
508         while (lock.getCount() > 0) {
509             try {
510                 lock.await(timeoutMillis, TimeUnit.MILLISECONDS);
511             } catch (InterruptedException e) {
512                 // do nothing
513             }
514         }
515     }
516 }