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