1 /* 2 * Copyright (C) 2024 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 package com.android.nfc; 17 18 import static android.nfc.NfcAdapter.ACTION_PREFERRED_PAYMENT_CHANGED; 19 20 import static com.android.nfc.NfcService.INVALID_NATIVE_HANDLE; 21 import static com.android.nfc.NfcService.NCI_VERSION_1_0; 22 import static com.android.nfc.NfcService.NFC_LISTEN_A; 23 import static com.android.nfc.NfcService.NFC_LISTEN_B; 24 import static com.android.nfc.NfcService.NFC_LISTEN_F; 25 import static com.android.nfc.NfcService.NFC_POLL_V; 26 import static com.android.nfc.NfcService.PREF_NFC_ON; 27 import static com.android.nfc.NfcService.SOUND_END; 28 import static com.android.nfc.NfcService.SOUND_ERROR; 29 30 import static com.google.common.truth.Truth.assertThat; 31 32 import static org.junit.Assert.assertArrayEquals; 33 import static org.junit.Assert.assertTrue; 34 import static org.junit.Assert.assertFalse; 35 import static org.mockito.ArgumentMatchers.any; 36 import static org.mockito.ArgumentMatchers.anyBoolean; 37 import static org.mockito.ArgumentMatchers.anyFloat; 38 import static org.mockito.ArgumentMatchers.anyInt; 39 import static org.mockito.ArgumentMatchers.anyString; 40 import static org.mockito.ArgumentMatchers.argThat; 41 import static org.mockito.ArgumentMatchers.eq; 42 import static org.mockito.ArgumentMatchers.isNull; 43 import static org.mockito.Mockito.atLeast; 44 import static org.mockito.Mockito.atLeastOnce; 45 import static org.mockito.Mockito.clearInvocations; 46 import static org.mockito.Mockito.doAnswer; 47 import static org.mockito.Mockito.doNothing; 48 import static org.mockito.Mockito.mock; 49 import static org.mockito.Mockito.never; 50 import static org.mockito.Mockito.times; 51 import static org.mockito.Mockito.verify; 52 import static org.mockito.Mockito.verifyNoMoreInteractions; 53 import static org.mockito.Mockito.when; 54 55 import android.app.ActivityManager; 56 import android.app.AlarmManager; 57 import android.app.Application; 58 import android.app.KeyguardManager; 59 import android.app.VrManager; 60 import android.app.backup.BackupManager; 61 import android.app.role.RoleManager; 62 import android.content.BroadcastReceiver; 63 import android.content.ContentResolver; 64 import android.content.Context; 65 import android.content.Intent; 66 import android.content.SharedPreferences; 67 import android.content.pm.ApplicationInfo; 68 import android.content.pm.PackageInfo; 69 import android.content.pm.PackageManager; 70 import android.content.res.Resources; 71 import android.database.ContentObserver; 72 import android.hardware.display.DisplayManager; 73 import android.media.SoundPool; 74 import android.nfc.ErrorCodes; 75 import android.nfc.INfcAdapterExtras; 76 import android.nfc.INfcControllerAlwaysOnListener; 77 import android.nfc.INfcDta; 78 import android.nfc.INfcOemExtensionCallback; 79 import android.nfc.INfcUnlockHandler; 80 import android.nfc.INfcVendorNciCallback; 81 import android.nfc.INfcWlcStateListener; 82 import android.nfc.ITagRemovedCallback; 83 import android.nfc.NdefMessage; 84 import android.nfc.NdefRecord; 85 import android.nfc.NfcAdapter; 86 import android.nfc.NfcAntennaInfo; 87 import android.nfc.NfcOemExtension; 88 import android.nfc.NfcServiceManager; 89 import android.nfc.Tag; 90 import android.nfc.TransceiveResult; 91 import android.nfc.WlcListenerDeviceInfo; 92 import android.nfc.cardemulation.CardEmulation; 93 import android.nfc.cardemulation.PollingFrame; 94 import android.nfc.tech.Ndef; 95 import android.nfc.tech.TagTechnology; 96 import android.os.AsyncTask; 97 import android.os.Binder; 98 import android.os.Bundle; 99 import android.os.Handler; 100 import android.os.HandlerExecutor; 101 import android.os.IBinder; 102 import android.os.Message; 103 import android.os.ParcelFileDescriptor; 104 import android.os.PowerManager; 105 import android.os.RemoteException; 106 import android.os.ResultReceiver; 107 import android.os.SystemClock; 108 import android.os.UserHandle; 109 import android.os.UserManager; 110 import android.os.test.TestLooper; 111 import android.platform.test.annotations.RequiresFlagsEnabled; 112 import android.platform.test.flag.junit.CheckFlagsRule; 113 import android.platform.test.flag.junit.DeviceFlagsValueProvider; 114 import android.se.omapi.ISecureElementService; 115 import android.sysprop.NfcProperties; 116 import android.view.Display; 117 118 import androidx.test.ext.junit.runners.AndroidJUnit4; 119 120 import com.android.dx.mockito.inline.extended.ExtendedMockito; 121 import com.android.nfc.cardemulation.CardEmulationManager; 122 import com.android.nfc.cardemulation.util.StatsdUtils; 123 import com.android.nfc.flags.FeatureFlags; 124 import com.android.nfc.flags.Flags; 125 import com.android.nfc.wlc.NfcCharging; 126 127 128 import org.junit.After; 129 import org.junit.Assert; 130 import org.junit.Assume; 131 import org.junit.Before; 132 import org.junit.Rule; 133 import org.junit.Test; 134 import org.junit.runner.RunWith; 135 import org.mockito.ArgumentCaptor; 136 import org.mockito.Captor; 137 import org.mockito.Mock; 138 import org.mockito.MockitoAnnotations; 139 import org.mockito.MockitoSession; 140 import org.mockito.invocation.InvocationOnMock; 141 import org.mockito.quality.Strictness; 142 import org.mockito.stubbing.Answer; 143 144 import java.io.FileDescriptor; 145 import java.nio.charset.StandardCharsets; 146 import java.util.ArrayList; 147 import java.util.Arrays; 148 import java.util.Collections; 149 import java.util.HashMap; 150 import java.util.HexFormat; 151 import java.util.List; 152 import java.util.Map; 153 import java.util.Optional; 154 155 @RunWith(AndroidJUnit4.class) 156 public final class NfcServiceTest { 157 private static final String PKG_NAME = "com.test"; 158 private static final int[] ANTENNA_POS_X = { 5 }; 159 private static final int[] ANTENNA_POS_Y = { 6 }; 160 private static final int ANTENNA_DEVICE_WIDTH = 9; 161 private static final int ANTENNA_DEVICE_HEIGHT = 10; 162 private static final boolean ANTENNA_DEVICE_FOLDABLE = true; 163 @Mock Application mApplication; 164 @Mock NfcInjector mNfcInjector; 165 @Mock DeviceHost mDeviceHost; 166 @Mock NfcEventLog mNfcEventLog; 167 @Mock NfcDispatcher mNfcDispatcher; 168 @Mock NfcUnlockManager mNfcUnlockManager; 169 @Mock SharedPreferences mPreferences; 170 @Mock SharedPreferences.Editor mPreferencesEditor; 171 @Mock PowerManager mPowerManager; 172 @Mock PackageManager mPackageManager; 173 @Mock ScreenStateHelper mScreenStateHelper; 174 @Mock Resources mResources; 175 @Mock KeyguardManager mKeyguardManager; 176 @Mock UserManager mUserManager; 177 @Mock ActivityManager mActivityManager; 178 @Mock NfcServiceManager.ServiceRegisterer mNfcManagerRegisterer; 179 @Mock NfcDiagnostics mNfcDiagnostics; 180 @Mock DeviceConfigFacade mDeviceConfigFacade; 181 @Mock ContentResolver mContentResolver; 182 @Mock Bundle mUserRestrictions; 183 @Mock BackupManager mBackupManager; 184 @Mock AlarmManager mAlarmManager; 185 @Mock SoundPool mSoundPool; 186 @Mock FeatureFlags mFeatureFlags; 187 @Mock DisplayManager mDisplayManager; 188 @Mock CardEmulationManager mCardEmulationManager; 189 @Mock StatsdUtils mStatsdUtils; 190 @Mock NfcCharging mNfcCharging; 191 @Mock VrManager mVrManager; 192 @Mock RoleManager mRoleManager; 193 @Captor ArgumentCaptor<DeviceHost.DeviceHostListener> mDeviceHostListener; 194 @Captor ArgumentCaptor<BroadcastReceiver> mGlobalReceiver; 195 @Captor ArgumentCaptor<IBinder> mIBinderArgumentCaptor; 196 @Captor ArgumentCaptor<Integer> mSoundCaptor; 197 @Captor ArgumentCaptor<Intent> mIntentArgumentCaptor; 198 @Captor ArgumentCaptor<ContentObserver> mContentObserverArgumentCaptor; 199 @Captor ArgumentCaptor<BroadcastReceiver> mBroadcastReceiverArgumentCaptor; 200 TestLooper mLooper; 201 NfcService mNfcService; 202 private MockitoSession mStaticMockSession; 203 private ContentObserver mContentObserver; 204 private TestClock mClock = new TestClock(); 205 206 class TestClock implements TestLooper.Clock { 207 long mOffset = 0; uptimeMillis()208 public long uptimeMillis() { 209 return SystemClock.uptimeMillis() + mOffset; 210 } 211 } 212 213 @Rule 214 public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule(); 215 216 @Before setUp()217 public void setUp() throws PackageManager.NameNotFoundException { 218 mLooper = new TestLooper(mClock); 219 mStaticMockSession = ExtendedMockito.mockitoSession() 220 .mockStatic(NfcProperties.class) 221 .mockStatic(android.nfc.Flags.class) 222 .mockStatic(Flags.class) 223 .mockStatic(NfcStatsLog.class) 224 .mockStatic(android.permission.flags.Flags.class) 225 .mockStatic(NfcInjector.class) 226 .strictness(Strictness.LENIENT) 227 .startMocking(); 228 MockitoAnnotations.initMocks(this); 229 AsyncTask.setDefaultExecutor(new HandlerExecutor(new Handler(mLooper.getLooper()))); 230 231 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) 232 .thenReturn(true); 233 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)) 234 .thenReturn(false); 235 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) 236 .thenReturn(true); 237 when(mNfcInjector.getMainLooper()).thenReturn(mLooper.getLooper()); 238 when(mNfcInjector.getNfcEventLog()).thenReturn(mNfcEventLog); 239 when(mNfcInjector.makeDeviceHost(any())).thenReturn(mDeviceHost); 240 when(mNfcInjector.getScreenStateHelper()).thenReturn(mScreenStateHelper); 241 when(mNfcInjector.getNfcDiagnostics()).thenReturn(mNfcDiagnostics); 242 when(mNfcInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade); 243 when(mNfcInjector.getNfcManagerRegisterer()).thenReturn(mNfcManagerRegisterer); 244 when(mNfcInjector.getBackupManager()).thenReturn(mBackupManager); 245 when(mNfcInjector.getNfcDispatcher()).thenReturn(mNfcDispatcher); 246 when(mNfcInjector.getNfcUnlockManager()).thenReturn(mNfcUnlockManager); 247 when(mNfcInjector.getFeatureFlags()).thenReturn(mFeatureFlags); 248 when(mNfcInjector.isSatelliteModeSensitive()).thenReturn(true); 249 when(mNfcInjector.getCardEmulationManager()).thenReturn(mCardEmulationManager); 250 when(mNfcInjector.getNfcCharging(mDeviceHost)).thenReturn(mNfcCharging); 251 when(mApplication.getSharedPreferences(anyString(), anyInt())).thenReturn(mPreferences); 252 when(mApplication.getSystemService(PowerManager.class)).thenReturn(mPowerManager); 253 when(mApplication.getSystemService(UserManager.class)).thenReturn(mUserManager); 254 when(mApplication.getSystemService(ActivityManager.class)).thenReturn(mActivityManager); 255 when(mApplication.getSystemService(KeyguardManager.class)).thenReturn(mKeyguardManager); 256 when(mApplication.getSystemService(AlarmManager.class)).thenReturn(mAlarmManager); 257 when(mApplication.getPackageManager()).thenReturn(mPackageManager); 258 when(mDeviceConfigFacade.getCheckDisplayStateForScreenState()).thenReturn(true); 259 when(mApplication.getResources()).thenReturn(mResources); 260 when(mApplication.createContextAsUser(any(), anyInt())).thenReturn(mApplication); 261 when(mApplication.getContentResolver()).thenReturn(mContentResolver); 262 when(mApplication.getSystemService(DisplayManager.class)).thenReturn(mDisplayManager); 263 when(mApplication.getSystemService(VrManager.class)).thenReturn(mVrManager); 264 when(mApplication.getSystemService(RoleManager.class)).thenReturn(mRoleManager); 265 when(mUserManager.getUserRestrictions()).thenReturn(mUserRestrictions); 266 when(mResources.getStringArray(R.array.nfc_allow_list)).thenReturn(new String[0]); 267 when(mResources.getBoolean(R.bool.tag_intent_app_pref_supported)).thenReturn(true); 268 when(mDeviceConfigFacade.getNfccAlwaysOnAllowed()).thenReturn(true); 269 when(mPreferences.edit()).thenReturn(mPreferencesEditor); 270 when(mPowerManager.newWakeLock(anyInt(), anyString())) 271 .thenReturn(mock(PowerManager.WakeLock.class)); 272 when(mResources.getIntArray(R.array.antenna_x)).thenReturn(new int[0]); 273 when(mResources.getIntArray(R.array.antenna_y)).thenReturn(new int[0]); 274 when(mResources.getStringArray(R.array.tag_intent_blocked_app_list)) 275 .thenReturn(new String[]{"com.android.test"}); 276 when(NfcProperties.info_antpos_X()).thenReturn(List.of()); 277 when(NfcProperties.info_antpos_Y()).thenReturn(List.of()); 278 when(NfcProperties.initialized()).thenReturn(Optional.of(Boolean.TRUE)); 279 when(NfcProperties.vendor_debug_enabled()).thenReturn(Optional.of(Boolean.TRUE)); 280 when(mPackageManager.getPackageUid(PKG_NAME, 0)).thenReturn(Binder.getCallingUid()); 281 createNfcService(); 282 } 283 284 @After tearDown()285 public void tearDown() { 286 mStaticMockSession.finishMocking(); 287 } 288 createNfcService()289 private void createNfcService() { 290 when(android.nfc.Flags.enableNfcCharging()).thenReturn(true); 291 when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_NFC_CHARGING)) 292 .thenReturn(true); 293 mNfcService = new NfcService(mApplication, mNfcInjector); 294 mLooper.dispatchAll(); 295 verify(mContentResolver, atLeastOnce()).registerContentObserver(any(), 296 anyBoolean(), mContentObserverArgumentCaptor.capture()); 297 mContentObserver = mContentObserverArgumentCaptor.getValue(); 298 Assert.assertNotNull(mContentObserver); 299 verify(mNfcInjector).makeDeviceHost(mDeviceHostListener.capture()); 300 verify(mApplication).registerReceiverForAllUsers( 301 mGlobalReceiver.capture(), 302 argThat(intent -> intent.hasAction(Intent.ACTION_SCREEN_ON)), any(), any()); 303 verify(mApplication).registerReceiver(mBroadcastReceiverArgumentCaptor.capture(), 304 argThat(intent -> intent.hasAction(UserManager.ACTION_USER_RESTRICTIONS_CHANGED))); 305 clearInvocations(mDeviceHost, mNfcInjector, mApplication); 306 } 307 createNfcServiceWithoutStatsdUtils()308 private void createNfcServiceWithoutStatsdUtils() { 309 when(mNfcInjector.getStatsdUtils()).thenReturn(mStatsdUtils); 310 createNfcService(); 311 } 312 enableAndVerify()313 private void enableAndVerify() throws Exception { 314 when(mDeviceHost.initialize()).thenReturn(true); 315 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 316 mNfcService.mNfcAdapter.enable(PKG_NAME); 317 verify(mPreferencesEditor).putBoolean(PREF_NFC_ON, true); 318 mLooper.dispatchAll(); 319 verify(mDeviceHost).initialize(); 320 clearInvocations(mDeviceHost, mPreferencesEditor); 321 } 322 disableAndVerify()323 private void disableAndVerify() throws Exception { 324 when(mDeviceHost.deinitialize()).thenReturn(true); 325 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(false); 326 mNfcService.mNfcAdapter.disable(true, PKG_NAME); 327 verify(mPreferencesEditor).putBoolean(PREF_NFC_ON, false); 328 mLooper.dispatchAll(); 329 verify(mDeviceHost).deinitialize(); 330 verify(mNfcDispatcher).resetForegroundDispatch(); 331 clearInvocations(mDeviceHost, mPreferencesEditor, mNfcDispatcher); 332 } 333 334 335 @Test testEnable()336 public void testEnable() throws Exception { 337 enableAndVerify(); 338 } 339 340 @Test testDisable()341 public void testDisable() throws Exception { 342 enableAndVerify(); 343 disableAndVerify(); 344 } 345 346 @Test testEnable_WheOemExtensionEnabledAndNotInitialized()347 public void testEnable_WheOemExtensionEnabledAndNotInitialized() throws Exception { 348 when(mDeviceConfigFacade.getEnableOemExtension()).thenReturn(true); 349 when(NfcProperties.initialized()).thenReturn(Optional.of(Boolean.FALSE)); 350 351 createNfcService(); 352 353 when(mDeviceHost.initialize()).thenReturn(true); 354 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 355 mNfcService.mNfcAdapter.enable(PKG_NAME); 356 verify(mPreferencesEditor, never()).putBoolean(PREF_NFC_ON, true); 357 mLooper.dispatchAll(); 358 verify(mDeviceHost, never()).initialize(); 359 } 360 361 @Test testBootupWithNfcOn()362 public void testBootupWithNfcOn() throws Exception { 363 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 364 mNfcService = new NfcService(mApplication, mNfcInjector); 365 mLooper.dispatchAll(); 366 verify(mNfcInjector).makeDeviceHost(mDeviceHostListener.capture()); 367 verify(mApplication).registerReceiverForAllUsers( 368 mGlobalReceiver.capture(), 369 argThat(intent -> intent.hasAction(Intent.ACTION_SCREEN_ON)), any(), any()); 370 verify(mDeviceHost).initialize(); 371 } 372 373 @Test testBootupWithNfcOn_WhenOemExtensionEnabled()374 public void testBootupWithNfcOn_WhenOemExtensionEnabled() throws Exception { 375 when(mDeviceConfigFacade.getEnableOemExtension()).thenReturn(true); 376 createNfcService(); 377 378 verifyNoMoreInteractions(mDeviceHost); 379 } 380 381 @Test testBootupWithNfcOn_WhenOemExtensionEnabled_ThenAllowBoot()382 public void testBootupWithNfcOn_WhenOemExtensionEnabled_ThenAllowBoot() throws Exception { 383 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 384 when(mResources.getBoolean(R.bool.enable_oem_extension)).thenReturn(true); 385 createNfcService(); 386 387 mNfcService.mNfcAdapter.triggerInitialization(); 388 mLooper.dispatchAll(); 389 verify(mDeviceHost).initialize(); 390 } 391 392 @Test testSetObserveMode_nfcDisabled()393 public void testSetObserveMode_nfcDisabled() throws Exception { 394 mNfcService.mNfcAdapter.disable(true, PKG_NAME); 395 396 Assert.assertFalse(mNfcService.mNfcAdapter.setObserveMode(true, PKG_NAME)); 397 } 398 399 @Test testIsObserveModeEnabled_nfcDisabled()400 public void testIsObserveModeEnabled_nfcDisabled() throws Exception { 401 mNfcService.mNfcAdapter.disable(true, PKG_NAME); 402 403 Assert.assertFalse(mNfcService.mNfcAdapter.isObserveModeEnabled()); 404 } 405 406 @Test testIsObserveModeSupported_nfcDisabled()407 public void testIsObserveModeSupported_nfcDisabled() throws Exception { 408 mNfcService.mNfcAdapter.disable(true, PKG_NAME); 409 410 Assert.assertFalse(mNfcService.mNfcAdapter.isObserveModeSupported()); 411 } 412 413 @Test testEnableNfc_changeStateRestricted()414 public void testEnableNfc_changeStateRestricted() throws Exception { 415 when(mUserRestrictions.getBoolean( 416 UserManager.DISALLOW_CHANGE_NEAR_FIELD_COMMUNICATION_RADIO)).thenReturn(true); 417 mNfcService.mNfcAdapter.enable(PKG_NAME); 418 assert(mNfcService.mState == NfcAdapter.STATE_OFF); 419 } 420 421 @Test testDisableNfc_changeStateRestricted()422 public void testDisableNfc_changeStateRestricted() throws Exception { 423 enableAndVerify(); 424 when(mUserRestrictions.getBoolean( 425 UserManager.DISALLOW_CHANGE_NEAR_FIELD_COMMUNICATION_RADIO)).thenReturn(true); 426 mNfcService.mNfcAdapter.disable(true, PKG_NAME); 427 assert(mNfcService.mState == NfcAdapter.STATE_ON); 428 } 429 430 @Test testHandlerResumePolling()431 public void testHandlerResumePolling() { 432 Handler handler = mNfcService.getHandler(); 433 Assert.assertNotNull(handler); 434 handler.handleMessage(handler.obtainMessage(NfcService.MSG_RESUME_POLLING)); 435 verify(mNfcManagerRegisterer).register(mIBinderArgumentCaptor.capture()); 436 Assert.assertNotNull(mIBinderArgumentCaptor.getValue()); 437 Assert.assertFalse(handler.hasMessages(NfcService.MSG_RESUME_POLLING)); 438 Assert.assertEquals(mIBinderArgumentCaptor.getValue(), mNfcService.mNfcAdapter); 439 } 440 441 @Test testHandlerRoute_Aid()442 public void testHandlerRoute_Aid() { 443 Handler handler = mNfcService.getHandler(); 444 Assert.assertNotNull(handler); 445 Message msg = handler.obtainMessage(NfcService.MSG_ROUTE_AID); 446 msg.arg1 = 1; 447 msg.arg2 = 2; 448 msg.obj = "test"; 449 handler.handleMessage(msg); 450 verify(mDeviceHost).routeAid(any(), anyInt(), anyInt(), anyInt()); 451 } 452 453 @Test testHandlerUnRoute_Aid()454 public void testHandlerUnRoute_Aid() { 455 Handler handler = mNfcService.getHandler(); 456 Assert.assertNotNull(handler); 457 Message msg = handler.obtainMessage(NfcService.MSG_UNROUTE_AID); 458 msg.obj = "test"; 459 handler.handleMessage(msg); 460 verify(mDeviceHost).unrouteAid(any()); 461 } 462 463 @Test testGetAntennaInfo_NoneSet()464 public void testGetAntennaInfo_NoneSet() throws Exception { 465 enableAndVerify(); 466 NfcAntennaInfo nfcAntennaInfo = mNfcService.mNfcAdapter.getNfcAntennaInfo(); 467 assertThat(nfcAntennaInfo).isNotNull(); 468 assertThat(nfcAntennaInfo.getDeviceWidth()).isEqualTo(0); 469 assertThat(nfcAntennaInfo.getDeviceHeight()).isEqualTo(0); 470 assertThat(nfcAntennaInfo.isDeviceFoldable()).isEqualTo(false); 471 assertThat(nfcAntennaInfo.getAvailableNfcAntennas()).isEmpty(); 472 } 473 474 @Test testGetAntennaInfo_ReadFromResources()475 public void testGetAntennaInfo_ReadFromResources() throws Exception { 476 enableAndVerify(); 477 when(mResources.getIntArray(R.array.antenna_x)).thenReturn(ANTENNA_POS_X); 478 when(mResources.getIntArray(R.array.antenna_y)).thenReturn(ANTENNA_POS_Y); 479 when(mResources.getInteger(R.integer.device_width)).thenReturn(ANTENNA_DEVICE_WIDTH); 480 when(mResources.getInteger(R.integer.device_height)).thenReturn(ANTENNA_DEVICE_HEIGHT); 481 when(mResources.getBoolean(R.bool.device_foldable)).thenReturn(ANTENNA_DEVICE_FOLDABLE); 482 NfcAntennaInfo nfcAntennaInfo = mNfcService.mNfcAdapter.getNfcAntennaInfo(); 483 assertThat(nfcAntennaInfo).isNotNull(); 484 assertThat(nfcAntennaInfo.getDeviceWidth()).isEqualTo(ANTENNA_DEVICE_WIDTH); 485 assertThat(nfcAntennaInfo.getDeviceHeight()).isEqualTo(ANTENNA_DEVICE_HEIGHT); 486 assertThat(nfcAntennaInfo.isDeviceFoldable()).isEqualTo(ANTENNA_DEVICE_FOLDABLE); 487 assertThat(nfcAntennaInfo.getAvailableNfcAntennas()).isNotEmpty(); 488 assertThat(nfcAntennaInfo.getAvailableNfcAntennas().get(0).getLocationX()) 489 .isEqualTo(ANTENNA_POS_X[0]); 490 assertThat(nfcAntennaInfo.getAvailableNfcAntennas().get(0).getLocationY()) 491 .isEqualTo(ANTENNA_POS_Y[0]); 492 } 493 494 @Test testGetAntennaInfo_ReadFromSysProp()495 public void testGetAntennaInfo_ReadFromSysProp() throws Exception { 496 enableAndVerify(); 497 when(NfcProperties.info_antpos_X()) 498 .thenReturn(Arrays.stream(ANTENNA_POS_X).boxed().toList()); 499 when(NfcProperties.info_antpos_Y()) 500 .thenReturn(Arrays.stream(ANTENNA_POS_Y).boxed().toList()); 501 when(NfcProperties.info_antpos_device_width()) 502 .thenReturn(Optional.of(ANTENNA_DEVICE_WIDTH)); 503 when(NfcProperties.info_antpos_device_height()) 504 .thenReturn(Optional.of(ANTENNA_DEVICE_HEIGHT)); 505 when(NfcProperties.info_antpos_device_foldable()) 506 .thenReturn(Optional.of(ANTENNA_DEVICE_FOLDABLE)); 507 NfcAntennaInfo nfcAntennaInfo = mNfcService.mNfcAdapter.getNfcAntennaInfo(); 508 assertThat(nfcAntennaInfo).isNotNull(); 509 assertThat(nfcAntennaInfo.getDeviceWidth()).isEqualTo(ANTENNA_DEVICE_WIDTH); 510 assertThat(nfcAntennaInfo.getDeviceHeight()).isEqualTo(ANTENNA_DEVICE_HEIGHT); 511 assertThat(nfcAntennaInfo.isDeviceFoldable()).isEqualTo(ANTENNA_DEVICE_FOLDABLE); 512 assertThat(nfcAntennaInfo.getAvailableNfcAntennas()).isNotEmpty(); 513 assertThat(nfcAntennaInfo.getAvailableNfcAntennas().get(0).getLocationX()) 514 .isEqualTo(ANTENNA_POS_X[0]); 515 assertThat(nfcAntennaInfo.getAvailableNfcAntennas().get(0).getLocationY()) 516 .isEqualTo(ANTENNA_POS_Y[0]); 517 } 518 519 @Test testHandlerMsgRegisterT3tIdentifier()520 public void testHandlerMsgRegisterT3tIdentifier() { 521 Handler handler = mNfcService.getHandler(); 522 Assert.assertNotNull(handler); 523 Message msg = handler.obtainMessage(NfcService.MSG_REGISTER_T3T_IDENTIFIER); 524 msg.obj = "test".getBytes(); 525 handler.handleMessage(msg); 526 verify(mDeviceHost).disableDiscovery(); 527 verify(mDeviceHost).registerT3tIdentifier(any()); 528 verify(mDeviceHost).enableDiscovery(any(), anyBoolean()); 529 Message msgDeregister = handler.obtainMessage(NfcService.MSG_DEREGISTER_T3T_IDENTIFIER); 530 msgDeregister.obj = "test".getBytes(); 531 handler.handleMessage(msgDeregister); 532 verify(mDeviceHost, times(2)).disableDiscovery(); 533 verify(mDeviceHost, times(2)).enableDiscovery(any(), anyBoolean()); 534 } 535 536 @Test testHandlerMsgCommitRouting()537 public void testHandlerMsgCommitRouting() { 538 Handler handler = mNfcService.getHandler(); 539 Assert.assertNotNull(handler); 540 Message msg = handler.obtainMessage(NfcService.MSG_COMMIT_ROUTING); 541 mNfcService.mState = NfcAdapter.STATE_OFF; 542 handler.handleMessage(msg); 543 verify(mDeviceHost, never()).commitRouting(); 544 mNfcService.mState = NfcAdapter.STATE_ON; 545 NfcDiscoveryParameters nfcDiscoveryParameters = mock(NfcDiscoveryParameters.class); 546 when(nfcDiscoveryParameters.shouldEnableDiscovery()).thenReturn(true); 547 mNfcService.mCurrentDiscoveryParameters = nfcDiscoveryParameters; 548 handler.handleMessage(msg); 549 verify(mDeviceHost).commitRouting(); 550 } 551 552 @Test testHandlerMsgMockNdef()553 public void testHandlerMsgMockNdef() { 554 Handler handler = mNfcService.getHandler(); 555 Assert.assertNotNull(handler); 556 Message msg = handler.obtainMessage(NfcService.MSG_MOCK_NDEF); 557 NdefMessage ndefMessage = mock(NdefMessage.class); 558 msg.obj = ndefMessage; 559 handler.handleMessage(msg); 560 verify(mNfcDispatcher).dispatchTag(any()); 561 } 562 563 @Test testInitSoundPool_End()564 public void testInitSoundPool_End() { 565 mNfcService.playSound(SOUND_END); 566 567 verify(mSoundPool, never()).play(mSoundCaptor.capture(), 568 anyFloat(), anyFloat(), anyInt(), anyInt(), anyFloat()); 569 mNfcService.mSoundPool = mSoundPool; 570 mNfcService.playSound(SOUND_END); 571 verify(mSoundPool, atLeastOnce()).play(mSoundCaptor.capture(), 572 anyFloat(), anyFloat(), anyInt(), anyInt(), anyFloat()); 573 Integer value = mSoundCaptor.getValue(); 574 Assert.assertEquals(mNfcService.mEndSound, (int) value); 575 } 576 577 @Test testInitSoundPool_Error()578 public void testInitSoundPool_Error() { 579 mNfcService.playSound(SOUND_ERROR); 580 581 verify(mSoundPool, never()).play(mSoundCaptor.capture(), 582 anyFloat(), anyFloat(), anyInt(), anyInt(), anyFloat()); 583 mNfcService.mSoundPool = mSoundPool; 584 mNfcService.playSound(SOUND_ERROR); 585 verify(mSoundPool, atLeastOnce()).play(mSoundCaptor.capture(), 586 anyFloat(), anyFloat(), anyInt(), anyInt(), anyFloat()); 587 Integer value = mSoundCaptor.getValue(); 588 Assert.assertEquals(mNfcService.mErrorSound, (int) value); 589 } 590 591 @Test testReleaseSoundPool()592 public void testReleaseSoundPool() { 593 mNfcService.mSoundPool = mSoundPool; 594 mNfcService.releaseSoundPool(); 595 Assert.assertNull(mNfcService.mSoundPool); 596 } 597 598 @Test testMsg_Rf_Field_Activated()599 public void testMsg_Rf_Field_Activated() { 600 Handler handler = mNfcService.getHandler(); 601 Assert.assertNotNull(handler); 602 Message msg = handler.obtainMessage(NfcService.MSG_RF_FIELD_ACTIVATED); 603 List<String> userlist = new ArrayList<>(); 604 userlist.add("com.android.nfc"); 605 mNfcService.mNfcEventInstalledPackages.put(1, userlist); 606 mNfcService.mIsSecureNfcEnabled = true; 607 mNfcService.mIsRequestUnlockShowed = false; 608 when(mNfcInjector.isDeviceLocked()).thenReturn(true); 609 handler.handleMessage(msg); 610 verify(mApplication).sendBroadcastAsUser(mIntentArgumentCaptor.capture(), any()); 611 Intent intent = mIntentArgumentCaptor.getValue(); 612 Assert.assertNotNull(intent); 613 Assert.assertEquals(NfcService.ACTION_RF_FIELD_ON_DETECTED, intent.getAction()); 614 verify(mApplication).sendBroadcast(mIntentArgumentCaptor.capture()); 615 intent = mIntentArgumentCaptor.getValue(); 616 Assert.assertEquals(NfcAdapter.ACTION_REQUIRE_UNLOCK_FOR_NFC, intent.getAction()); 617 } 618 619 @Test testMsg_Rf_Field_Deactivated()620 public void testMsg_Rf_Field_Deactivated() { 621 Handler handler = mNfcService.getHandler(); 622 Assert.assertNotNull(handler); 623 Message msg = handler.obtainMessage(NfcService.MSG_RF_FIELD_DEACTIVATED); 624 List<String> userlist = new ArrayList<>(); 625 userlist.add("com.android.nfc"); 626 mNfcService.mNfcEventInstalledPackages.put(1, userlist); 627 handler.handleMessage(msg); 628 verify(mApplication).sendBroadcastAsUser(mIntentArgumentCaptor.capture(), any()); 629 Intent intent = mIntentArgumentCaptor.getValue(); 630 Assert.assertNotNull(intent); 631 Assert.assertEquals(NfcService.ACTION_RF_FIELD_OFF_DETECTED, intent.getAction()); 632 } 633 634 @Test testMsg_Tag_Debounce()635 public void testMsg_Tag_Debounce() { 636 Handler handler = mNfcService.getHandler(); 637 Assert.assertNotNull(handler); 638 Message msg = handler.obtainMessage(NfcService.MSG_TAG_DEBOUNCE); 639 handler.handleMessage(msg); 640 Assert.assertEquals(INVALID_NATIVE_HANDLE, mNfcService.mDebounceTagNativeHandle); 641 } 642 643 @Test testMsg_Apply_Screen_State()644 public void testMsg_Apply_Screen_State() { 645 Handler handler = mNfcService.getHandler(); 646 Assert.assertNotNull(handler); 647 Message msg = handler.obtainMessage(NfcService.MSG_APPLY_SCREEN_STATE); 648 msg.obj = ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED; 649 handler.handleMessage(msg); 650 verify(mDeviceHost).doSetScreenState(anyInt(), anyBoolean()); 651 } 652 653 @Test testMsg_Transaction_Event_Cardemulation_Occurred()654 public void testMsg_Transaction_Event_Cardemulation_Occurred() { 655 CardEmulationManager cardEmulationManager = mock(CardEmulationManager.class); 656 when(cardEmulationManager.getRegisteredAidCategory(anyString())). 657 thenReturn(CardEmulation.CATEGORY_PAYMENT); 658 mNfcService.mCardEmulationManager = cardEmulationManager; 659 Handler handler = mNfcService.getHandler(); 660 Assert.assertNotNull(handler); 661 Message msg = handler.obtainMessage(NfcService.MSG_TRANSACTION_EVENT); 662 byte[][] data = {NfcService.hexStringToBytes("F00102030405"), 663 NfcService.hexStringToBytes("02FE00010002"), 664 NfcService.hexStringToBytes("03000000")}; 665 msg.obj = data; 666 handler.handleMessage(msg); 667 ExtendedMockito.verify(() -> NfcStatsLog.write(NfcStatsLog.NFC_CARDEMULATION_OCCURRED, 668 NfcStatsLog 669 .NFC_CARDEMULATION_OCCURRED__CATEGORY__OFFHOST_PAYMENT, 670 new String(NfcService.hexStringToBytes("03000000"), "UTF-8"), 671 -1)); 672 } 673 674 @Test testMsg_Transaction_Event()675 public void testMsg_Transaction_Event() throws RemoteException { 676 CardEmulationManager cardEmulationManager = mock(CardEmulationManager.class); 677 when(cardEmulationManager.getRegisteredAidCategory(anyString())). 678 thenReturn(CardEmulation.CATEGORY_PAYMENT); 679 mNfcService.mCardEmulationManager = cardEmulationManager; 680 Handler handler = mNfcService.getHandler(); 681 Assert.assertNotNull(handler); 682 Message msg = handler.obtainMessage(NfcService.MSG_TRANSACTION_EVENT); 683 byte[][] data = {NfcService.hexStringToBytes("F00102030405"), 684 NfcService.hexStringToBytes("02FE00010002"), 685 NfcService.hexStringToBytes("03000000")}; 686 msg.obj = data; 687 List<String> userlist = new ArrayList<>(); 688 userlist.add("com.android.nfc"); 689 mNfcService.mNfcEventInstalledPackages.put(1, userlist); 690 ISecureElementService iSecureElementService = mock(ISecureElementService.class); 691 IBinder iBinder = mock(IBinder.class); 692 when(iSecureElementService.asBinder()).thenReturn(iBinder); 693 boolean[] nfcAccess = {true}; 694 when(iSecureElementService.isNfcEventAllowed(anyString(), any(), any(), anyInt())) 695 .thenReturn(nfcAccess); 696 when(mNfcInjector.connectToSeService()).thenReturn(iSecureElementService); 697 handler.handleMessage(msg); 698 verify(mApplication).sendBroadcastAsUser(mIntentArgumentCaptor.capture(), 699 any(), any(), any()); 700 } 701 702 @Test testMsg_Preferred_Payment_Changed()703 public void testMsg_Preferred_Payment_Changed() 704 throws RemoteException, PackageManager.NameNotFoundException { 705 Handler handler = mNfcService.getHandler(); 706 Assert.assertNotNull(handler); 707 Message msg = handler.obtainMessage(NfcService.MSG_PREFERRED_PAYMENT_CHANGED); 708 msg.obj = 1; 709 List<String> packagesList = new ArrayList<>(); 710 packagesList.add("com.android.nfc"); 711 packagesList.add("com.sample.nfc"); 712 mNfcService.mNfcPreferredPaymentChangedInstalledPackages.put(1, packagesList); 713 ISecureElementService iSecureElementService = mock(ISecureElementService.class); 714 IBinder iBinder = mock(IBinder.class); 715 when(iSecureElementService.asBinder()).thenReturn(iBinder); 716 when(iSecureElementService.getReaders()).thenReturn(new String[]{"com.android.nfc"}); 717 when(iSecureElementService.isNfcEventAllowed(anyString(), isNull(), any(), anyInt())) 718 .thenReturn(new boolean[]{true}); 719 boolean[] nfcAccess = {true}; 720 when(iSecureElementService.isNfcEventAllowed(anyString(), any(), any(), anyInt())) 721 .thenReturn(nfcAccess); 722 when(mNfcInjector.connectToSeService()).thenReturn(iSecureElementService); 723 PackageInfo info = mock(PackageInfo.class); 724 ApplicationInfo applicationInfo = mock(ApplicationInfo.class); 725 applicationInfo.flags = 1; 726 info.applicationInfo = applicationInfo; 727 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(info); 728 handler.handleMessage(msg); 729 verify(mApplication, times(2)) 730 .sendBroadcastAsUser(mIntentArgumentCaptor.capture(), any()); 731 Intent intent = mIntentArgumentCaptor.getValue(); 732 Assert.assertEquals(ACTION_PREFERRED_PAYMENT_CHANGED, intent.getAction()); 733 } 734 735 @Test testMSG_NDEF_TAG()736 public void testMSG_NDEF_TAG() { 737 Handler handler = mNfcService.getHandler(); 738 Assert.assertNotNull(handler); 739 Message msg = handler.obtainMessage(NfcService.MSG_NDEF_TAG); 740 mNfcService.mState = NfcAdapter.STATE_ON; 741 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 742 when(tagEndpoint.getConnectedTechnology()).thenReturn(TagTechnology.NDEF); 743 NdefMessage ndefMessage = mock(NdefMessage.class); 744 when(tagEndpoint.findAndReadNdef()).thenReturn(ndefMessage); 745 msg.obj = tagEndpoint; 746 handler.handleMessage(msg); 747 verify(tagEndpoint, atLeastOnce()).startPresenceChecking(anyInt(), any()); 748 } 749 750 @Test testMsg_Ndef_Tag_Wlc_Enabled()751 public void testMsg_Ndef_Tag_Wlc_Enabled() { 752 Handler handler = mNfcService.getHandler(); 753 Assert.assertNotNull(handler); 754 Message msg = handler.obtainMessage(NfcService.MSG_NDEF_TAG); 755 mNfcService.mState = NfcAdapter.STATE_ON; 756 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 757 when(tagEndpoint.getConnectedTechnology()).thenReturn(TagTechnology.NDEF); 758 when(tagEndpoint.getUid()).thenReturn(NfcService 759 .hexStringToBytes("0x040000010100000000000000")); 760 when(tagEndpoint.getTechList()).thenReturn(new int[]{Ndef.NDEF}); 761 when(tagEndpoint.getTechExtras()).thenReturn(new Bundle[]{}); 762 when(tagEndpoint.getHandle()).thenReturn(1); 763 NdefMessage ndefMessage = mock(NdefMessage.class); 764 when(tagEndpoint.findAndReadNdef()).thenReturn(ndefMessage); 765 msg.obj = tagEndpoint; 766 mNfcService.mIsWlcEnabled = true; 767 mNfcService.mIsRWCapable = true; 768 handler.handleMessage(msg); 769 verify(tagEndpoint, atLeastOnce()).startPresenceChecking(anyInt(), any()); 770 ArgumentCaptor<Tag> tagCaptor = ArgumentCaptor 771 .forClass(Tag.class); 772 verify(mNfcDispatcher).dispatchTag(tagCaptor.capture()); 773 Tag tag = tagCaptor.getValue(); 774 Assert.assertNotNull(tag); 775 Assert.assertEquals("android.nfc.tech.Ndef", tag.getTechList()[0]); 776 } 777 778 @Test testMsg_Clear_Routing_Table()779 public void testMsg_Clear_Routing_Table() { 780 Handler handler = mNfcService.getHandler(); 781 Assert.assertNotNull(handler); 782 Message msg = handler.obtainMessage(NfcService.MSG_CLEAR_ROUTING_TABLE); 783 mNfcService.mState = NfcAdapter.STATE_ON; 784 msg.obj = 1; 785 handler.handleMessage(msg); 786 ArgumentCaptor<Integer> flagCaptor = ArgumentCaptor.forClass(Integer.class); 787 verify(mDeviceHost).clearRoutingEntry(flagCaptor.capture()); 788 int flag = flagCaptor.getValue(); 789 Assert.assertEquals(1, flag); 790 } 791 792 @Test testMsg_Update_Isodep_Protocol_Route()793 public void testMsg_Update_Isodep_Protocol_Route() { 794 Handler handler = mNfcService.getHandler(); 795 mNfcService.mState = NfcAdapter.STATE_ON; 796 Assert.assertNotNull(handler); 797 Message msg = handler.obtainMessage(NfcService.MSG_UPDATE_ISODEP_PROTOCOL_ROUTE); 798 msg.obj = 1; 799 handler.handleMessage(msg); 800 ArgumentCaptor<Integer> flagCaptor = ArgumentCaptor.forClass(Integer.class); 801 verify(mDeviceHost).setIsoDepProtocolRoute(flagCaptor.capture()); 802 int flag = flagCaptor.getValue(); 803 Assert.assertEquals(1, flag); 804 } 805 806 @Test testMsg_Update_Technology_Abf_Route()807 public void testMsg_Update_Technology_Abf_Route() { 808 Handler handler = mNfcService.getHandler(); 809 Assert.assertNotNull(handler); 810 mNfcService.mState = NfcAdapter.STATE_ON; 811 Message msg = handler.obtainMessage(NfcService.MSG_UPDATE_TECHNOLOGY_ABF_ROUTE); 812 msg.arg1 = 1; 813 msg.arg2 = 2; 814 handler.handleMessage(msg); 815 ArgumentCaptor<Integer> flagCaptor = ArgumentCaptor.forClass(Integer.class); 816 ArgumentCaptor<Integer> flagCaptor2 = ArgumentCaptor.forClass(Integer.class); 817 verify(mDeviceHost).setTechnologyABFRoute(flagCaptor.capture(), flagCaptor2.capture()); 818 int flag = flagCaptor.getValue(); 819 Assert.assertEquals(1, flag); 820 int flag2 = flagCaptor2.getValue(); 821 Assert.assertEquals(2, flag2); 822 } 823 824 @Test testDirectBootAware()825 public void testDirectBootAware() throws Exception { 826 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 827 when(mFeatureFlags.enableDirectBootAware()).thenReturn(true); 828 mNfcService = new NfcService(mApplication, mNfcInjector); 829 mLooper.dispatchAll(); 830 verify(mNfcInjector).makeDeviceHost(mDeviceHostListener.capture()); 831 verify(mApplication).registerReceiverForAllUsers( 832 mGlobalReceiver.capture(), 833 argThat(intent -> intent.hasAction(Intent.ACTION_USER_UNLOCKED)), any(), any()); 834 verify(mDeviceHost).initialize(); 835 836 clearInvocations(mApplication, mPreferences, mPreferencesEditor); 837 Context ceContext = mock(Context.class); 838 when(mApplication.createCredentialProtectedStorageContext()).thenReturn(ceContext); 839 when(ceContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mPreferences); 840 doAnswer(new Answer() { 841 @Override 842 public Map<String, ?> answer(InvocationOnMock invocation) throws Throwable { 843 Map<String, Object> prefMap = Map.of(PREF_NFC_ON, true); 844 return prefMap; 845 } 846 }).when(mPreferences).getAll(); 847 when(mApplication.moveSharedPreferencesFrom(ceContext, NfcService.PREF)).thenReturn(true); 848 when(mApplication.moveSharedPreferencesFrom(ceContext, NfcService.PREF_TAG_APP_LIST)) 849 .thenReturn(true); 850 mGlobalReceiver.getValue().onReceive(mApplication, new Intent(Intent.ACTION_USER_UNLOCKED)); 851 verify(mApplication).moveSharedPreferencesFrom(ceContext, NfcService.PREF); 852 verify(mApplication).getSharedPreferences(eq(NfcService.PREF), anyInt()); 853 verify(mPreferences).edit(); 854 verify(mPreferencesEditor).putBoolean(NfcService.PREF_MIGRATE_TO_DE_COMPLETE, true); 855 verify(mPreferencesEditor).apply(); 856 } 857 858 @Test testAllowOemOnTagDispatchCallback()859 public void testAllowOemOnTagDispatchCallback() throws Exception { 860 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 861 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 862 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 863 Handler handler = mNfcService.getHandler(); 864 Assert.assertNotNull(handler); 865 Message msg = handler.obtainMessage(NfcService.MSG_NDEF_TAG); 866 mNfcService.mState = NfcAdapter.STATE_ON; 867 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 868 when(tagEndpoint.getConnectedTechnology()).thenReturn(TagTechnology.NDEF); 869 when(tagEndpoint.getUid()).thenReturn(NfcService 870 .hexStringToBytes("0x040000010100000000000000")); 871 when(tagEndpoint.getTechList()).thenReturn(new int[]{Ndef.NDEF}); 872 when(tagEndpoint.getTechExtras()).thenReturn(new Bundle[]{}); 873 when(tagEndpoint.getHandle()).thenReturn(1); 874 NdefMessage ndefMessage = mock(NdefMessage.class); 875 when(tagEndpoint.findAndReadNdef()).thenReturn(ndefMessage); 876 msg.obj = tagEndpoint; 877 mNfcService.mIsWlcEnabled = true; 878 mNfcService.mIsRWCapable = true; 879 handler.handleMessage(msg); 880 verify(tagEndpoint, atLeastOnce()).startPresenceChecking(anyInt(), any()); 881 ArgumentCaptor<Tag> tagCaptor = ArgumentCaptor 882 .forClass(Tag.class); 883 verify(mNfcDispatcher).dispatchTag(tagCaptor.capture()); 884 Tag tag = tagCaptor.getValue(); 885 Assert.assertNotNull(tag); 886 Assert.assertEquals("android.nfc.tech.Ndef", tag.getTechList()[0]); 887 888 doAnswer(new Answer() { 889 @Override 890 public Void answer(InvocationOnMock invocation) throws Throwable { 891 ResultReceiver r = invocation.getArgument(0); 892 r.send(1, null); 893 return null; 894 } 895 }).when(callback).onTagDispatch(any(ResultReceiver.class)); 896 mContentObserver.onChange(true); 897 ArgumentCaptor<ResultReceiver> receiverArgumentCaptor = ArgumentCaptor 898 .forClass(ResultReceiver.class); 899 verify(callback).onTagDispatch(receiverArgumentCaptor.capture()); 900 ResultReceiver resultReceiver = receiverArgumentCaptor.getValue(); 901 Assert.assertNotNull(resultReceiver); 902 } 903 904 @Test testAllowOemOnNdefReadCallback()905 public void testAllowOemOnNdefReadCallback() throws Exception { 906 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 907 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 908 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 909 Handler handler = mNfcService.getHandler(); 910 Assert.assertNotNull(handler); 911 Message msg = handler.obtainMessage(NfcService.MSG_NDEF_TAG); 912 mNfcService.mState = NfcAdapter.STATE_ON; 913 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 914 when(tagEndpoint.getConnectedTechnology()).thenReturn(TagTechnology.NDEF); 915 when(tagEndpoint.getUid()).thenReturn(NfcService 916 .hexStringToBytes("0x040000010100000000000000")); 917 when(tagEndpoint.getTechList()).thenReturn(new int[]{Ndef.NDEF}); 918 when(tagEndpoint.getTechExtras()).thenReturn(new Bundle[]{}); 919 when(tagEndpoint.getHandle()).thenReturn(1); 920 NdefMessage ndefMessage = mock(NdefMessage.class); 921 when(tagEndpoint.findAndReadNdef()).thenReturn(ndefMessage); 922 msg.obj = tagEndpoint; 923 mNfcService.mIsWlcEnabled = true; 924 mNfcService.mIsRWCapable = true; 925 handler.handleMessage(msg); 926 verify(tagEndpoint, atLeastOnce()).startPresenceChecking(anyInt(), any()); 927 ArgumentCaptor<Tag> tagCaptor = ArgumentCaptor 928 .forClass(Tag.class); 929 verify(mNfcDispatcher).dispatchTag(tagCaptor.capture()); 930 Tag tag = tagCaptor.getValue(); 931 Assert.assertNotNull(tag); 932 Assert.assertEquals("android.nfc.tech.Ndef", tag.getTechList()[0]); 933 934 doAnswer(new Answer() { 935 @Override 936 public Void answer(InvocationOnMock invocation) throws Throwable { 937 ResultReceiver r = invocation.getArgument(0); 938 r.send(1, null); 939 return null; 940 } 941 }).when(callback).onNdefRead(any(ResultReceiver.class)); 942 mContentObserver.onChange(true); 943 ArgumentCaptor<ResultReceiver> receiverArgumentCaptor = ArgumentCaptor 944 .forClass(ResultReceiver.class); 945 verify(callback).onNdefRead(receiverArgumentCaptor.capture()); 946 ResultReceiver resultReceiver = receiverArgumentCaptor.getValue(); 947 Assert.assertNotNull(resultReceiver); 948 } 949 950 @Test testAllowOemOnApplyRoutingCallback()951 public void testAllowOemOnApplyRoutingCallback() throws Exception { 952 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 953 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 954 mNfcService.mState = NfcAdapter.STATE_ON; 955 INfcUnlockHandler binder = mock(INfcUnlockHandler.class); 956 mNfcService.mNfcAdapter.removeNfcUnlockHandler(binder); 957 958 doAnswer(new Answer() { 959 @Override 960 public Void answer(InvocationOnMock invocation) throws Throwable { 961 ResultReceiver r = invocation.getArgument(0); 962 r.send(1, null); 963 return null; 964 } 965 }).when(callback).onApplyRouting(any(ResultReceiver.class)); 966 mContentObserver.onChange(true); 967 ArgumentCaptor<ResultReceiver> receiverArgumentCaptor = ArgumentCaptor 968 .forClass(ResultReceiver.class); 969 verify(callback).onApplyRouting(receiverArgumentCaptor.capture()); 970 ResultReceiver resultReceiver = receiverArgumentCaptor.getValue(); 971 Assert.assertNotNull(resultReceiver); 972 } 973 974 @Test testThermalStatusChangeListener()975 public void testThermalStatusChangeListener() { 976 Assert.assertNotNull(mPowerManager); 977 ArgumentCaptor<PowerManager.OnThermalStatusChangedListener> argumentCaptor = 978 ArgumentCaptor.forClass(PowerManager.OnThermalStatusChangedListener.class); 979 verify(mPowerManager).addThermalStatusListener(any(), argumentCaptor.capture()); 980 PowerManager.OnThermalStatusChangedListener changedListener = 981 argumentCaptor.getValue(); 982 Assert.assertNotNull(changedListener); 983 changedListener.onThermalStatusChanged(PowerManager.THERMAL_STATUS_MODERATE); 984 changedListener.onThermalStatusChanged(PowerManager.THERMAL_STATUS_SEVERE); 985 changedListener.onThermalStatusChanged(PowerManager.THERMAL_STATUS_CRITICAL); 986 changedListener.onThermalStatusChanged(0); 987 } 988 989 @Test testClearRoutingTable()990 public void testClearRoutingTable() { 991 mNfcService.mState = NfcAdapter.STATE_ON; 992 mNfcService.clearRoutingTable(1); 993 mLooper.dispatchAll(); 994 ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class); 995 verify(mDeviceHost).clearRoutingEntry(captor.capture()); 996 int flag = captor.getValue(); 997 Assert.assertEquals(1, flag); 998 } 999 1000 @Test testDeregisterT3tIdentifier()1001 public void testDeregisterT3tIdentifier() { 1002 NfcDiscoveryParameters nfcDiscoveryParameters = mock(NfcDiscoveryParameters.class); 1003 when(nfcDiscoveryParameters.shouldEnableDiscovery()).thenReturn(true); 1004 mNfcService.mCurrentDiscoveryParameters = nfcDiscoveryParameters; 1005 mNfcService.deregisterT3tIdentifier("02FE", "02FEC1DE32456789", "F0010203"); 1006 mLooper.dispatchAll(); 1007 verify(mDeviceHost).disableDiscovery(); 1008 ArgumentCaptor<byte[]> t3tIdentifierByteArray = ArgumentCaptor.forClass(byte[].class); 1009 verify(mDeviceHost).deregisterT3tIdentifier(t3tIdentifierByteArray.capture()); 1010 byte[] data = t3tIdentifierByteArray.getValue(); 1011 Assert.assertNotNull(data); 1012 String msg = new String(data, StandardCharsets.UTF_8); 1013 Assert.assertNotNull(msg); 1014 verify(mDeviceHost).enableDiscovery(any(), anyBoolean()); 1015 } 1016 1017 @Test testFindAndRemoveObject()1018 public void testFindAndRemoveObject() { 1019 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1020 when(tagEndpoint.getHandle()).thenReturn(1); 1021 mNfcService.registerTagObject(tagEndpoint); 1022 DeviceHost.TagEndpoint device = (DeviceHost.TagEndpoint) mNfcService.mObjectMap.get(1); 1023 Assert.assertNotNull(device); 1024 Assert.assertEquals(tagEndpoint, device); 1025 mNfcService.findAndRemoveObject(1); 1026 Object obj = mNfcService.mObjectMap.get(1); 1027 Assert.assertNull(obj); 1028 } 1029 1030 @Test testDisplayManagerCallback()1031 public void testDisplayManagerCallback() { 1032 ArgumentCaptor<DisplayManager.DisplayListener> displayListenerArgumentCaptor = 1033 ArgumentCaptor.forClass(DisplayManager.DisplayListener.class); 1034 ArgumentCaptor<NfcService.NfcServiceHandler> nfcServiceHandlerArgumentCaptor = 1035 ArgumentCaptor.forClass(NfcService.NfcServiceHandler.class); 1036 verify(mDisplayManager).registerDisplayListener(displayListenerArgumentCaptor.capture(), 1037 nfcServiceHandlerArgumentCaptor.capture()); 1038 DisplayManager.DisplayListener displayListener = displayListenerArgumentCaptor.getValue(); 1039 Assert.assertNotNull(displayListener); 1040 NfcService.NfcServiceHandler handler = nfcServiceHandlerArgumentCaptor.getValue(); 1041 Assert.assertNotNull(handler); 1042 displayListener.onDisplayAdded(Display.DEFAULT_DISPLAY); 1043 displayListener.onDisplayRemoved(Display.DEFAULT_DISPLAY); 1044 mNfcService.mIsWlcCapable = false; 1045 when(mScreenStateHelper.checkScreenState(anyBoolean())) 1046 .thenReturn(ScreenStateHelper.SCREEN_STATE_ON_LOCKED); 1047 mNfcService.mScreenState = ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED; 1048 displayListener.onDisplayChanged(Display.DEFAULT_DISPLAY); 1049 mLooper.dispatchAll(); 1050 Assert.assertFalse(handler.hasMessages(NfcService.MSG_DELAY_POLLING)); 1051 Assert.assertFalse(mNfcService.mIsRequestUnlockShowed); 1052 verify(mDeviceHost).doSetScreenState(anyInt(), anyBoolean()); 1053 } 1054 1055 @Test testThermalStatusListener()1056 public void testThermalStatusListener() { 1057 Assert.assertNotNull(mPowerManager); 1058 ArgumentCaptor<PowerManager.OnThermalStatusChangedListener> argumentCaptor = 1059 ArgumentCaptor.forClass(PowerManager.OnThermalStatusChangedListener.class); 1060 verify(mPowerManager).addThermalStatusListener(any(), argumentCaptor.capture()); 1061 PowerManager.OnThermalStatusChangedListener thermalStatusChangedListener = 1062 argumentCaptor.getValue(); 1063 Assert.assertNotNull(thermalStatusChangedListener); 1064 thermalStatusChangedListener.onThermalStatusChanged(PowerManager.THERMAL_STATUS_MODERATE); 1065 thermalStatusChangedListener.onThermalStatusChanged(PowerManager.THERMAL_STATUS_SEVERE); 1066 thermalStatusChangedListener.onThermalStatusChanged(PowerManager.THERMAL_STATUS_CRITICAL); 1067 thermalStatusChangedListener.onThermalStatusChanged(PowerManager.THERMAL_STATUS_SHUTDOWN); 1068 } 1069 1070 @Test testGetAppName()1071 public void testGetAppName() throws RemoteException, PackageManager.NameNotFoundException { 1072 String[] packages = {"com.android.test1"}; 1073 when(mResources.getStringArray(R.array.nfc_allow_list)).thenReturn(packages); 1074 mNfcService.mNfcAdapter.enable(PKG_NAME); 1075 ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class); 1076 verify(mPackageManager).getApplicationInfoAsUser(stringArgumentCaptor.capture(), anyInt(), 1077 any()); 1078 assertThat(PKG_NAME).isEqualTo(stringArgumentCaptor.getValue()); 1079 verify(mPackageManager, atLeastOnce()).getApplicationLabel(any()); 1080 } 1081 1082 @Test testFindObject()1083 public void testFindObject() { 1084 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1085 when(tagEndpoint.getHandle()).thenReturn(1); 1086 mNfcService.registerTagObject(tagEndpoint); 1087 DeviceHost.TagEndpoint device = (DeviceHost.TagEndpoint) mNfcService.mObjectMap.get(1); 1088 Assert.assertNotNull(device); 1089 Assert.assertEquals(tagEndpoint, device); 1090 Object obj = mNfcService.findObject(1); 1091 Assert.assertNotNull(obj); 1092 Object object = mNfcService.mObjectMap.get(1); 1093 Assert.assertNotNull(object); 1094 assertThat(obj).isEqualTo(object); 1095 } 1096 1097 @Test testGetEnabledUserIds()1098 public void testGetEnabledUserIds() { 1099 when(mPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(true); 1100 Assert.assertTrue(mNfcService.getNfcOnSetting()); 1101 when(mNfcInjector.isSatelliteModeOn()).thenReturn(false); 1102 when(mUserRestrictions.getBoolean(UserManager.DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO)) 1103 .thenReturn(false); 1104 NfcService.sIsNfcRestore = true; 1105 UserHandle uh = mock(UserHandle.class); 1106 when(uh.getIdentifier()).thenReturn(1); 1107 List<UserHandle> luh = new ArrayList<>(); 1108 luh.add(uh); 1109 when(mUserManager.getEnabledProfiles()).thenReturn(luh); 1110 mNfcService.enableNfc(); 1111 verify(mPreferences).edit(); 1112 verify(mPreferencesEditor).putBoolean(PREF_NFC_ON, true); 1113 verify(mPreferencesEditor, atLeastOnce()).apply(); 1114 verify(mBackupManager).dataChanged(); 1115 mLooper.dispatchAll(); 1116 verify(mUserManager, atLeastOnce()).getEnabledProfiles(); 1117 } 1118 1119 @Test testGetLfT3tMax()1120 public void testGetLfT3tMax() { 1121 int lfT3t = mNfcService.getLfT3tMax(); 1122 assertThat(lfT3t).isEqualTo(0); 1123 when(mDeviceHost.getLfT3tMax()).thenReturn(100); 1124 lfT3t = mNfcService.getLfT3tMax(); 1125 assertThat(lfT3t).isEqualTo(100); 1126 verify(mDeviceHost, atLeastOnce()).getLfT3tMax(); 1127 } 1128 1129 @Test testGetNfcPollTech()1130 public void testGetNfcPollTech() { 1131 int pollTech = mNfcService.getNfcPollTech(); 1132 assertThat(pollTech).isEqualTo(0); 1133 when(mPreferences.getInt(NfcService.PREF_POLL_TECH, NfcService.DEFAULT_POLL_TECH)) 1134 .thenReturn(NfcService.DEFAULT_LISTEN_TECH); 1135 pollTech = mNfcService.getNfcPollTech(); 1136 assertThat(pollTech).isEqualTo(0xf); 1137 verify(mPreferences, atLeastOnce()).getInt(anyString(), anyInt()); 1138 } 1139 1140 @Test testIsPackageInstalled()1141 public void testIsPackageInstalled() { 1142 when(mPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(true); 1143 String jsonString = "{}"; 1144 when(mPreferences.getString(anyString(), anyString())).thenReturn(jsonString); 1145 Assert.assertTrue(mNfcService.getNfcOnSetting()); 1146 when(mNfcInjector.isSatelliteModeOn()).thenReturn(false); 1147 when(mUserRestrictions.getBoolean(UserManager.DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO)) 1148 .thenReturn(false); 1149 NfcService.sIsNfcRestore = true; 1150 UserHandle uh = mock(UserHandle.class); 1151 when(uh.getIdentifier()).thenReturn(1); 1152 List<UserHandle> luh = new ArrayList<>(); 1153 luh.add(uh); 1154 when(mUserManager.getEnabledProfiles()).thenReturn(luh); 1155 mNfcService.enableNfc(); 1156 verify(mPreferences).edit(); 1157 verify(mPreferencesEditor).putBoolean(PREF_NFC_ON, true); 1158 verify(mPreferencesEditor, atLeastOnce()).apply(); 1159 verify(mBackupManager).dataChanged(); 1160 mLooper.dispatchAll(); 1161 verify(mUserManager, atLeastOnce()).getEnabledProfiles(); 1162 verify(mApplication, atLeastOnce()).createContextAsUser(any(), anyInt()); 1163 } 1164 1165 @Test testIsSecureNfcEnabled()1166 public void testIsSecureNfcEnabled() { 1167 mNfcService.mIsSecureNfcEnabled = true; 1168 boolean isSecureNfcEnabled = mNfcService.isSecureNfcEnabled(); 1169 assertThat(isSecureNfcEnabled).isTrue(); 1170 mNfcService.mIsSecureNfcEnabled = false; 1171 isSecureNfcEnabled = mNfcService.isSecureNfcEnabled(); 1172 assertThat(isSecureNfcEnabled).isFalse(); 1173 } 1174 1175 @Test testIsTagPresent()1176 public void testIsTagPresent() throws RemoteException { 1177 boolean isTagPresent = mNfcService.mNfcAdapter.isTagPresent(); 1178 assertThat(isTagPresent).isFalse(); 1179 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1180 when(tagEndpoint.isPresent()).thenReturn(true); 1181 mNfcService.mObjectMap.put(1, tagEndpoint); 1182 isTagPresent = mNfcService.mNfcAdapter.isTagPresent(); 1183 assertThat(isTagPresent).isTrue(); 1184 1185 } 1186 1187 @Test testOnObserveModeStateChanged()1188 public void testOnObserveModeStateChanged() { 1189 when(Flags.postCallbacks()).thenReturn(true); 1190 mNfcService.onObserveModeStateChanged(true); 1191 mLooper.dispatchAll(); 1192 verify(mCardEmulationManager, atLeastOnce()).onObserveModeStateChange(anyBoolean()); 1193 when(Flags.postCallbacks()).thenReturn(false); 1194 mNfcService.onObserveModeStateChanged(false); 1195 verify(mCardEmulationManager, atLeastOnce()).onObserveModeStateChange(anyBoolean()); 1196 } 1197 1198 @Test testOnPollingLoopDetected()1199 public void testOnPollingLoopDetected() { 1200 PollingFrame pollingFrame = mock(PollingFrame.class); 1201 List<PollingFrame> frames = new ArrayList<>(); 1202 frames.add(pollingFrame); 1203 when(Flags.postCallbacks()).thenReturn(true); 1204 mNfcService.onPollingLoopDetected(frames); 1205 mLooper.dispatchAll(); 1206 ArgumentCaptor<List<PollingFrame>> listArgumentCaptor = ArgumentCaptor.forClass(List.class); 1207 verify(mCardEmulationManager).onPollingLoopDetected(listArgumentCaptor.capture()); 1208 assertThat(frames).isEqualTo(listArgumentCaptor.getValue()); 1209 when(Flags.postCallbacks()).thenReturn(false); 1210 mNfcService.onPollingLoopDetected(frames); 1211 verify(mCardEmulationManager, atLeastOnce()).onPollingLoopDetected(listArgumentCaptor.capture()); 1212 assertThat(frames).isEqualTo(listArgumentCaptor.getValue()); 1213 } 1214 1215 @Test testOnVendorSpecificEvent()1216 public void testOnVendorSpecificEvent() throws RemoteException { 1217 INfcVendorNciCallback callback = mock(INfcVendorNciCallback.class); 1218 mNfcService.mNfcAdapter.registerVendorExtensionCallback(callback); 1219 verify(mDeviceHost).enableVendorNciNotifications(true); 1220 mNfcService.onVendorSpecificEvent(1, 2, "test".getBytes()); 1221 mLooper.dispatchAll(); 1222 verify(callback).onVendorNotificationReceived(anyInt(), anyInt(), any()); 1223 } 1224 1225 @Test testOnHostCardEmulationActivated()1226 public void testOnHostCardEmulationActivated() throws RemoteException { 1227 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 1228 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 1229 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 1230 verify(callback).onCardEmulationActivated(anyBoolean()); 1231 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 1232 mNfcService.onHostCardEmulationActivated(1); 1233 verify(mCardEmulationManager).onHostCardEmulationActivated(anyInt()); 1234 verify(mNfcEventLog, times(2)).logEvent(any()); 1235 } 1236 1237 @Test testOnHostCardEmulationDeactivated()1238 public void testOnHostCardEmulationDeactivated() throws RemoteException { 1239 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 1240 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 1241 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 1242 verify(callback).onCardEmulationActivated(false); 1243 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 1244 mNfcService.onHostCardEmulationDeactivated(1); 1245 verify(mCardEmulationManager).onHostCardEmulationDeactivated(anyInt()); 1246 verify(mNfcEventLog, times(2)).logEvent(any()); 1247 } 1248 1249 @Test testOnEeUpdated()1250 public void testOnEeUpdated() { 1251 mNfcService.onEeUpdated(); 1252 mLooper.dispatchAll(); 1253 Assert.assertEquals(0, mNfcService.mScreenState); 1254 } 1255 1256 @Test testOnHwErrorReported()1257 public void testOnHwErrorReported() { 1258 when(mPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(true); 1259 Assert.assertTrue(mNfcService.getNfcOnSetting()); 1260 when(mNfcInjector.isSatelliteModeOn()).thenReturn(false); 1261 when(mUserRestrictions.getBoolean(UserManager.DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO)) 1262 .thenReturn(false); 1263 NfcService.sIsNfcRestore = true; 1264 mNfcService.mState = NfcAdapter.STATE_OFF; 1265 mNfcService.onHwErrorReported(); 1266 verify(mApplication).unregisterReceiver(any()); 1267 assertThat(mNfcService.mIsRecovering).isTrue(); 1268 mLooper.dispatchAll(); 1269 verify(mUserManager, atLeastOnce()).getEnabledProfiles(); 1270 } 1271 1272 @Test testOnNfcTransactionEvent()1273 public void testOnNfcTransactionEvent() throws RemoteException { 1274 ISecureElementService iSecureElementService = mock(ISecureElementService.class); 1275 IBinder iBinder = mock(IBinder.class); 1276 when(iSecureElementService.asBinder()).thenReturn(iBinder); 1277 boolean[] nfcAccess = {true}; 1278 when(iSecureElementService.isNfcEventAllowed(anyString(), any(), any(), anyInt())) 1279 .thenReturn(nfcAccess); 1280 when(mNfcInjector.connectToSeService()).thenReturn(iSecureElementService); 1281 List<String> packages = new ArrayList<>(); 1282 packages.add("com.android.test"); 1283 mNfcService.mNfcEventInstalledPackages.put(1, packages); 1284 when(mCardEmulationManager.getRegisteredAidCategory(anyString())) 1285 .thenReturn(CardEmulation.CATEGORY_PAYMENT); 1286 byte[] aid = { 0x0A, 0x00, 0x00, 0x00 }; 1287 byte[] data = { 0x12, 0x34, 0x56, 0x78, 0x78 }; 1288 mNfcService.onNfcTransactionEvent(aid, data, "SecureElement1"); 1289 mLooper.dispatchAll(); 1290 verify(mCardEmulationManager).onOffHostAidSelected(); 1291 verify(mPackageManager).queryBroadcastReceiversAsUser(any(), anyInt(), any()); 1292 verify(mApplication).sendBroadcastAsUser(any(), any(), isNull(), any()); 1293 } 1294 1295 @Test testOnRemoteEndpointDiscovered()1296 public void testOnRemoteEndpointDiscovered() { 1297 mNfcService.mState = NfcAdapter.STATE_ON; 1298 NfcService.ReaderModeParams readerModeParams = mock(NfcService.ReaderModeParams.class); 1299 readerModeParams.presenceCheckDelay = 1; 1300 readerModeParams.flags = 129; 1301 mNfcService.mReaderModeParams = readerModeParams; 1302 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1303 mNfcService.onRemoteEndpointDiscovered(tagEndpoint); 1304 mLooper.dispatchAll(); 1305 verify(tagEndpoint).startPresenceChecking(anyInt(), any()); 1306 } 1307 1308 @Test testOnRemoteFieldActivated()1309 public void testOnRemoteFieldActivated() throws RemoteException { 1310 createNfcServiceWithoutStatsdUtils(); 1311 List<String> userlist = new ArrayList<>(); 1312 userlist.add("com.android.nfc"); 1313 mNfcService.mIsSecureNfcEnabled = true; 1314 mNfcService.mIsRequestUnlockShowed = false; 1315 when(mNfcInjector.isDeviceLocked()).thenReturn(true); 1316 mNfcService.mNfcEventInstalledPackages.put(1, userlist); 1317 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 1318 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 1319 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 1320 mNfcService.onRemoteFieldActivated(); 1321 verify(callback, atLeastOnce()).onRfFieldDetected(anyBoolean()); 1322 mLooper.dispatchAll(); 1323 verify(mCardEmulationManager).onFieldChangeDetected(anyBoolean()); 1324 verify(mApplication).sendBroadcastAsUser(any(), any()); 1325 verify(mApplication).sendBroadcast(any()); 1326 verify(mStatsdUtils).logFieldChanged(anyBoolean(), anyInt()); 1327 verify(mNfcEventLog, atLeast(2)).logEvent(any()); 1328 } 1329 1330 @Test testOnRemoteFieldDeactivated()1331 public void testOnRemoteFieldDeactivated() throws RemoteException { 1332 createNfcServiceWithoutStatsdUtils(); 1333 List<String> userlist = new ArrayList<>(); 1334 userlist.add("com.android.nfc"); 1335 mNfcService.mIsSecureNfcEnabled = true; 1336 mNfcService.mIsRequestUnlockShowed = false; 1337 when(mKeyguardManager.isKeyguardLocked()).thenReturn(true); 1338 mNfcService.mNfcEventInstalledPackages.put(1, userlist); 1339 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 1340 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 1341 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 1342 mNfcService.onRemoteFieldDeactivated(); 1343 verify(callback, atLeastOnce()).onRfFieldDetected(anyBoolean()); 1344 mClock.mOffset += 60; 1345 mLooper.dispatchAll(); 1346 verify(mCardEmulationManager).onFieldChangeDetected(anyBoolean()); 1347 verify(mApplication).sendBroadcastAsUser(any(), any()); 1348 verify(mStatsdUtils).logFieldChanged(anyBoolean(), anyInt()); 1349 verify(mNfcEventLog, atLeast(2)).logEvent(any()); 1350 } 1351 1352 @Test 1353 @RequiresFlagsEnabled(Flags.FLAG_COALESCE_RF_EVENTS) testOnRemoteFieldCoalessing()1354 public void testOnRemoteFieldCoalessing() throws RemoteException { 1355 Assume.assumeTrue(Flags.coalesceRfEvents()); 1356 createNfcServiceWithoutStatsdUtils(); 1357 List<String> userlist = new ArrayList<>(); 1358 userlist.add("com.android.nfc"); 1359 mNfcService.mIsSecureNfcEnabled = true; 1360 mNfcService.mIsRequestUnlockShowed = false; 1361 when(mKeyguardManager.isKeyguardLocked()).thenReturn(true); 1362 mNfcService.mNfcEventInstalledPackages.put(1, userlist); 1363 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 1364 mNfcService.onRemoteFieldActivated(); 1365 mNfcService.onRemoteFieldDeactivated(); 1366 mNfcService.onRemoteFieldActivated(); 1367 mNfcService.onRemoteFieldDeactivated(); 1368 mClock.mOffset += 60; 1369 mLooper.dispatchAll(); 1370 verify(mCardEmulationManager).onFieldChangeDetected(true); 1371 verify(mCardEmulationManager).onFieldChangeDetected(false); 1372 verify(mApplication, times(2)).sendBroadcastAsUser(any(), any()); 1373 verify(mStatsdUtils, times(4)).logFieldChanged(anyBoolean(), anyInt()); 1374 verify(mNfcEventLog, atLeast(2)).logEvent(any()); 1375 } 1376 1377 @Test testOnSeSelected()1378 public void testOnSeSelected() { 1379 mNfcService.onSeSelected(NfcService.SE_SELECTED_AID); 1380 mLooper.dispatchAll(); 1381 verify(mCardEmulationManager).onOffHostAidSelected(); 1382 } 1383 1384 @Test testOnUidToBackground()1385 public void testOnUidToBackground() throws RemoteException { 1386 mNfcService.mState = NfcAdapter.STATE_ON; 1387 mNfcService.mNfcAdapter.disable(false, PKG_NAME); 1388 mLooper.dispatchAll(); 1389 NfcService.ReaderModeParams readerModeParams = mock(NfcService.ReaderModeParams.class); 1390 mNfcService.mReaderModeParams = readerModeParams; 1391 readerModeParams.uid = 1; 1392 IBinder binder = mock(IBinder.class); 1393 readerModeParams.binder = binder; 1394 NfcService.DiscoveryTechParams discoveryTechParams = 1395 mock(NfcService.DiscoveryTechParams.class); 1396 discoveryTechParams.uid = 1; 1397 discoveryTechParams.binder = binder; 1398 mNfcService.mDiscoveryTechParams = discoveryTechParams; 1399 mNfcService.onUidToBackground(1); 1400 verify(binder, times(2)).unlinkToDeath(any(), anyInt()); 1401 Assert.assertNull(mNfcService.mReaderModeParams); 1402 verify(binder, times(2)).unlinkToDeath(any(), anyInt()); 1403 verify(mDeviceHost).resetDiscoveryTech(); 1404 Assert.assertNull(mNfcService.mDiscoveryTechParams); 1405 } 1406 1407 @Test testOnWlcData()1408 public void testOnWlcData() throws RemoteException { 1409 mNfcService.mIsWlcCapable = true; 1410 INfcWlcStateListener listener = mock(INfcWlcStateListener.class); 1411 mNfcService.mNfcAdapter.registerWlcStateListener(listener); 1412 Map<String, Integer> wlcDeviceInfo = new HashMap<>(); 1413 wlcDeviceInfo.put(NfcCharging.VendorId, 1); 1414 wlcDeviceInfo.put(NfcCharging.TemperatureListener, 1); 1415 wlcDeviceInfo.put(NfcCharging.BatteryLevel, 1); 1416 wlcDeviceInfo.put(NfcCharging.State, 1); 1417 mNfcService.onWlcData(wlcDeviceInfo); 1418 ArgumentCaptor<WlcListenerDeviceInfo> argumentCaptor = ArgumentCaptor 1419 .forClass(WlcListenerDeviceInfo.class); 1420 verify(listener).onWlcStateChanged(argumentCaptor.capture()); 1421 WlcListenerDeviceInfo deviceInfo = argumentCaptor.getValue(); 1422 Assert.assertNotNull(deviceInfo); 1423 assertThat(deviceInfo.getBatteryLevel()).isEqualTo(1); 1424 } 1425 1426 @Test testOnWlcStopped()1427 public void testOnWlcStopped() { 1428 mNfcService.onWlcStopped(0x0); 1429 verify(mNfcCharging).onWlcStopped(anyInt()); 1430 } 1431 1432 @Test testRenewTagAppPrefList()1433 public void testRenewTagAppPrefList() throws PackageManager.NameNotFoundException { 1434 BroadcastReceiver receiver = mGlobalReceiver.getValue(); 1435 Assert.assertNotNull(receiver); 1436 Intent intent = new Intent(); 1437 intent.setAction(Intent.ACTION_USER_SWITCHED); 1438 UserHandle uh = mock(UserHandle.class); 1439 when(uh.getIdentifier()).thenReturn(5); 1440 List<UserHandle> luh = new ArrayList<>(); 1441 luh.add(uh); 1442 when(mUserManager.getEnabledProfiles()).thenReturn(luh); 1443 String jsonString = "{}"; 1444 when(mPreferences.getString(anyString(), anyString())).thenReturn(jsonString); 1445 PackageInfo info = mock(PackageInfo.class); 1446 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(info); 1447 when(mPreferencesEditor.remove(any())).thenReturn(mPreferencesEditor); 1448 when(mPreferencesEditor.putString(anyString(), anyString())).thenReturn(mPreferencesEditor); 1449 receiver.onReceive(mApplication, intent); 1450 verify(mUserManager, atLeastOnce()).getEnabledProfiles(); 1451 verify(mPreferencesEditor).putString(anyString(), anyString()); 1452 } 1453 1454 @Test testSaveNfcPollTech()1455 public void testSaveNfcPollTech() { 1456 mNfcService.saveNfcPollTech(NfcService.DEFAULT_POLL_TECH); 1457 verify(mPreferencesEditor, atLeastOnce()).putInt(anyString(), anyInt()); 1458 verify(mPreferencesEditor, atLeastOnce()).apply(); 1459 verify(mBackupManager).dataChanged(); 1460 } 1461 1462 @Test testSendData()1463 public void testSendData() { 1464 mNfcService.sendData("test".getBytes()); 1465 ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class); 1466 verify(mDeviceHost).sendRawFrame(captor.capture()); 1467 assertThat(captor.getValue()).isNotNull(); 1468 assertThat(captor.getValue()).isEqualTo("test".getBytes()); 1469 } 1470 1471 @Test testSendMockNdefTag()1472 public void testSendMockNdefTag() { 1473 NdefMessage msg = mock(NdefMessage.class); 1474 when(mNfcDispatcher.dispatchTag(any())).thenReturn(NfcDispatcher.DISPATCH_SUCCESS); 1475 when(mVrManager.isVrModeEnabled()).thenReturn(false); 1476 mNfcService.mSoundPool = mSoundPool; 1477 mNfcService.sendMockNdefTag(msg); 1478 mLooper.dispatchAll(); 1479 ArgumentCaptor<Tag> captor = ArgumentCaptor.forClass(Tag.class); 1480 verify(mNfcDispatcher).dispatchTag(captor.capture()); 1481 Tag tag = captor.getValue(); 1482 assertThat(tag).isNotNull(); 1483 verify(mSoundPool) 1484 .play(anyInt(), anyFloat(), anyFloat(), anyInt(), anyInt(), anyFloat()); 1485 1486 when(mNfcDispatcher.dispatchTag(any())).thenReturn(NfcDispatcher.DISPATCH_FAIL); 1487 mNfcService.sendMockNdefTag(msg); 1488 mLooper.dispatchAll(); 1489 verify(mNfcDispatcher, atLeastOnce()).dispatchTag(captor.capture()); 1490 tag = captor.getValue(); 1491 assertThat(tag).isNotNull(); 1492 verify(mSoundPool, times(2)) 1493 .play(anyInt(), anyFloat(), anyFloat(), anyInt(), anyInt(), anyFloat()); 1494 } 1495 1496 @Test testSendScreenMessageAfterNfcCharging()1497 public void testSendScreenMessageAfterNfcCharging() { 1498 mNfcService.mPendingPowerStateUpdate = true; 1499 when(mScreenStateHelper.checkScreenState(anyBoolean())) 1500 .thenReturn(ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED); 1501 boolean result = mNfcService.sendScreenMessageAfterNfcCharging(); 1502 mLooper.dispatchAll(); 1503 assertThat(mNfcService.mIsRequestUnlockShowed).isFalse(); 1504 assertThat(result).isTrue(); 1505 assertThat(mNfcService.mPendingPowerStateUpdate).isFalse(); 1506 verify(mDeviceHost).doSetScreenState(anyInt(), anyBoolean()); 1507 } 1508 1509 @Test testSetPowerSavingMode()1510 public void testSetPowerSavingMode() throws RemoteException { 1511 mNfcService.mState = NfcAdapter.STATE_ON; 1512 byte[] payload = { 0x01, 0x01, 0x00, 0x00 }; 1513 when(mDeviceHost.setPowerSavingMode(true)).thenReturn(true); 1514 int result = mNfcService.mNfcAdapter.sendVendorNciMessage(1,0x0f,0x0c, payload); 1515 mLooper.dispatchAll(); 1516 assertThat(result).isEqualTo(0x00); 1517 verify(mDeviceHost).setPowerSavingMode(anyBoolean()); 1518 } 1519 1520 @Test testSetSystemCodeRoute()1521 public void testSetSystemCodeRoute() { 1522 mNfcService.setSystemCodeRoute(1); 1523 mLooper.dispatchAll(); 1524 ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class); 1525 verify(mDeviceHost).setSystemCodeRoute(captor.capture()); 1526 assertThat(captor.getValue()).isEqualTo(1); 1527 } 1528 1529 @Test testStateToProtoEnum()1530 public void testStateToProtoEnum() { 1531 int result = NfcService.stateToProtoEnum(NfcAdapter.STATE_OFF); 1532 assertThat(result).isEqualTo(NfcServiceDumpProto.STATE_OFF); 1533 result = NfcService.stateToProtoEnum(NfcAdapter.STATE_TURNING_ON); 1534 assertThat(result).isEqualTo(NfcServiceDumpProto.STATE_TURNING_ON); 1535 result = NfcService.stateToProtoEnum(NfcAdapter.STATE_ON); 1536 assertThat(result).isEqualTo(NfcServiceDumpProto.STATE_ON); 1537 result = NfcService.stateToProtoEnum(NfcAdapter.STATE_TURNING_OFF); 1538 assertThat(result).isEqualTo(NfcServiceDumpProto.STATE_TURNING_OFF); 1539 result = NfcService.stateToProtoEnum(0); 1540 assertThat(result).isEqualTo(NfcServiceDumpProto.STATE_UNKNOWN); 1541 } 1542 @Test testUnregisterObject()1543 public void testUnregisterObject() { 1544 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1545 when(tagEndpoint.getHandle()).thenReturn(1); 1546 mNfcService.registerTagObject(tagEndpoint); 1547 mNfcService.unregisterObject(1); 1548 assertThat(mNfcService.mObjectMap.get(1)).isNull(); 1549 } 1550 1551 @Test testNfcServiceOnReceive()1552 public void testNfcServiceOnReceive() { 1553 BroadcastReceiver receiver = mBroadcastReceiverArgumentCaptor.getValue(); 1554 Bundle bundle = new Bundle(); 1555 bundle.putBoolean(UserManager.DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO, true); 1556 when(mUserManager.getUserRestrictions()).thenReturn(bundle); 1557 Assert.assertNotNull(receiver); 1558 mNfcService.mIsNfcUserRestricted = false; 1559 when(mPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(true); 1560 when(mNfcInjector.isSatelliteModeOn()).thenReturn(false); 1561 receiver.onReceive(mApplication, new Intent(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)); 1562 verify(mUserManager, atLeastOnce()).getUserRestrictions(); 1563 1564 } 1565 1566 @Test testDiscoveryTechDeathRecipient_BinderDied()1567 public void testDiscoveryTechDeathRecipient_BinderDied() { 1568 mNfcService.mState = NfcAdapter.STATE_ON; 1569 mNfcService.mDiscoveryTechParams = mock(NfcService.DiscoveryTechParams.class); 1570 NfcService.DiscoveryTechDeathRecipient discoveryTechDeathRecipient = mNfcService 1571 .new DiscoveryTechDeathRecipient(); 1572 discoveryTechDeathRecipient.binderDied(); 1573 verify(mDeviceHost).resetDiscoveryTech(); 1574 assertThat(mNfcService.mDiscoveryTechParams).isNull(); 1575 } 1576 1577 @Test testDisableAlwaysOnInternal()1578 public void testDisableAlwaysOnInternal() throws RemoteException { 1579 mNfcService.mAlwaysOnState = NfcAdapter.STATE_OFF; 1580 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.DISABLE); 1581 mLooper.dispatchAll(); 1582 1583 mNfcService.mAlwaysOnState = NfcAdapter.STATE_TURNING_OFF; 1584 mNfcService.mAlwaysOnMode = NfcOemExtension.DISABLE; 1585 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.DISABLE); 1586 mLooper.dispatchAll(); 1587 assertThat(mNfcService.mAlwaysOnMode).isEqualTo(NfcOemExtension.DISABLE); 1588 1589 mNfcService.mState = NfcAdapter.STATE_ON; 1590 mNfcService.mAlwaysOnState = NfcAdapter.STATE_TURNING_ON; 1591 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.DISABLE); 1592 mLooper.dispatchAll(); 1593 verify(mDeviceHost).setNfceePowerAndLinkCtrl(false); 1594 1595 mNfcService.mState = NfcAdapter.STATE_OFF; 1596 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.DISABLE); 1597 mLooper.dispatchAll(); 1598 verify(mDeviceHost).setNfceePowerAndLinkCtrl(false); 1599 1600 } 1601 1602 @Test testEnableAlwaysOnInternal()1603 public void testEnableAlwaysOnInternal() throws RemoteException { 1604 mNfcService.mAlwaysOnState = NfcAdapter.STATE_ON; 1605 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.ENABLE_EE); 1606 mLooper.dispatchAll(); 1607 1608 mNfcService.mAlwaysOnState = NfcAdapter.STATE_TURNING_OFF; 1609 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.ENABLE_EE); 1610 mLooper.dispatchAll(); 1611 1612 mNfcService.mState = NfcAdapter.STATE_ON; 1613 mNfcService.mAlwaysOnState = NfcAdapter.STATE_OFF; 1614 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.ENABLE_EE); 1615 mLooper.dispatchAll(); 1616 verify(mDeviceHost).setNfceePowerAndLinkCtrl(true); 1617 1618 mNfcService.mState = NfcAdapter.STATE_OFF; 1619 mNfcService.mAlwaysOnState = NfcAdapter.STATE_OFF; 1620 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.ENABLE_EE); 1621 mLooper.dispatchAll(); 1622 verify(mDeviceHost, times(2)).setPartialInitMode(anyInt()); 1623 verify(mDeviceHost).setNfceePowerAndLinkCtrl(true); 1624 } 1625 1626 @Test testAddNfcUnlockHandler()1627 public void testAddNfcUnlockHandler() { 1628 INfcUnlockHandler unlockHandler = mock(INfcUnlockHandler.class); 1629 mNfcService.mNfcAdapter.addNfcUnlockHandler(unlockHandler, new int[]{NfcService.NFC_POLL_A, 1630 NfcService.NFC_POLL_B, NFC_POLL_V}); 1631 ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class); 1632 verify(mNfcUnlockManager).addUnlockHandler(any(), captor.capture()); 1633 assertThat(captor.getValue()).isNotNull(); 1634 assertThat(captor.getValue()).isEqualTo(3); 1635 } 1636 1637 @Test testCheckFirmware()1638 public void testCheckFirmware() throws RemoteException { 1639 mNfcService.mNfcAdapter.checkFirmware(); 1640 verify(mDeviceHost).checkFirmware(); 1641 } 1642 1643 @Test testClearPreference()1644 public void testClearPreference() throws RemoteException { 1645 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 1646 mNfcService.mNfcAdapter.clearPreference(); 1647 verify(mNfcEventLog, times(2)).logEvent(any()); 1648 } 1649 1650 @Test testEnableReaderOption()1651 public void testEnableReaderOption() throws RemoteException { 1652 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 1653 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 1654 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 1655 mNfcService.mReaderOptionCapable = true; 1656 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 1657 boolean result = mNfcService.mNfcAdapter 1658 .enableReaderOption(true, "com.android.test"); 1659 assertThat(mNfcService.mIsReaderOptionEnabled).isTrue(); 1660 verify(mPreferencesEditor, atLeastOnce()).apply(); 1661 verify(mBackupManager).dataChanged(); 1662 verify(callback).onReaderOptionChanged(true); 1663 verify(mNfcEventLog, times(2)).logEvent(any()); 1664 assertThat(result).isTrue(); 1665 } 1666 1667 @Test testFetchActiveNfceeList()1668 public void testFetchActiveNfceeList() throws RemoteException { 1669 mNfcService.mState = NfcAdapter.STATE_ON; 1670 Map<String, Integer> nfceeMap = new HashMap<>(); 1671 nfceeMap.put("test1", Integer.valueOf(NFC_LISTEN_A)); 1672 nfceeMap.put("test2", Integer.valueOf(NFC_LISTEN_B)); 1673 nfceeMap.put("test3", Integer.valueOf(NFC_LISTEN_F)); 1674 when(mDeviceHost.dofetchActiveNfceeList()).thenReturn(nfceeMap); 1675 Map<String, Integer> map = mNfcService.mNfcAdapter.fetchActiveNfceeList(); 1676 verify(mDeviceHost).dofetchActiveNfceeList(); 1677 Assert.assertEquals(map, nfceeMap); 1678 } 1679 1680 @Test testGetNfcAdapterExtrasInterface()1681 public void testGetNfcAdapterExtrasInterface() throws RemoteException { 1682 INfcAdapterExtras adpExtras = mNfcService.mNfcAdapter 1683 .getNfcAdapterExtrasInterface("com.android.test"); 1684 assertThat(adpExtras).isNull(); 1685 } 1686 1687 @Test testGetNfcDtaInterface()1688 public void testGetNfcDtaInterface() throws RemoteException { 1689 mNfcService.mNfcDtaService = null; 1690 INfcDta nfcData = mNfcService.mNfcAdapter.getNfcDtaInterface("com.android.test"); 1691 assertThat(nfcData).isNotNull(); 1692 1693 NfcService.NfcDtaService nfcDtaService = mock(NfcService.NfcDtaService.class); 1694 mNfcService.mNfcDtaService = nfcDtaService; 1695 INfcDta resultDtaService = mNfcService.mNfcAdapter 1696 .getNfcDtaInterface("com.android.test"); 1697 Assert.assertNotNull(resultDtaService); 1698 assertThat(nfcDtaService).isEqualTo(resultDtaService); 1699 } 1700 1701 @Test testGetSettingStatus()1702 public void testGetSettingStatus() throws RemoteException { 1703 when(mDeviceConfigFacade.getNfcDefaultState()).thenReturn(true); 1704 when(mPreferences.getBoolean(PREF_NFC_ON, true)).thenReturn(true); 1705 boolean result = mNfcService.mNfcAdapter.getSettingStatus(); 1706 assertThat(result).isTrue(); 1707 verify(mPreferences, atLeastOnce()).getBoolean(anyString(), anyBoolean()); 1708 } 1709 1710 @Test testSetTagIntentAppPreferenceForUser()1711 public void testSetTagIntentAppPreferenceForUser() 1712 throws RemoteException, PackageManager.NameNotFoundException { 1713 PackageInfo info = mock(PackageInfo.class); 1714 ApplicationInfo applicationInfo = mock(ApplicationInfo.class); 1715 applicationInfo.flags = 1; 1716 info.applicationInfo = applicationInfo; 1717 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(info); 1718 int result = mNfcService.mNfcAdapter 1719 .setTagIntentAppPreferenceForUser(1, "com.android.test", true); 1720 assertThat(result).isEqualTo(NfcAdapter.TAG_INTENT_APP_PREF_RESULT_SUCCESS); 1721 when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(null); 1722 result = mNfcService.mNfcAdapter 1723 .setTagIntentAppPreferenceForUser(1, "com.android.test", true); 1724 assertThat(result).isEqualTo(NfcAdapter.TAG_INTENT_APP_PREF_RESULT_PACKAGE_NOT_FOUND); 1725 } 1726 1727 @Test testCanMakeReadOnly()1728 public void testCanMakeReadOnly() throws RemoteException { 1729 NfcService.TagService tagService = mNfcService.new TagService(); 1730 tagService.canMakeReadOnly(Ndef.TYPE_1); 1731 verify(mDeviceHost).canMakeReadOnly(anyInt()); 1732 } 1733 1734 @Test testConnect()1735 public void testConnect() throws RemoteException { 1736 NfcService.TagService tagService = mNfcService.new TagService(); 1737 mNfcService.mState = NfcAdapter.STATE_ON; 1738 mNfcService.mIsReaderOptionEnabled = true; 1739 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1740 when(tagEndpoint.isPresent()).thenReturn(true); 1741 when(tagEndpoint.connect(anyInt())).thenReturn(true); 1742 mNfcService.mObjectMap.put(1, tagEndpoint); 1743 int resultCode = tagService.connect(1, Ndef.TYPE_1); 1744 assertThat(resultCode).isEqualTo(ErrorCodes.SUCCESS); 1745 } 1746 1747 @Test testReConnect()1748 public void testReConnect() throws RemoteException { 1749 NfcService.TagService tagService = mNfcService.new TagService(); 1750 mNfcService.mState = NfcAdapter.STATE_ON; 1751 mNfcService.mIsReaderOptionEnabled = true; 1752 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1753 when(tagEndpoint.isPresent()).thenReturn(true); 1754 when(tagEndpoint.reconnect()).thenReturn(true); 1755 mNfcService.mObjectMap.put(1, tagEndpoint); 1756 int resultCode = tagService.reconnect(1); 1757 assertThat(resultCode).isEqualTo(ErrorCodes.SUCCESS); 1758 } 1759 1760 @Test testFormatNdef()1761 public void testFormatNdef() throws RemoteException { 1762 NfcService.TagService tagService = mNfcService.new TagService(); 1763 mNfcService.mState = NfcAdapter.STATE_ON; 1764 mNfcService.mIsReaderOptionEnabled = true; 1765 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1766 when(tagEndpoint.formatNdef(any())).thenReturn(true); 1767 mNfcService.mObjectMap.put(1, tagEndpoint); 1768 int resultCode = tagService.formatNdef(1, "test".getBytes()); 1769 assertThat(resultCode).isEqualTo(ErrorCodes.SUCCESS); 1770 } 1771 1772 @Test testRediscover()1773 public void testRediscover() throws RemoteException { 1774 NfcService.TagService tagService = mNfcService.new TagService(); 1775 mNfcService.mState = NfcAdapter.STATE_ON; 1776 mNfcService.mIsReaderOptionEnabled = true; 1777 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1778 when(tagEndpoint.getUid()).thenReturn(new byte[]{4, 18, 52, 86}); 1779 when(tagEndpoint.getTechList()).thenReturn(new int[]{Ndef.NDEF}); 1780 when(tagEndpoint.getTechExtras()).thenReturn(new Bundle[]{}); 1781 when(tagEndpoint.getHandle()).thenReturn(1); 1782 mNfcService.mObjectMap.put(1, tagEndpoint); 1783 Tag tag = tagService.rediscover(1); 1784 assertThat(tag).isNotNull(); 1785 } 1786 1787 @Test testGetExtendedLengthApdusSupported()1788 public void testGetExtendedLengthApdusSupported() throws RemoteException { 1789 NfcService.TagService tagService = mNfcService.new TagService(); 1790 tagService.getExtendedLengthApdusSupported(); 1791 verify(mDeviceHost).getExtendedLengthApdusSupported(); 1792 } 1793 1794 @Test testGetMaxTransceiveLength()1795 public void testGetMaxTransceiveLength() throws RemoteException { 1796 NfcService.TagService tagService = mNfcService.new TagService(); 1797 tagService.getMaxTransceiveLength(Ndef.NDEF); 1798 verify(mDeviceHost).getMaxTransceiveLength(Ndef.NDEF); 1799 } 1800 1801 @Test testTechList()1802 public void testTechList() throws RemoteException { 1803 NfcService.TagService tagService = mNfcService.new TagService(); 1804 mNfcService.mState = NfcAdapter.STATE_ON; 1805 mNfcService.mIsReaderOptionEnabled = true; 1806 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1807 when(tagEndpoint.getTechList()).thenReturn(new int[]{Ndef.NDEF, Ndef.TYPE_OTHER}); 1808 mNfcService.mObjectMap.put(1, tagEndpoint); 1809 int[] techList = tagService.getTechList(1); 1810 assertThat(techList).isNotNull(); 1811 assertThat(techList).hasLength(2); 1812 } 1813 1814 @Test testGetTimeOut()1815 public void testGetTimeOut() throws RemoteException { 1816 NfcService.TagService tagService = mNfcService.new TagService(); 1817 tagService.getTimeout(Ndef.NDEF); 1818 verify(mDeviceHost).getTimeout(Ndef.NDEF); 1819 } 1820 1821 @Test testIsNdef()1822 public void testIsNdef() throws RemoteException { 1823 NfcService.TagService tagService = mNfcService.new TagService(); 1824 mNfcService.mState = NfcAdapter.STATE_ON; 1825 mNfcService.mIsReaderOptionEnabled = true; 1826 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1827 when(tagEndpoint.checkNdef(any())).thenReturn(true); 1828 mNfcService.mObjectMap.put(1, tagEndpoint); 1829 boolean result = tagService.isNdef(1); 1830 assertThat(result).isTrue(); 1831 } 1832 1833 @Test testIsPresent()1834 public void testIsPresent() throws RemoteException { 1835 NfcService.TagService tagService = mNfcService.new TagService(); 1836 mNfcService.mState = NfcAdapter.STATE_ON; 1837 mNfcService.mIsReaderOptionEnabled = true; 1838 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1839 when(tagEndpoint.isPresent()).thenReturn(true); 1840 mNfcService.mObjectMap.put(1, tagEndpoint); 1841 boolean result = tagService.isPresent(1); 1842 assertThat(result).isTrue(); 1843 } 1844 1845 @Test testIsTagUpToDate()1846 public void testIsTagUpToDate() throws RemoteException { 1847 NfcService.TagService tagService = mNfcService.new TagService(); 1848 mNfcService.mCookieUpToDate = 0; 1849 boolean result = tagService.isTagUpToDate(0); 1850 assertThat(result).isTrue(); 1851 } 1852 1853 @Test testNdefMakeReadOnly()1854 public void testNdefMakeReadOnly() throws RemoteException { 1855 NfcService.TagService tagService = mNfcService.new TagService(); 1856 mNfcService.mState = NfcAdapter.STATE_ON; 1857 mNfcService.mIsReaderOptionEnabled = true; 1858 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1859 when(tagEndpoint.makeReadOnly()).thenReturn(true); 1860 mNfcService.mObjectMap.put(1, tagEndpoint); 1861 int result = tagService.ndefMakeReadOnly(1); 1862 assertThat(result).isEqualTo(ErrorCodes.SUCCESS); 1863 } 1864 1865 @Test testNdefRead()1866 public void testNdefRead() throws RemoteException { 1867 NfcService.TagService tagService = mNfcService.new TagService(); 1868 mNfcService.mState = NfcAdapter.STATE_ON; 1869 mNfcService.mIsReaderOptionEnabled = true; 1870 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1871 NdefRecord record = NdefRecord.createTextRecord("en", "ndef"); 1872 NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{record}); 1873 when(tagEndpoint.readNdef()).thenReturn(ndefMessage.toByteArray()); 1874 mNfcService.mObjectMap.put(1, tagEndpoint); 1875 NdefMessage resultMessage = tagService.ndefRead(1); 1876 assertThat(resultMessage).isNotNull(); 1877 assertThat(resultMessage.getRecords()).hasLength(1); 1878 } 1879 1880 @Test testNdefWrite()1881 public void testNdefWrite() throws RemoteException { 1882 NfcService.TagService tagService = mNfcService.new TagService(); 1883 mNfcService.mState = NfcAdapter.STATE_ON; 1884 mNfcService.mIsReaderOptionEnabled = true; 1885 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1886 NdefRecord record = NdefRecord.createTextRecord("en", "ndef"); 1887 NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{record}); 1888 when(tagEndpoint.writeNdef(any())).thenReturn(true); 1889 mNfcService.mObjectMap.put(1, tagEndpoint); 1890 int result = tagService.ndefWrite(1, ndefMessage); 1891 assertThat(result).isEqualTo(ErrorCodes.SUCCESS); 1892 } 1893 1894 @Test testResetTimeouts()1895 public void testResetTimeouts() throws RemoteException { 1896 NfcService.TagService tagService = mNfcService.new TagService(); 1897 tagService.resetTimeouts(); 1898 verify(mDeviceHost).resetTimeouts(); 1899 } 1900 1901 @Test testSetTimeout()1902 public void testSetTimeout() throws RemoteException { 1903 NfcService.TagService tagService = mNfcService.new TagService(); 1904 when(mDeviceHost.setTimeout(Ndef.NDEF, 100)).thenReturn(true); 1905 int result = tagService.setTimeout(Ndef.NDEF, 100); 1906 verify(mDeviceHost).setTimeout(Ndef.NDEF, 100); 1907 assertThat(result).isEqualTo(ErrorCodes.SUCCESS); 1908 } 1909 1910 @Test testTransceive()1911 public void testTransceive() throws RemoteException { 1912 NfcService.TagService tagService = mNfcService.new TagService(); 1913 mNfcService.mState = NfcAdapter.STATE_ON; 1914 mNfcService.mIsReaderOptionEnabled = true; 1915 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1916 NdefRecord record = NdefRecord.createTextRecord("en", "ndef"); 1917 NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{record}); 1918 when(mDeviceHost.getMaxTransceiveLength(anyInt())).thenReturn(100); 1919 when(tagEndpoint.getConnectedTechnology()).thenReturn(Ndef.NDEF); 1920 when(tagEndpoint.transceive(any(), anyBoolean(), any())) 1921 .thenReturn(ndefMessage.toByteArray()); 1922 mNfcService.mObjectMap.put(1, tagEndpoint); 1923 1924 TransceiveResult result = tagService.transceive(1, ndefMessage 1925 .toByteArray(), true); 1926 assertThat(result).isNotNull(); 1927 } 1928 1929 @Test testGetWlcListenerDeviceInfo()1930 public void testGetWlcListenerDeviceInfo() { 1931 Map<String, Integer> wlcDeviceInfo = new HashMap<>(); 1932 wlcDeviceInfo.put(NfcCharging.VendorId, 1); 1933 wlcDeviceInfo.put(NfcCharging.TemperatureListener, 1); 1934 wlcDeviceInfo.put(NfcCharging.BatteryLevel, 1); 1935 wlcDeviceInfo.put(NfcCharging.State, 1); 1936 mNfcService.onWlcData(wlcDeviceInfo); 1937 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 1938 mNfcService.mIsWlcCapable = true; 1939 WlcListenerDeviceInfo wlcListenerDeviceInfo = adapterService.getWlcListenerDeviceInfo(); 1940 assertThat(wlcListenerDeviceInfo).isNotNull(); 1941 assertThat(wlcListenerDeviceInfo.getBatteryLevel()).isEqualTo(1); 1942 } 1943 1944 @Test testHandleShellCommand()1945 public void testHandleShellCommand() { 1946 ParcelFileDescriptor in = mock(ParcelFileDescriptor.class); 1947 when(in.getFileDescriptor()).thenReturn(mock(FileDescriptor.class)); 1948 ParcelFileDescriptor out = mock(ParcelFileDescriptor.class); 1949 when(out.getFileDescriptor()).thenReturn(mock(FileDescriptor.class)); 1950 ParcelFileDescriptor err = mock(ParcelFileDescriptor.class); 1951 when(err.getFileDescriptor()).thenReturn(mock(FileDescriptor.class)); 1952 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 1953 int result = adapterService.handleShellCommand(in, out, err, new String[]{"test"}); 1954 assertThat(result).isEqualTo(-1); 1955 } 1956 1957 @Test testIgnore()1958 public void testIgnore() throws RemoteException { 1959 mNfcService.mDebounceTagNativeHandle = 0; 1960 ITagRemovedCallback callback = mock(ITagRemovedCallback.class); 1961 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 1962 boolean result = adapterService.ignore(0,0, callback); 1963 mLooper.dispatchAll(); 1964 assertThat(result).isTrue(); 1965 1966 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 1967 when(tagEndpoint.getUid()).thenReturn(new byte[]{4, 18 ,52, 86}); 1968 mNfcService.mObjectMap.put(1, tagEndpoint); 1969 result = adapterService.ignore(1,1, callback); 1970 verify(tagEndpoint).disconnect(); 1971 mLooper.dispatchAll(); 1972 assertThat(result).isTrue(); 1973 1974 } 1975 1976 @Test testIsNfcSecureEnabled()1977 public void testIsNfcSecureEnabled() throws RemoteException { 1978 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 1979 mNfcService.mIsSecureNfcEnabled = true; 1980 boolean result = adapterService.isNfcSecureEnabled(); 1981 assertThat(result).isTrue(); 1982 } 1983 1984 @Test testIsReaderOptionSupported()1985 public void testIsReaderOptionSupported() { 1986 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 1987 mNfcService.mReaderOptionCapable = true; 1988 boolean result = adapterService.isReaderOptionSupported(); 1989 assertThat(result).isTrue(); 1990 } 1991 1992 @Test testGetTagIntentAppPreferenceForUser()1993 public void testGetTagIntentAppPreferenceForUser() throws RemoteException { 1994 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 1995 mNfcService.mTagAppPrefList.put(1, new HashMap<>()); 1996 Map result = adapterService.getTagIntentAppPreferenceForUser(1); 1997 assertThat(result).isNotNull(); 1998 } 1999 2000 @Test testGetWalletRoleHolder()2001 public void testGetWalletRoleHolder() { 2002 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2003 mNfcService.mState = NfcAdapter.STATE_ON; 2004 when(NfcInjector.isPrivileged(anyInt())).thenReturn(false); 2005 when(mCardEmulationManager.isPreferredServicePackageNameForUser(anyString(), anyInt())) 2006 .thenReturn(true); 2007 when(android.permission.flags.Flags.walletRoleEnabled()).thenReturn(true); 2008 List<String> list = new ArrayList<>(); 2009 list.add("com.android.test"); 2010 when(mRoleManager.getRoleHolders(anyString())).thenReturn(list); 2011 boolean result = adapterService.setObserveMode(true, "com.android.test"); 2012 assertThat(result).isFalse(); 2013 verify(mDeviceHost).setObserveMode(anyBoolean()); 2014 } 2015 2016 @Test testIsWlcEnabled()2017 public void testIsWlcEnabled() throws RemoteException { 2018 mNfcService.mIsWlcCapable = true; 2019 mNfcService.mIsWlcEnabled = true; 2020 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2021 boolean result = adapterService.isWlcEnabled(); 2022 assertThat(result).isTrue(); 2023 } 2024 2025 @Test testNotifyTestHceData()2026 public void testNotifyTestHceData() { 2027 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2028 doNothing().when(mCardEmulationManager).onHostCardEmulationData(anyInt(), any()); 2029 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 2030 adapterService.notifyTestHceData(Ndef.NDEF, "test".getBytes()); 2031 verify(mCardEmulationManager).onHostCardEmulationData(anyInt(), any()); 2032 verify(mNfcEventLog, atLeastOnce()).logEvent(any()); 2033 } 2034 2035 @Test testPausePolling()2036 public void testPausePolling() { 2037 mNfcService.onRfDiscoveryEvent(true); 2038 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2039 adapterService.pausePolling(100); 2040 verify(mDeviceHost).disableDiscovery(); 2041 mLooper.dispatchAll(); 2042 } 2043 2044 @Test testRegisterControllerAlwaysOnListener()2045 public void testRegisterControllerAlwaysOnListener() throws RemoteException { 2046 INfcControllerAlwaysOnListener iNfcControllerAlwaysOnListener 2047 = mock(INfcControllerAlwaysOnListener.class); 2048 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2049 adapterService.registerControllerAlwaysOnListener(iNfcControllerAlwaysOnListener); 2050 2051 mNfcService.mAlwaysOnState = NfcAdapter.STATE_TURNING_ON; 2052 mNfcService.mState = NfcAdapter.STATE_OFF; 2053 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.ENABLE_DEFAULT); 2054 mLooper.dispatchAll(); 2055 2056 verify(iNfcControllerAlwaysOnListener).onControllerAlwaysOnChanged(anyBoolean()); 2057 } 2058 2059 @Test testSetNfcSecure()2060 public void testSetNfcSecure() { 2061 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2062 when(mKeyguardManager.isKeyguardLocked()).thenReturn(false); 2063 mNfcService.mIsSecureNfcEnabled = false; 2064 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 2065 mNfcService.mIsHceCapable = true; 2066 adapterService.setNfcSecure(true); 2067 verify(mPreferencesEditor).putBoolean(anyString(), anyBoolean()); 2068 verify(mPreferencesEditor, atLeastOnce()).apply(); 2069 verify(mBackupManager).dataChanged(); 2070 verify(mDeviceHost).setNfcSecure(true); 2071 verify(mNfcEventLog, times(2)).logEvent(any()); 2072 verify(mCardEmulationManager).onTriggerRoutingTableUpdate(); 2073 } 2074 2075 @Test testSetScreenState()2076 public void testSetScreenState() throws RemoteException { 2077 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2078 when(mScreenStateHelper.checkScreenState(anyBoolean())) 2079 .thenReturn(ScreenStateHelper.SCREEN_STATE_OFF_LOCKED); 2080 mNfcService.mScreenState = ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED; 2081 when(mDeviceHost.getNciVersion()).thenReturn(NCI_VERSION_1_0); 2082 when(mFeatureFlags.reduceStateTransition()).thenReturn(true); 2083 mNfcService.mIsWatchType = true; 2084 mNfcService.mState = NfcAdapter.STATE_ON; 2085 when(mCardEmulationManager.isRequiresScreenOnServiceExist()).thenReturn(false); 2086 adapterService.setScreenState(); 2087 mLooper.dispatchAll(); 2088 verify(mDeviceHost).doSetScreenState(anyInt(), anyBoolean()); 2089 } 2090 2091 @Test testSetWlcEnabled()2092 public void testSetWlcEnabled() { 2093 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2094 mNfcService.mIsWlcCapable = true; 2095 mNfcService.mState = NfcAdapter.STATE_ON; 2096 when(android.nfc.Flags.nfcPersistLog()).thenReturn(true); 2097 adapterService.setWlcEnabled(true); 2098 verify(mPreferencesEditor).putBoolean(anyString(), anyBoolean()); 2099 verify(mPreferencesEditor, atLeastOnce()).apply(); 2100 verify(mBackupManager).dataChanged(); 2101 verify(mBackupManager).dataChanged(); 2102 } 2103 2104 @Test testUnregisterControllerAlwaysOnListener()2105 public void testUnregisterControllerAlwaysOnListener() throws RemoteException { 2106 INfcControllerAlwaysOnListener iNfcControllerAlwaysOnListener 2107 = mock(INfcControllerAlwaysOnListener.class); 2108 NfcService.NfcAdapterService adapterService = mNfcService.new NfcAdapterService(); 2109 adapterService.unregisterControllerAlwaysOnListener(iNfcControllerAlwaysOnListener); 2110 2111 mNfcService.mAlwaysOnState = NfcAdapter.STATE_TURNING_ON; 2112 mNfcService.mState = NfcAdapter.STATE_OFF; 2113 mNfcService.mNfcAdapter.setControllerAlwaysOn(NfcOemExtension.ENABLE_DEFAULT); 2114 mLooper.dispatchAll(); 2115 2116 verify(iNfcControllerAlwaysOnListener, never()).onControllerAlwaysOnChanged(anyBoolean()); 2117 } 2118 2119 @Test testUnregisterOemExtensionCallback()2120 public void testUnregisterOemExtensionCallback() throws RemoteException { 2121 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 2122 INfcOemExtensionCallback callback = mock(INfcOemExtensionCallback.class); 2123 mNfcService.mNfcAdapter.registerOemExtensionCallback(callback); 2124 ArgumentCaptor<INfcOemExtensionCallback> captor = ArgumentCaptor 2125 .forClass(INfcOemExtensionCallback.class); 2126 verify(mCardEmulationManager).setOemExtension(captor.capture()); 2127 assertThat(captor.getValue()).isEqualTo(callback); 2128 2129 mNfcService.mNfcAdapter.unregisterOemExtensionCallback(callback); 2130 mNfcService.onHostCardEmulationActivated(Ndef.NDEF); 2131 verify(callback, times(1)).onCardEmulationActivated(anyBoolean()); 2132 } 2133 2134 @Test testUnregisterWlcStateListener()2135 public void testUnregisterWlcStateListener() throws RemoteException { 2136 mNfcService.mIsWlcCapable = true; 2137 INfcWlcStateListener listener = mock(INfcWlcStateListener.class); 2138 mNfcService.mNfcAdapter.registerWlcStateListener(listener); 2139 Map<String, Integer> wlcDeviceInfo = new HashMap<>(); 2140 wlcDeviceInfo.put(NfcCharging.VendorId, 1); 2141 wlcDeviceInfo.put(NfcCharging.TemperatureListener, 1); 2142 wlcDeviceInfo.put(NfcCharging.BatteryLevel, 1); 2143 wlcDeviceInfo.put(NfcCharging.State, 1); 2144 mNfcService.onWlcData(wlcDeviceInfo); 2145 verify(listener).onWlcStateChanged(any()); 2146 2147 mNfcService.mNfcAdapter.unregisterWlcStateListener(listener); 2148 mNfcService.onWlcData(wlcDeviceInfo); 2149 verify(listener, times(1)).onWlcStateChanged(any()); 2150 } 2151 2152 @Test testIsControllerAlwaysOn()2153 public void testIsControllerAlwaysOn() throws RemoteException { 2154 mNfcService.mAlwaysOnState = NfcAdapter.STATE_ON; 2155 boolean result = mNfcService.mNfcAdapter.isControllerAlwaysOn(); 2156 assertThat(result).isTrue(); 2157 } 2158 2159 2160 @Test testDisableDta()2161 public void testDisableDta() throws RemoteException { 2162 mNfcService.mNfcAdapter.getNfcDtaInterface("com.android.test"); 2163 NfcService.sIsDtaMode = true; 2164 mNfcService.mNfcDtaService.disableDta(); 2165 verify(mDeviceHost).disableDtaMode(); 2166 assertThat(NfcService.sIsDtaMode).isFalse(); 2167 } 2168 2169 @Test testEnableClient()2170 public void testEnableClient() throws RemoteException { 2171 mNfcService.mNfcAdapter.getNfcDtaInterface("com.android.test"); 2172 boolean result = mNfcService.mNfcDtaService.enableClient("com.android.test", 2173 0, 0, 0); 2174 assertThat(result).isFalse(); 2175 2176 } 2177 2178 @Test testEnableDta()2179 public void testEnableDta() throws RemoteException { 2180 mNfcService.mNfcAdapter.getNfcDtaInterface("com.android.test"); 2181 NfcService.sIsDtaMode = false; 2182 mNfcService.mNfcDtaService.enableDta(); 2183 verify(mDeviceHost).enableDtaMode(); 2184 assertThat(NfcService.sIsDtaMode).isTrue(); 2185 } 2186 2187 @Test testEnableServer()2188 public void testEnableServer() throws RemoteException { 2189 mNfcService.mNfcAdapter.getNfcDtaInterface("com.android.test"); 2190 boolean result = mNfcService.mNfcDtaService.enableServer("com.android.test", 2191 0, 0, 0, 0); 2192 assertThat(result).isFalse(); 2193 } 2194 2195 @Test testRegisterMessageService()2196 public void testRegisterMessageService() throws RemoteException { 2197 mNfcService.mNfcAdapter.getNfcDtaInterface("com.android.test"); 2198 boolean result = mNfcService.mNfcDtaService 2199 .registerMessageService("com.android.test"); 2200 assertThat(result).isTrue(); 2201 } 2202 2203 @Test testPollingDelay()2204 public void testPollingDelay() { 2205 Handler handler = mNfcService.getHandler(); 2206 Assert.assertNotNull(handler); 2207 Message msg = handler.obtainMessage(NfcService.MSG_NDEF_TAG); 2208 mNfcService.mState = NfcAdapter.STATE_ON; 2209 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 2210 when(tagEndpoint.getConnectedTechnology()).thenReturn(TagTechnology.NDEF); 2211 when(tagEndpoint.reconnect()).thenReturn(false); 2212 mNfcService.mScreenState = ScreenStateHelper.SCREEN_STATE_ON_UNLOCKED; 2213 msg.obj = tagEndpoint; 2214 handler.handleMessage(msg); 2215 verify(tagEndpoint).disconnect(); 2216 verify(mDeviceHost).startStopPolling(false); 2217 } 2218 2219 @Test testOnTagDisconnected()2220 public void testOnTagDisconnected() throws RemoteException { 2221 Handler handler = mNfcService.getHandler(); 2222 Assert.assertNotNull(handler); 2223 Message msg = handler.obtainMessage(NfcService.MSG_NDEF_TAG); 2224 mNfcService.mState = NfcAdapter.STATE_ON; 2225 DeviceHost.TagEndpoint tagEndpoint = mock(DeviceHost.TagEndpoint.class); 2226 when(tagEndpoint.getConnectedTechnology()).thenReturn(TagTechnology.NDEF); 2227 NdefMessage ndefMessage = mock(NdefMessage.class); 2228 when(tagEndpoint.findAndReadNdef()).thenReturn(ndefMessage); 2229 msg.obj = tagEndpoint; 2230 handler.handleMessage(msg); 2231 ArgumentCaptor<DeviceHost.TagDisconnectedCallback> callbackArgumentCaptor 2232 = ArgumentCaptor.forClass(DeviceHost.TagDisconnectedCallback.class); 2233 verify(tagEndpoint, atLeastOnce()).startPresenceChecking(anyInt(), 2234 callbackArgumentCaptor.capture()); 2235 2236 DeviceHost.TagDisconnectedCallback callback = callbackArgumentCaptor.getValue(); 2237 Assert.assertNotNull(callback); 2238 when(mPreferences.getBoolean(eq(PREF_NFC_ON), anyBoolean())).thenReturn(true); 2239 INfcOemExtensionCallback oemExtensionCallback = mock(INfcOemExtensionCallback.class); 2240 mNfcService.mNfcAdapter.registerOemExtensionCallback(oemExtensionCallback); 2241 callback.onTagDisconnected(); 2242 assertThat(mNfcService.mCookieUpToDate).isLessThan(0); 2243 verify(oemExtensionCallback).onTagConnected(anyBoolean()); 2244 } 2245 2246 @Test testSetFirmwareExitFrameTable()2247 public void testSetFirmwareExitFrameTable() throws Exception{ 2248 createNfcServiceWithoutStatsdUtils(); 2249 mNfcService.mState = NfcAdapter.STATE_ON; 2250 ArgumentCaptor<ExitFrame[]> frameCaptor = ArgumentCaptor.forClass(ExitFrame[].class); 2251 ArgumentCaptor<byte[]> timeoutCaptor = ArgumentCaptor.forClass(byte[].class); 2252 when(mDeviceHost.setFirmwareExitFrameTable(any(), any())).thenReturn(true); 2253 2254 boolean result = mNfcService.setFirmwareExitFrameTable( 2255 Collections.singletonList(new ExitFrame("1234")), 5000); 2256 2257 assertTrue("setFirmwareExitFrameTable should return true", result); 2258 verify(mDeviceHost).setFirmwareExitFrameTable(frameCaptor.capture(), 2259 timeoutCaptor.capture()); 2260 ExitFrame[] frames = frameCaptor.getValue(); 2261 assertThat(frames).hasLength(1); 2262 assertThat(frames[0].getData()).isEqualTo(HexFormat.of().parseHex("1234")); 2263 byte[] timeoutBytes = timeoutCaptor.getValue(); 2264 // 5000 in little-endian bytes 2265 assertArrayEquals(new byte[] {(byte) 0x88, 0x13}, timeoutBytes); 2266 verify(mStatsdUtils).logExitFrameTableChanged(1, 5000); 2267 } 2268 2269 @Test testSetFirmwareExitFrameTable_largeTimeout()2270 public void testSetFirmwareExitFrameTable_largeTimeout() throws Exception{ 2271 createNfcServiceWithoutStatsdUtils(); 2272 mNfcService.mState = NfcAdapter.STATE_ON; 2273 ArgumentCaptor<byte[]> timeoutCaptor = ArgumentCaptor.forClass(byte[].class); 2274 when(mDeviceHost.setFirmwareExitFrameTable(any(), any())).thenReturn(true); 2275 2276 boolean result = mNfcService.setFirmwareExitFrameTable( 2277 Collections.singletonList(new ExitFrame("1234")), 500000); 2278 2279 assertTrue("setFirmwareExitFrameTable should return true", result); 2280 verify(mDeviceHost).setFirmwareExitFrameTable(any(), timeoutCaptor.capture()); 2281 byte[] timeoutBytes = timeoutCaptor.getValue(); 2282 assertArrayEquals(new byte[] {(byte) 0xFF, (byte) 0xFF}, timeoutBytes); 2283 verify(mStatsdUtils).logExitFrameTableChanged(1, 500000); 2284 } 2285 2286 @Test testSetFirmwareExitFrameTable_nfcDisabled()2287 public void testSetFirmwareExitFrameTable_nfcDisabled() throws Exception { 2288 createNfcServiceWithoutStatsdUtils(); 2289 mNfcService.mState = NfcAdapter.STATE_OFF; 2290 2291 boolean result = mNfcService.setFirmwareExitFrameTable( 2292 Collections.singletonList(new ExitFrame("1234")), 5000); 2293 2294 assertFalse("setFirmwareExitFrameTable should return false", result); 2295 verify(mDeviceHost, never()).setFirmwareExitFrameTable(any(), any()); 2296 } 2297 2298 @Test testSetFirmwareExitFrameTable_hceActive()2299 public void testSetFirmwareExitFrameTable_hceActive() throws Exception { 2300 createNfcServiceWithoutStatsdUtils(); 2301 mNfcService.mState = NfcAdapter.STATE_ON; 2302 when(mCardEmulationManager.isHostCardEmulationActivated()) 2303 .thenReturn(true); 2304 2305 boolean result = mNfcService.setFirmwareExitFrameTable( 2306 Collections.singletonList(new ExitFrame("1234")), 5000); 2307 2308 assertFalse("setFirmwareExitFrameTable should return false", result); 2309 verify(mDeviceHost, never()).setFirmwareExitFrameTable(any(), any()); 2310 } 2311 } 2312