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