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