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