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