1 /*
2  * Copyright (C) 2015 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.server.telecom.tests;
18 
19 import com.google.common.collect.ArrayListMultimap;
20 import com.google.common.collect.Multimap;
21 
22 import com.android.internal.telecom.IConnectionService;
23 import com.android.internal.telecom.IInCallService;
24 
25 import org.mockito.MockitoAnnotations;
26 import org.mockito.invocation.InvocationOnMock;
27 import org.mockito.stubbing.Answer;
28 
29 import android.Manifest;
30 import android.app.AppOpsManager;
31 import android.app.NotificationManager;
32 import android.app.StatusBarManager;
33 import android.app.UiModeManager;
34 import android.app.role.RoleManager;
35 import android.content.AttributionSource;
36 import android.content.AttributionSourceState;
37 import android.content.BroadcastReceiver;
38 import android.content.ComponentName;
39 import android.content.ContentResolver;
40 import android.content.Context;
41 import android.content.IContentProvider;
42 import android.content.Intent;
43 import android.content.IntentFilter;
44 import android.content.ServiceConnection;
45 import android.content.pm.ActivityInfo;
46 import android.content.pm.ApplicationInfo;
47 import android.content.pm.PackageManager;
48 import android.content.pm.PermissionInfo;
49 import android.content.pm.ResolveInfo;
50 import android.content.pm.ServiceInfo;
51 import android.content.res.Configuration;
52 import android.content.res.Resources;
53 import android.hardware.SensorPrivacyManager;
54 import android.location.Country;
55 import android.location.CountryDetector;
56 import android.media.AudioManager;
57 import android.os.Bundle;
58 import android.os.Handler;
59 import android.os.IInterface;
60 import android.os.PersistableBundle;
61 import android.os.PowerWhitelistManager;
62 import android.os.Process;
63 import android.os.UserHandle;
64 import android.os.UserManager;
65 import android.os.VibratorManager;
66 import android.permission.PermissionCheckerManager;
67 import android.telecom.CallAudioState;
68 import android.telecom.ConnectionService;
69 import android.telecom.Log;
70 import android.telecom.InCallService;
71 import android.telecom.PhoneAccount;
72 import android.telecom.TelecomManager;
73 import android.telephony.CarrierConfigManager;
74 import android.telephony.SubscriptionManager;
75 import android.telephony.TelephonyManager;
76 import android.telephony.TelephonyRegistryManager;
77 import android.test.mock.MockContext;
78 import android.util.DisplayMetrics;
79 
80 import java.io.File;
81 import java.io.IOException;
82 import java.util.ArrayList;
83 import java.util.Arrays;
84 import java.util.HashMap;
85 import java.util.List;
86 import java.util.Locale;
87 import java.util.Map;
88 import java.util.concurrent.Executor;
89 
90 import static org.mockito.ArgumentMatchers.anyBoolean;
91 import static org.mockito.ArgumentMatchers.matches;
92 import static org.mockito.ArgumentMatchers.nullable;
93 import static org.mockito.Matchers.anyString;
94 import static org.mockito.Mockito.any;
95 import static org.mockito.Mockito.anyInt;
96 import static org.mockito.Mockito.doAnswer;
97 import static org.mockito.Mockito.doReturn;
98 import static org.mockito.Mockito.eq;
99 import static org.mockito.Mockito.mock;
100 import static org.mockito.Mockito.spy;
101 import static org.mockito.Mockito.when;
102 
103 /**
104  * Controls a test {@link Context} as would be provided by the Android framework to an
105  * {@code Activity}, {@code Service} or other system-instantiated component.
106  *
107  * The {@link Context} created by this object is "hollow" but its {@code applicationContext}
108  * property points to an application context implementing all the nontrivial functionality.
109  */
110 public class ComponentContextFixture implements TestFixture<Context> {
111 
112     public class FakeApplicationContext extends MockContext {
113         @Override
getPackageManager()114         public PackageManager getPackageManager() {
115             return mPackageManager;
116         }
117 
118         @Override
getMainExecutor()119         public Executor getMainExecutor() {
120             // TODO: This doesn't actually execute anything as we don't need to do so for now, but
121             //  future users might need it.
122             return mMainExecutor;
123         }
124 
125         @Override
getPackageName()126         public String getPackageName() {
127             return "com.android.server.telecom.tests";
128         }
129 
130         @Override
getPackageResourcePath()131         public String getPackageResourcePath() {
132             return "/tmp/i/dont/know";
133         }
134 
135         @Override
getApplicationContext()136         public Context getApplicationContext() {
137             return mApplicationContextSpy;
138         }
139 
140         @Override
getTheme()141         public Resources.Theme getTheme() {
142             return mResourcesTheme;
143         }
144 
145         @Override
getFilesDir()146         public File getFilesDir() {
147             try {
148                 return File.createTempFile("temp", "temp").getParentFile();
149             } catch (IOException e) {
150                 throw new RuntimeException(e);
151             }
152         }
153 
154         @Override
bindServiceAsUser( Intent serviceIntent, ServiceConnection connection, int flags, UserHandle userHandle)155         public boolean bindServiceAsUser(
156                 Intent serviceIntent,
157                 ServiceConnection connection,
158                 int flags,
159                 UserHandle userHandle) {
160             // TODO: Implement "as user" functionality
161             return bindService(serviceIntent, connection, flags);
162         }
163 
164         @Override
bindService( Intent serviceIntent, ServiceConnection connection, int flags)165         public boolean bindService(
166                 Intent serviceIntent,
167                 ServiceConnection connection,
168                 int flags) {
169             if (mServiceByServiceConnection.containsKey(connection)) {
170                 throw new RuntimeException("ServiceConnection already bound: " + connection);
171             }
172             IInterface service = mServiceByComponentName.get(serviceIntent.getComponent());
173             if (service == null) {
174                 throw new RuntimeException("ServiceConnection not found: "
175                         + serviceIntent.getComponent());
176             }
177             mServiceByServiceConnection.put(connection, service);
178             connection.onServiceConnected(serviceIntent.getComponent(), service.asBinder());
179             return true;
180         }
181 
182         @Override
unbindService( ServiceConnection connection)183         public void unbindService(
184                 ServiceConnection connection) {
185             IInterface service = mServiceByServiceConnection.remove(connection);
186             if (service == null) {
187                 throw new RuntimeException("ServiceConnection not found: " + connection);
188             }
189             connection.onServiceDisconnected(mComponentNameByService.get(service));
190         }
191 
192         @Override
getSystemService(String name)193         public Object getSystemService(String name) {
194             switch (name) {
195                 case Context.AUDIO_SERVICE:
196                     return mAudioManager;
197                 case Context.TELEPHONY_SERVICE:
198                     return mTelephonyManager;
199                 case Context.APP_OPS_SERVICE:
200                     return mAppOpsManager;
201                 case Context.NOTIFICATION_SERVICE:
202                     return mNotificationManager;
203                 case Context.STATUS_BAR_SERVICE:
204                     return mStatusBarManager;
205                 case Context.USER_SERVICE:
206                     return mUserManager;
207                 case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
208                     return mSubscriptionManager;
209                 case Context.TELECOM_SERVICE:
210                     return mTelecomManager;
211                 case Context.CARRIER_CONFIG_SERVICE:
212                     return mCarrierConfigManager;
213                 case Context.COUNTRY_DETECTOR:
214                     return mCountryDetector;
215                 case Context.ROLE_SERVICE:
216                     return mRoleManager;
217                 case Context.TELEPHONY_REGISTRY_SERVICE:
218                     return mTelephonyRegistryManager;
219                 case Context.UI_MODE_SERVICE:
220                     return mUiModeManager;
221                 case Context.VIBRATOR_MANAGER_SERVICE:
222                     return mVibratorManager;
223                 case Context.PERMISSION_CHECKER_SERVICE:
224                     return mPermissionCheckerManager;
225                 case Context.SENSOR_PRIVACY_SERVICE:
226                     return mSensorPrivacyManager;
227                 default:
228                     return null;
229             }
230         }
231 
232         @Override
getSystemServiceName(Class<?> svcClass)233         public String getSystemServiceName(Class<?> svcClass) {
234             if (svcClass == UserManager.class) {
235                 return Context.USER_SERVICE;
236             } else if (svcClass == RoleManager.class) {
237                 return Context.ROLE_SERVICE;
238             } else if (svcClass == AudioManager.class) {
239                 return Context.AUDIO_SERVICE;
240             } else if (svcClass == TelephonyManager.class) {
241                 return Context.TELEPHONY_SERVICE;
242             } else if (svcClass == CarrierConfigManager.class) {
243                 return Context.CARRIER_CONFIG_SERVICE;
244             } else if (svcClass == SubscriptionManager.class) {
245                 return Context.TELEPHONY_SUBSCRIPTION_SERVICE;
246             } else if (svcClass == TelephonyRegistryManager.class) {
247                 return Context.TELEPHONY_REGISTRY_SERVICE;
248             } else if (svcClass == UiModeManager.class) {
249                 return Context.UI_MODE_SERVICE;
250             } else if (svcClass == VibratorManager.class) {
251                 return Context.VIBRATOR_MANAGER_SERVICE;
252             } else if (svcClass == PermissionCheckerManager.class) {
253                 return Context.PERMISSION_CHECKER_SERVICE;
254             } else if (svcClass == SensorPrivacyManager.class) {
255                 return Context.SENSOR_PRIVACY_SERVICE;
256             }
257             throw new UnsupportedOperationException();
258         }
259 
260         @Override
getUserId()261         public int getUserId() {
262             return 0;
263         }
264 
265         @Override
getResources()266         public Resources getResources() {
267             return mResources;
268         }
269 
270         @Override
getOpPackageName()271         public String getOpPackageName() {
272             return "com.android.server.telecom.tests";
273         }
274 
275         @Override
getApplicationInfo()276         public ApplicationInfo getApplicationInfo() {
277             return mTestApplicationInfo;
278         }
279 
280         @Override
getAttributionSource()281         public AttributionSource getAttributionSource() {
282             return mAttributionSource;
283         }
284 
285         @Override
getContentResolver()286         public ContentResolver getContentResolver() {
287             return new ContentResolver(mApplicationContextSpy) {
288                 @Override
289                 protected IContentProvider acquireProvider(Context c, String name) {
290                     Log.i(this, "acquireProvider %s", name);
291                     return getOrCreateProvider(name);
292                 }
293 
294                 @Override
295                 public boolean releaseProvider(IContentProvider icp) {
296                     return true;
297                 }
298 
299                 @Override
300                 protected IContentProvider acquireUnstableProvider(Context c, String name) {
301                     Log.i(this, "acquireUnstableProvider %s", name);
302                     return getOrCreateProvider(name);
303                 }
304 
305                 private IContentProvider getOrCreateProvider(String name) {
306                     if (!mIContentProviderByUri.containsKey(name)) {
307                         mIContentProviderByUri.put(name, mock(IContentProvider.class));
308                     }
309                     return mIContentProviderByUri.get(name);
310                 }
311 
312                 @Override
313                 public boolean releaseUnstableProvider(IContentProvider icp) {
314                     return false;
315                 }
316 
317                 @Override
318                 public void unstableProviderDied(IContentProvider icp) {
319                 }
320             };
321         }
322 
323         @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter)324         public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
325             // TODO -- this is called by WiredHeadsetManager!!!
326             return null;
327         }
328 
329         @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)330         public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
331                 String broadcastPermission, Handler scheduler) {
332             return null;
333         }
334 
335         @Override
registerReceiverAsUser(BroadcastReceiver receiver, UserHandle handle, IntentFilter filter, String broadcastPermission, Handler scheduler)336         public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle handle,
337                 IntentFilter filter, String broadcastPermission, Handler scheduler) {
338             return null;
339         }
340 
341         @Override
sendBroadcast(Intent intent)342         public void sendBroadcast(Intent intent) {
343             // TODO -- need to ensure this is captured
344         }
345 
346         @Override
sendBroadcast(Intent intent, String receiverPermission)347         public void sendBroadcast(Intent intent, String receiverPermission) {
348             // TODO -- need to ensure this is captured
349         }
350 
351         @Override
sendBroadcastAsUser(Intent intent, UserHandle userHandle)352         public void sendBroadcastAsUser(Intent intent, UserHandle userHandle) {
353             // TODO -- need to ensure this is captured
354         }
355 
356         @Override
sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, Bundle options)357         public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission,
358                 Bundle options) {
359             // Override so that this can be verified via spy.
360         }
361 
362         @Override
sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)363         public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
364                 String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler,
365                 int initialCode, String initialData, Bundle initialExtras) {
366             // TODO -- need to ensure this is captured
367         }
368 
369         @Override
sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)370         public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
371                 String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
372                 Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
373         }
374 
375         @Override
sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, Bundle options, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)376         public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
377                 String receiverPermission, int appOp, Bundle options,
378                 BroadcastReceiver resultReceiver, Handler scheduler, int initialCode,
379                 String initialData, Bundle initialExtras) {
380         }
381 
382         @Override
createPackageContextAsUser(String packageName, int flags, UserHandle user)383         public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
384                 throws PackageManager.NameNotFoundException {
385             return this;
386         }
387 
388         @Override
checkCallingOrSelfPermission(String permission)389         public int checkCallingOrSelfPermission(String permission) {
390             return PackageManager.PERMISSION_GRANTED;
391         }
392 
393         @Override
checkSelfPermission(String permission)394         public int checkSelfPermission(String permission) {
395             return PackageManager.PERMISSION_GRANTED;
396         }
397 
398         @Override
enforceCallingOrSelfPermission(String permission, String message)399         public void enforceCallingOrSelfPermission(String permission, String message) {
400             // Don't bother enforcing anything in mock.
401         }
402 
403         @Override
enforcePermission( String permission, int pid, int uid, String message)404         public void enforcePermission(
405                 String permission, int pid, int uid, String message) {
406             // By default, don't enforce anything in mock.
407         }
408 
409         @Override
startActivityAsUser(Intent intent, UserHandle userHandle)410         public void startActivityAsUser(Intent intent, UserHandle userHandle) {
411             // For capturing
412         }
413     }
414 
415     public class FakeAudioManager extends AudioManager {
416 
417         private boolean mMute = false;
418         private boolean mSpeakerphoneOn = false;
419         private int mAudioStreamValue = 1;
420         private int mMode = AudioManager.MODE_NORMAL;
421         private int mRingerMode = AudioManager.RINGER_MODE_NORMAL;
422 
423         public FakeAudioManager(Context context) {
424             super(context);
425         }
426 
427         @Override
428         public void setMicrophoneMute(boolean value) {
429             mMute = value;
430         }
431 
432         @Override
433         public boolean isMicrophoneMute() {
434             return mMute;
435         }
436 
437         @Override
438         public void setSpeakerphoneOn(boolean value) {
439             mSpeakerphoneOn = value;
440         }
441 
442         @Override
443         public boolean isSpeakerphoneOn() {
444             return mSpeakerphoneOn;
445         }
446 
447         @Override
448         public void setMode(int mode) {
449             mMode = mode;
450         }
451 
452         @Override
453         public int getMode() {
454             return mMode;
455         }
456 
457         @Override
458         public void setRingerModeInternal(int ringerMode) {
459             mRingerMode = ringerMode;
460         }
461 
462         @Override
463         public int getRingerModeInternal() {
464             return mRingerMode;
465         }
466 
467         @Override
468         public void setStreamVolume(int streamTypeUnused, int index, int flagsUnused){
469             mAudioStreamValue = index;
470         }
471 
472         @Override
473         public int getStreamVolume(int streamValueUnused) {
474             return mAudioStreamValue;
475         }
476     }
477 
478     private static final String PACKAGE_NAME = "com.android.server.telecom.tests";
479     private final AttributionSource mAttributionSource =
480             new AttributionSource.Builder(Process.myUid()).setPackageName(PACKAGE_NAME).build();
481 
482     private final Multimap<String, ComponentName> mComponentNamesByAction =
483             ArrayListMultimap.create();
484     private final Map<ComponentName, IInterface> mServiceByComponentName = new HashMap<>();
485     private final Map<ComponentName, ServiceInfo> mServiceInfoByComponentName = new HashMap<>();
486     private final Map<ComponentName, ActivityInfo> mActivityInfoByComponentName = new HashMap<>();
487     private final Map<IInterface, ComponentName> mComponentNameByService = new HashMap<>();
488     private final Map<ServiceConnection, IInterface> mServiceByServiceConnection = new HashMap<>();
489 
490     private final Context mContext = new MockContext() {
491         @Override
492         public Context getApplicationContext() {
493             return mApplicationContextSpy;
494         }
495 
496         @Override
497         public Resources getResources() {
498             return mResources;
499         }
500     };
501 
502     // The application context is the most important object this class provides to the system
503     // under test.
504     private final Context mApplicationContext = new FakeApplicationContext();
505 
506     // We then create a spy on the application context allowing standard Mockito-style
507     // when(...) logic to be used to add specific little responses where needed.
508 
509     private final Resources.Theme mResourcesTheme = mock(Resources.Theme.class);
510     private final Resources mResources = mock(Resources.class);
511     private final Context mApplicationContextSpy = spy(mApplicationContext);
512     private final DisplayMetrics mDisplayMetrics = mock(DisplayMetrics.class);
513     private final PackageManager mPackageManager = mock(PackageManager.class);
514     private final Executor mMainExecutor = mock(Executor.class);
515     private final AudioManager mAudioManager = spy(new FakeAudioManager(mContext));
516     private final TelephonyManager mTelephonyManager = mock(TelephonyManager.class);
517     private final AppOpsManager mAppOpsManager = mock(AppOpsManager.class);
518     private final NotificationManager mNotificationManager = mock(NotificationManager.class);
519     private final UserManager mUserManager = mock(UserManager.class);
520     private final StatusBarManager mStatusBarManager = mock(StatusBarManager.class);
521     private final SubscriptionManager mSubscriptionManager = mock(SubscriptionManager.class);
522     private final CarrierConfigManager mCarrierConfigManager = mock(CarrierConfigManager.class);
523     private final CountryDetector mCountryDetector = mock(CountryDetector.class);
524     private final Map<String, IContentProvider> mIContentProviderByUri = new HashMap<>();
525     private final Configuration mResourceConfiguration = new Configuration();
526     private final ApplicationInfo mTestApplicationInfo = new ApplicationInfo();
527     private final RoleManager mRoleManager = mock(RoleManager.class);
528     private final TelephonyRegistryManager mTelephonyRegistryManager =
529             mock(TelephonyRegistryManager.class);
530     private final VibratorManager mVibratorManager = mock(VibratorManager.class);
531     private final UiModeManager mUiModeManager = mock(UiModeManager.class);
532     private final PermissionCheckerManager mPermissionCheckerManager =
533             mock(PermissionCheckerManager.class);
534     private final PermissionInfo mPermissionInfo = mock(PermissionInfo.class);
535     private final SensorPrivacyManager mSensorPrivacyManager = mock(SensorPrivacyManager.class);
536 
537     private TelecomManager mTelecomManager = mock(TelecomManager.class);
538 
539     public ComponentContextFixture() {
540         MockitoAnnotations.initMocks(this);
541         when(mResources.getConfiguration()).thenReturn(mResourceConfiguration);
542         when(mResources.getString(anyInt())).thenReturn("");
543         when(mResources.getStringArray(anyInt())).thenReturn(new String[0]);
544         when(mResources.newTheme()).thenReturn(mResourcesTheme);
545         when(mResources.getDisplayMetrics()).thenReturn(mDisplayMetrics);
546         mDisplayMetrics.density = 3.125f;
547         mResourceConfiguration.setLocale(Locale.TAIWAN);
548 
549         // TODO: Move into actual tests
550         doReturn(false).when(mAudioManager).isWiredHeadsetOn();
551 
552         doAnswer(new Answer<List<ResolveInfo>>() {
553             @Override
554             public List<ResolveInfo> answer(InvocationOnMock invocation) throws Throwable {
555                 return doQueryIntentServices(
556                         (Intent) invocation.getArguments()[0],
557                         (Integer) invocation.getArguments()[1]);
558             }
559         }).when(mPackageManager).queryIntentServices((Intent) any(), anyInt());
560 
561         doAnswer(new Answer<List<ResolveInfo>>() {
562             @Override
563             public List<ResolveInfo> answer(InvocationOnMock invocation) throws Throwable {
564                 return doQueryIntentServices(
565                         (Intent) invocation.getArguments()[0],
566                         (Integer) invocation.getArguments()[1]);
567             }
568         }).when(mPackageManager).queryIntentServicesAsUser((Intent) any(), anyInt(), anyInt());
569 
570         doAnswer(new Answer<List<ResolveInfo>>() {
571             @Override
572             public List<ResolveInfo> answer(InvocationOnMock invocation) throws Throwable {
573                 return doQueryIntentReceivers(
574                         (Intent) invocation.getArguments()[0],
575                         (Integer) invocation.getArguments()[1]);
576             }
577         }).when(mPackageManager).queryBroadcastReceivers((Intent) any(), anyInt());
578 
579         doAnswer(new Answer<List<ResolveInfo>>() {
580             @Override
581             public List<ResolveInfo> answer(InvocationOnMock invocation) throws Throwable {
582                 return doQueryIntentReceivers(
583                         (Intent) invocation.getArguments()[0],
584                         (Integer) invocation.getArguments()[1]);
585             }
586         }).when(mPackageManager).queryBroadcastReceiversAsUser((Intent) any(), anyInt(), anyInt());
587 
588         // By default, tests use non-ui apps instead of 3rd party companion apps.
589         when(mPermissionCheckerManager.checkPermission(
590                 matches(Manifest.permission.CALL_COMPANION_APP), any(AttributionSourceState.class),
591                 nullable(String.class), anyBoolean(), anyBoolean(), anyBoolean(), anyInt()))
592                 .thenReturn(PermissionCheckerManager.PERMISSION_HARD_DENIED);
593 
594         try {
595             when(mPackageManager.getPermissionInfo(anyString(), anyInt())).thenReturn(
596                     mPermissionInfo);
597         } catch (PackageManager.NameNotFoundException ex) {
598         }
599 
600         when(mPermissionInfo.isAppOp()).thenReturn(true);
601         when(mVibratorManager.getVibratorIds()).thenReturn(new int[0]);
602 
603         // Used in CreateConnectionProcessor to rank emergency numbers by viability.
604         // For the test, make them all equal to INVALID so that the preferred PhoneAccount will be
605         // chosen.
606         when(mTelephonyManager.getSubscriptionId(any())).thenReturn(
607                 SubscriptionManager.INVALID_SUBSCRIPTION_ID);
608 
609         when(mTelephonyManager.getNetworkOperatorName()).thenReturn("label1");
610         when(mTelephonyManager.getMaxNumberOfSimultaneouslyActiveSims()).thenReturn(1);
611         when(mTelephonyManager.createForSubscriptionId(anyInt())).thenReturn(mTelephonyManager);
612         when(mResources.getBoolean(eq(R.bool.grant_location_permission_enabled))).thenReturn(false);
613         doAnswer(new Answer<Void>(){
614             @Override
615             public Void answer(InvocationOnMock invocation) throws Throwable {
616                 return null;
617             }
618         }).when(mAppOpsManager).checkPackage(anyInt(), anyString());
619 
620         when(mNotificationManager.matchesCallFilter(any(Bundle.class))).thenReturn(true);
621 
622         when(mCarrierConfigManager.getConfig()).thenReturn(new PersistableBundle());
623         when(mCarrierConfigManager.getConfigForSubId(anyInt())).thenReturn(new PersistableBundle());
624 
625         when(mUserManager.getSerialNumberForUser(any(UserHandle.class))).thenReturn(-1L);
626 
627         doReturn(null).when(mApplicationContextSpy).registerReceiver(any(BroadcastReceiver.class),
628                 any(IntentFilter.class));
629 
630         // Make sure we do not hide PII during testing.
631         Log.setTag("TelecomTEST");
632         Log.setIsExtendedLoggingEnabled(true);
633         Log.VERBOSE = true;
634     }
635 
636     @Override
637     public Context getTestDouble() {
638         return mContext;
639     }
640 
641     public void addConnectionService(
642             ComponentName componentName,
643             IConnectionService service)
644             throws Exception {
645         addService(ConnectionService.SERVICE_INTERFACE, componentName, service);
646         ServiceInfo serviceInfo = new ServiceInfo();
647         serviceInfo.permission = android.Manifest.permission.BIND_CONNECTION_SERVICE;
648         serviceInfo.packageName = componentName.getPackageName();
649         serviceInfo.name = componentName.getClassName();
650         mServiceInfoByComponentName.put(componentName, serviceInfo);
651     }
652 
653     public void addInCallService(
654             ComponentName componentName,
655             IInCallService service,
656             int uid)
657             throws Exception {
658         addService(InCallService.SERVICE_INTERFACE, componentName, service);
659         ServiceInfo serviceInfo = new ServiceInfo();
660         serviceInfo.permission = android.Manifest.permission.BIND_INCALL_SERVICE;
661         serviceInfo.packageName = componentName.getPackageName();
662         serviceInfo.applicationInfo = new ApplicationInfo();
663         serviceInfo.applicationInfo.uid = uid;
664         serviceInfo.metaData = new Bundle();
665         serviceInfo.metaData.putBoolean(TelecomManager.METADATA_IN_CALL_SERVICE_UI, false);
666         serviceInfo.name = componentName.getClassName();
667         mServiceInfoByComponentName.put(componentName, serviceInfo);
668 
669         // Used in InCallController to check permissions for CONTROL_INCALL_fvEXPERIENCE
670         when(mPackageManager.getPackagesForUid(eq(uid))).thenReturn(new String[] {
671                 componentName.getPackageName() });
672         when(mPackageManager.checkPermission(eq(Manifest.permission.CONTROL_INCALL_EXPERIENCE),
673                 eq(componentName.getPackageName()))).thenReturn(PackageManager.PERMISSION_GRANTED);
674         when(mPermissionCheckerManager.checkPermission(
675                 eq(Manifest.permission.CONTROL_INCALL_EXPERIENCE),
676                 any(AttributionSourceState.class), anyString(), anyBoolean(), anyBoolean(),
677                 anyBoolean(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
678     }
679 
680     public void addIntentReceiver(String action, ComponentName name) {
681         mComponentNamesByAction.put(action, name);
682         ActivityInfo activityInfo = new ActivityInfo();
683         activityInfo.packageName = name.getPackageName();
684         activityInfo.name = name.getClassName();
685         mActivityInfoByComponentName.put(name, activityInfo);
686     }
687 
688     public void putResource(int id, final String value) {
689         when(mResources.getText(eq(id))).thenReturn(value);
690         when(mResources.getString(eq(id))).thenReturn(value);
691         when(mResources.getString(eq(id), any())).thenAnswer(new Answer<String>() {
692             @Override
693             public String answer(InvocationOnMock invocation) {
694                 Object[] args = invocation.getArguments();
695                 return String.format(value, Arrays.copyOfRange(args, 1, args.length));
696             }
697         });
698     }
699 
700     public void putFloatResource(int id, final float value) {
701         when(mResources.getFloat(eq(id))).thenReturn(value);
702     }
703 
704     public void putBooleanResource(int id, boolean value) {
705         when(mResources.getBoolean(eq(id))).thenReturn(value);
706     }
707 
708     public void putStringArrayResource(int id, String[] value) {
709         when(mResources.getStringArray(eq(id))).thenReturn(value);
710     }
711 
712     public void setTelecomManager(TelecomManager telecomManager) {
713         mTelecomManager = telecomManager;
714     }
715 
716     public TelephonyManager getTelephonyManager() {
717         return mTelephonyManager;
718     }
719 
720     public NotificationManager getNotificationManager() {
721         return mNotificationManager;
722     }
723 
724     private void addService(String action, ComponentName name, IInterface service) {
725         mComponentNamesByAction.put(action, name);
726         mServiceByComponentName.put(name, service);
727         mComponentNameByService.put(service, name);
728     }
729 
730     private List<ResolveInfo> doQueryIntentServices(Intent intent, int flags) {
731         List<ResolveInfo> result = new ArrayList<>();
732         for (ComponentName componentName : mComponentNamesByAction.get(intent.getAction())) {
733             ResolveInfo resolveInfo = new ResolveInfo();
734             resolveInfo.serviceInfo = mServiceInfoByComponentName.get(componentName);
735             resolveInfo.serviceInfo.metaData = new Bundle();
736             resolveInfo.serviceInfo.metaData.putBoolean(
737                     TelecomManager.METADATA_INCLUDE_EXTERNAL_CALLS, true);
738             result.add(resolveInfo);
739         }
740         return result;
741     }
742 
743     private List<ResolveInfo> doQueryIntentReceivers(Intent intent, int flags) {
744         List<ResolveInfo> result = new ArrayList<>();
745         for (ComponentName componentName : mComponentNamesByAction.get(intent.getAction())) {
746             ResolveInfo resolveInfo = new ResolveInfo();
747             resolveInfo.activityInfo = mActivityInfoByComponentName.get(componentName);
748             result.add(resolveInfo);
749         }
750         return result;
751     }
752 }
753