aboutsummaryrefslogtreecommitdiff
path: root/tests/carservice_unit_test/src/com/android/car/user/BaseCarUserServiceTestCase.java
blob: 50dc55b17e0e3342a1187c8f6ac3d83222c0ac19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.car.user;

import static android.car.test.mocks.AndroidMockitoHelper.mockUmGetUserHandles;
import static android.car.test.mocks.AndroidMockitoHelper.mockUmRemoveUserWhenPossible;
import static android.car.test.mocks.JavaMockitoHelper.getResult;

import static com.android.car.user.MockedUserHandleBuilder.expectAdminUserExists;
import static com.android.car.user.MockedUserHandleBuilder.expectGuestUserExists;
import static com.android.car.user.MockedUserHandleBuilder.expectRegularUserExists;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doAnswer;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doThrow;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.notNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UserIdInt;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.car.ICarResultReceiver;
import android.car.builtin.app.ActivityManagerHelper;
import android.car.drivingstate.CarUxRestrictions;
import android.car.drivingstate.ICarUxRestrictionsChangeListener;
import android.car.test.mocks.AbstractExtendedMockitoTestCase;
import android.car.test.mocks.BlockingAnswer;
import android.car.testapi.BlockingUserLifecycleListener;
import android.car.user.CarUserManager;
import android.car.user.CarUserManager.UserLifecycleEvent;
import android.car.user.UserCreationResult;
import android.car.user.UserIdentificationAssociationResponse;
import android.car.user.UserRemovalResult;
import android.car.user.UserStartResult;
import android.car.user.UserStopResult;
import android.car.user.UserSwitchResult;
import android.car.util.concurrent.AndroidFuture;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.UserInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.hardware.automotive.vehicle.CreateUserRequest;
import android.hardware.automotive.vehicle.CreateUserResponse;
import android.hardware.automotive.vehicle.InitialUserInfoResponse;
import android.hardware.automotive.vehicle.RemoveUserRequest;
import android.hardware.automotive.vehicle.SwitchUserRequest;
import android.hardware.automotive.vehicle.SwitchUserResponse;
import android.hardware.automotive.vehicle.UserIdentificationAssociation;
import android.hardware.automotive.vehicle.UserIdentificationGetRequest;
import android.hardware.automotive.vehicle.UserIdentificationResponse;
import android.hardware.automotive.vehicle.UserIdentificationSetRequest;
import android.hardware.automotive.vehicle.UsersInfo;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.UserManager.RemoveResult;
import android.util.Log;
import android.view.Display;

import androidx.test.InstrumentationRegistry;

import com.android.car.CarServiceUtils;
import com.android.car.CarUxRestrictionsManagerService;
import com.android.car.hal.HalCallback;
import com.android.car.hal.HalCallback.HalCallbackStatus;
import com.android.car.hal.UserHalHelper;
import com.android.car.hal.UserHalService;
import com.android.car.internal.ICarServiceHelper;
import com.android.car.internal.common.CommonConstants.UserLifecycleEventType;
import com.android.car.internal.common.UserHelperLite;
import com.android.car.internal.os.CarSystemProperties;
import com.android.car.internal.user.UserHelper;
import com.android.internal.R;
import com.android.internal.util.Preconditions;

import org.junit.Before;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.mockito.Captor;
import org.mockito.Mock;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * This class contains unit tests for the {@link CarUserService}.
 *
 * The following mocks are used:
 * <ol>
 * <li> {@link Context} provides system services and resources.
 * <li> {@link ActivityManager} provides current user and other calls.
 * <li> {@link UserManager} provides user creation and user info.
 * <li> {@link Resources} provides user icon.
 * <li> {@link Drawable} provides bitmap of user icon.
 * <ol/>
 */
abstract class BaseCarUserServiceTestCase extends AbstractExtendedMockitoTestCase {

    private static final String TAG = BaseCarUserServiceTestCase.class.getSimpleName();

    protected static final int NO_USER_INFO_FLAGS = 0;
    protected static final int NON_EXISTING_USER = 55; // must not be on mExistingUsers

    protected static final boolean HAS_CALLER_RESTRICTIONS = true;
    protected static final boolean NO_CALLER_RESTRICTIONS = false;

    protected static final int DEFAULT_TIMEOUT_MS = 15000;

    @Mock protected Context mMockContext;
    @Mock protected Context mApplicationContext;
    @Mock protected LocationManager mLocationManager;
    @Mock protected UserHalService mUserHal;
    @Mock protected ActivityManager mMockedActivityManager;
    @Mock protected UserManager mMockedUserManager;
    @Mock protected DevicePolicyManager mMockedDevicePolicyManager;
    @Mock protected Resources mMockedResources;
    @Mock protected Drawable mMockedDrawable;
    @Mock protected InitialUserSetter mInitialUserSetter;
    @Mock protected UserPreCreator mUserPreCreator;
    @Mock protected ICarResultReceiver mSwitchUserUiReceiver;
    @Mock protected PackageManager mPackageManager;
    @Mock protected CarUxRestrictionsManagerService mCarUxRestrictionService;
    @Mock protected ICarUxRestrictionsChangeListener mCarUxRestrictionsListener;
    @Mock protected ICarServiceHelper mICarServiceHelper;
    @Mock protected Handler mMockedHandler;
    @Mock protected UserHandleHelper mMockedUserHandleHelper;

    protected final BlockingUserLifecycleListener mUserLifecycleListener =
            BlockingUserLifecycleListener.forAnyEvent().build();

    @Captor protected ArgumentCaptor<UsersInfo> mUsersInfoCaptor;

    protected CarUserService mCarUserService;
    protected boolean mUser0TaskExecuted;

    // NOTE: Futures below should be used just once per test case, otherwise they could cause
    // failures
    protected final AndroidFuture<UserSwitchResult> mUserSwitchFuture = new AndroidFuture<>();
    protected final AndroidFuture<UserSwitchResult> mUserSwitchFuture2 = new AndroidFuture<>();
    protected final AndroidFuture<UserCreationResult> mUserCreationFuture = new AndroidFuture<>();
    protected final AndroidFuture<UserRemovalResult> mUserRemovalFuture = new AndroidFuture<>();

    protected final AndroidFuture<UserIdentificationAssociationResponse>
            mUserAssociationRespFuture = new AndroidFuture<>();
    protected final int mAsyncCallTimeoutMs = 100;
    protected final InitialUserInfoResponse mGetUserInfoResponse = new InitialUserInfoResponse();
    protected final SwitchUserResponse mSwitchUserResponse = new SwitchUserResponse();

    protected UserHandle mAdminUser;
    protected UserHandle mAnotherAdminUser;
    protected UserHandle mGuestUser;
    protected UserHandle mRegularUser;
    protected UserHandle mAnotherRegularUser;
    protected List<UserHandle> mExistingUsers;

    protected int mAdminUserId;
    protected int mAnotherAdminUserId;
    protected int mGuestUserId;
    protected int mRegularUserId;
    protected int mAnotherRegularUserId;

    protected final HandlerThread mHandlerThread = CarServiceUtils.getHandlerThread(
            getClass().getSimpleName());
    protected final Handler mHandler = new Handler(mHandlerThread.getLooper());

    protected BaseCarUserServiceTestCase(String... logTags) {
        super(logTags);
    }

    @Override
    protected void onSessionBuilder(CustomMockitoSessionBuilder builder) {
        builder
                .spyStatic(ActivityManager.class)
                .spyStatic(ActivityManagerHelper.class)
                // TODO(b/156299496): it cannot spy on UserManager, as it would slow down the tests
                // considerably (more than 5 minutes total, instead of just a couple seconds).
                // So, it's mocking UserHelper.isHeadlessSystemUser()
                // (on mockIsHeadlessSystemUser()) instead...
                .spyStatic(UserHelper.class)
                .spyStatic(UserHelperLite.class)
                .spyStatic(CarSystemProperties.class)
                .spyStatic(Binder.class);
    }

    /**
     * Initialize all of the objects with the @Mock annotation.
     */
    @Before
    public void setUpMocks() {
        doReturn(mApplicationContext).when(mMockContext).getApplicationContext();
        doReturn(mMockContext).when(mMockContext).createContextAsUser(any(), anyInt());
        doReturn(mLocationManager).when(mMockContext).getSystemService(Context.LOCATION_SERVICE);
        doReturn(InstrumentationRegistry.getTargetContext().getContentResolver())
                .when(mMockContext).getContentResolver();
        doReturn(false).when(mMockedUserManager).isUserUnlockingOrUnlocked(any());
        doReturn(mMockedResources).when(mMockContext).getResources();
        doReturn(mMockedDrawable).when(mMockedResources)
                .getDrawable(eq(R.drawable.ic_account_circle), eq(null));
        doReturn(mMockedDrawable).when(mMockedDrawable).mutate();
        doReturn(1).when(mMockedDrawable).getIntrinsicWidth();
        doReturn(1).when(mMockedDrawable).getIntrinsicHeight();
        mockUserHalSupported(true);
        mockUserHalUserAssociationSupported(true);
        doReturn(Optional.of(mAsyncCallTimeoutMs)).when(
                () -> CarSystemProperties.getUserHalTimeout());

        mCarUserService = newCarUserService(/* switchGuestUserBeforeGoingSleep= */ false);
    }

    @Before
    public void setUpUsers() {
        mAdminUser = expectAdminUserExists(mMockedUserHandleHelper, 100);
        mAnotherAdminUser = expectAdminUserExists(mMockedUserHandleHelper, 108);
        mGuestUser = expectGuestUserExists(mMockedUserHandleHelper, 111, /* isEphemeral= */ false);
        mRegularUser = expectRegularUserExists(mMockedUserHandleHelper, 222);
        mAnotherRegularUser = expectRegularUserExists(mMockedUserHandleHelper, 333);

        mExistingUsers = Arrays
                .asList(mAdminUser, mAnotherAdminUser, mGuestUser, mRegularUser,
                        mAnotherRegularUser);

        mAdminUserId = mAdminUser.getIdentifier();
        mAnotherAdminUserId = mAnotherAdminUser.getIdentifier();
        mGuestUserId = mGuestUser.getIdentifier();
        mRegularUserId = mRegularUser.getIdentifier();
        mAnotherRegularUserId = mAnotherRegularUser.getIdentifier();
    }

    // The responses must never contain null values.
    @Before
    public void fillInDefaultValues() {
        mGetUserInfoResponse.userToSwitchOrCreate =
                new android.hardware.automotive.vehicle.UserInfo();
        mGetUserInfoResponse.userLocales = new String();
        mGetUserInfoResponse.userNameToCreate = new String();
    }

    protected ICarUxRestrictionsChangeListener initService() {
        ArgumentCaptor<ICarUxRestrictionsChangeListener> listenerCaptor =
                ArgumentCaptor.forClass(ICarUxRestrictionsChangeListener.class);
        doNothing().when(mCarUxRestrictionService).registerUxRestrictionsChangeListener(
                listenerCaptor.capture(), eq(Display.DEFAULT_DISPLAY));

        mCarUserService.init();

        ICarUxRestrictionsChangeListener listener = listenerCaptor.getValue();
        assertWithMessage("init() didn't register ICarUxRestrictionsChangeListener")
                .that(listener).isNotNull();

        return listener;
    }

    protected void mockNoLogoutUserId() {
        mockLogoutUser(/* userHandle= */ null);
    }

    protected void mockLogoutUser(UserHandle userHandle) {
        when(mMockedDevicePolicyManager.getLogoutUser()).thenReturn(userHandle);
    }

    protected void verifyListenerOnEventInvoked(int expectedNewUserId, int expectedEventType)
            throws Exception {
        UserLifecycleEvent actualEvent = mUserLifecycleListener.waitForAnyEvent();
        assertThat(actualEvent.getEventType()).isEqualTo(expectedEventType);
        assertThat(actualEvent.getUserId()).isEqualTo(expectedNewUserId);
    }

    protected void verifyLastActiveUserSet(UserHandle user) {
        verify(mInitialUserSetter).setLastActiveUser(user.getIdentifier());
    }

    protected void associateParentChild(UserHandle parent, UserHandle child) {
        when(mMockedUserManager.isSameProfileGroup(parent, child)).thenReturn(true);
        when(mMockedUserManager.isSameProfileGroup(child, parent)).thenReturn(true);
    }

    protected void assertUserCreationInvalidArgumentsFailure(
            AndroidFuture<UserCreationResult> future) throws Exception {
        UserCreationResult result = assertBasicFieldsOnUserCreationFailure(future,
                UserCreationResult.STATUS_INVALID_REQUEST);
        assertThat(result.getInternalErrorMessage()).isNull();
    }

    protected void assertUserCreationInvalidArgumentsFailureWithInternalErrorMessage(
            AndroidFuture<UserCreationResult> future, String format, @Nullable Object... args)
                    throws Exception {
        assertUserCreationWithInternalErrorMessage(future,
                UserCreationResult.STATUS_INVALID_REQUEST, format, args);
    }

    protected void assertUserCreationWithInternalErrorMessage(
            AndroidFuture<UserCreationResult> future, int status, String format,
            @Nullable Object... args) throws Exception {
        UserCreationResult result = assertBasicFieldsOnUserCreationFailure(future, status);
        assertThat(result.getInternalErrorMessage()).isEqualTo(String.format(format, args));
    }

    private UserCreationResult assertBasicFieldsOnUserCreationFailure(
            AndroidFuture<UserCreationResult> future, int status) throws Exception {
        UserCreationResult result = getResult(future, "user creation");
        assertThat(result).isNotNull();
        assertThat(result.isSuccess()).isFalse();
        assertThat(result.getStatus()).isEqualTo(status);
        assertThat(result.getAndroidFailureStatus()).isNull();
        assertThat(result.getUser()).isNull();
        assertThat(result.getErrorMessage()).isNull();
        return result;
    }

    protected void createUserWithRestrictionsInvalidTypes(@NonNull String type) throws Exception {
        int flags = 0;
        AndroidFuture<UserCreationResult> future = new AndroidFuture<>();
        mCarUserService.createUser("name", type, flags, mAsyncCallTimeoutMs, future,
                HAS_CALLER_RESTRICTIONS);
        waitForHandlerThreadToFinish();
        assertUserCreationInvalidArgumentsFailureWithInternalErrorMessage(future,
                CarUserService.ERROR_TEMPLATE_INVALID_USER_TYPE_AND_FLAGS_COMBINATION, type, flags);
    }

    protected void createUserWithRestrictionsInvalidTypes(int flags) throws Exception {
        String userType = UserManager.USER_TYPE_FULL_SECONDARY;
        AndroidFuture<UserCreationResult> future = new AndroidFuture<UserCreationResult>();
        mCarUserService.createUser("name", userType, flags, mAsyncCallTimeoutMs, future,
                HAS_CALLER_RESTRICTIONS);
        waitForHandlerThreadToFinish();
        assertUserCreationInvalidArgumentsFailureWithInternalErrorMessage(future,
                CarUserService.ERROR_TEMPLATE_INVALID_USER_TYPE_AND_FLAGS_COMBINATION,
                userType, flags);
    }

    protected void mockCreateProfile(int profileOwner, String profileName, UserHandle profile) {
        Context userContext = mock(Context.class);
        UserManager userManager = mock(UserManager.class);
        when(mMockContext.createContextAsUser(UserHandle.of(profileOwner), /* flags= */ 0))
                .thenReturn(userContext);
        when(userContext.getSystemService(UserManager.class)).thenReturn(userManager);
        when(userManager.createProfile(eq(profileName), eq(UserManager.USER_TYPE_PROFILE_MANAGED),
                any())).thenReturn(profile);
    }

    protected void waitForHandlerThreadToFinish() {
        assertThat(mHandler.runWithScissors(() -> {}, DEFAULT_TIMEOUT_MS)).isTrue();
    }

    protected void createUser(@Nullable String name, @NonNull String userType, int flags,
            int timeoutMs, @NonNull AndroidFuture<UserCreationResult> receiver,
            boolean hasCallerRestrictions) {
        mCarUserService.createUser(name, userType, flags, timeoutMs, receiver,
                hasCallerRestrictions);
        waitForHandlerThreadToFinish();
    }

    protected void switchUser(@UserIdInt int userId, int timeoutMs,
            @NonNull AndroidFuture<UserSwitchResult> receiver) {
        mCarUserService.switchUser(userId, timeoutMs, receiver);
        waitForHandlerThreadToFinish();
    }

    protected void removeUser(@UserIdInt int userId,
            @NonNull AndroidFuture<UserRemovalResult> userRemovalFuture) {
        mCarUserService.removeUser(userId, userRemovalFuture);
        waitForHandlerThreadToFinish();
    }

    protected void removeUser(@UserIdInt int userId, boolean hasCallerRestrictions,
            @NonNull AndroidFuture<UserRemovalResult> userRemovalFuture) {
        mCarUserService.removeUser(userId, hasCallerRestrictions, userRemovalFuture);
        waitForHandlerThreadToFinish();
    }

    protected void startUserInBackground(@UserIdInt int userId,
            @NonNull AndroidFuture<UserStartResult> userStartResultFuture) {
        mCarUserService.startUserInBackground(userId, userStartResultFuture);
        waitForHandlerThreadToFinish();
    }

    protected void stopUser(@UserIdInt int userId,
            @NonNull AndroidFuture<UserStopResult> userStopResultFuture) {
        mCarUserService.stopUser(userId, userStopResultFuture);
        waitForHandlerThreadToFinish();
    }

    /**
     * Gets the result of a user switch call that was made using {@link #mUserSwitchFuture}.
     */
    @NonNull
    protected UserSwitchResult getUserSwitchResult(int userId) throws Exception {
        return getResult(mUserSwitchFuture, "result of switching user %d", userId);
    }

    /**
     * Gets the result of a user switch call that was made using {@link #mUserSwitchFuture2}.
     */
    @NonNull
    protected UserSwitchResult getUserSwitchResult2(int userId) throws Exception {
        return getResult(mUserSwitchFuture2, "result of switching user %d", userId);
    }

    /**
     * Gets the result of a user creation call that was made using {@link #mUserCreationFuture}.
     */
    @NonNull
    protected UserCreationResult getUserCreationResult() throws Exception {
        return getResult(mUserCreationFuture, "result of user creation");
    }

    /**
     * Gets the result of a user removal call that was made using {@link #mUserRemovalFuture}.
     */
    @NonNull
    protected UserRemovalResult getUserRemovalResult(int userId) throws Exception {
        return getResult(mUserRemovalFuture, "result of removing user %d", userId);
    }

    /**
     * Gets the result of setting a user identification association call that was made using
     * {@link #mUserAssociationRespFuture}.
     */
    @NonNull
    protected UserIdentificationAssociationResponse getUserAssociationRespResult()
            throws Exception {
        return getResult(mUserAssociationRespFuture, "result of getting user association");
    }

    protected CarUserService newCarUserService(boolean switchGuestUserBeforeGoingSleep) {
        when(mMockedResources
                .getBoolean(com.android.car.R.bool.config_switchGuestUserBeforeGoingSleep))
                .thenReturn(switchGuestUserBeforeGoingSleep);

        return new CarUserService(
                mMockContext,
                mUserHal,
                mMockedUserManager,
                mMockedUserHandleHelper,
                mMockedDevicePolicyManager,
                mMockedActivityManager,
                /* maxRunningUsers= */ 3,
                mInitialUserSetter,
                mUserPreCreator,
                mCarUxRestrictionService,
                mHandler);
    }

    /**
     * This method must be called for cases where the service infers the user id of the caller
     * using Binder - it's not worth the effort of mocking such (native) calls.
     */
    @NonNull
    protected UserHandle mockCurrentUserForBinderCalls() {
        int currentUserId = ActivityManager.getCurrentUser();
        Log.d(TAG, "testetUserIdentificationAssociation_ok(): current user is " + currentUserId);
        UserHandle currentUser = expectRegularUserExists(mMockedUserHandleHelper, currentUserId);

        return currentUser;
    }

    /**
     * Mock calls that generate a {@code UsersInfo}.
     */
    protected void mockExistingUsersAndCurrentUser(@NonNull UserHandle user)
            throws Exception {
        mockExistingUsers(mExistingUsers);
        mockCurrentUser(user);
    }

    protected void mockExistingUsersAndCurrentUser(@NonNull List<UserHandle> existingUsers,
            @NonNull UserHandle currentUser) throws Exception {
        mockExistingUsers(existingUsers);
        mockCurrentUser(currentUser);
    }

    protected void mockExistingUsers(@NonNull List<UserHandle> existingUsers) {
        mockUmGetUserHandles(mMockedUserManager, /* excludeDying= */ false, existingUsers);
    }

    protected void mockCurrentUser(@NonNull UserHandle user) throws Exception {
        mockGetCurrentUser(user.getIdentifier());
    }

    protected void mockRemoveUser(@NonNull UserHandle user) {
        mockRemoveUser(user, UserManager.REMOVE_RESULT_REMOVED);
    }

    protected void mockRemoveUser(@NonNull UserHandle user, @RemoveResult int result) {
        mockRemoveUser(user, /* overrideDevicePolicy= */ false, result);
    }

    protected void mockRemoveUser(@NonNull UserHandle user, boolean overrideDevicePolicy) {
        mockRemoveUser(user, overrideDevicePolicy, UserManager.REMOVE_RESULT_REMOVED);
    }

    protected void mockRemoveUser(@NonNull UserHandle user, boolean overrideDevicePolicy,
            @RemoveResult int result) {
        mockUmRemoveUserWhenPossible(mMockedUserManager, user, overrideDevicePolicy, result,
                (u) -> mCarUserService.onUserRemoved(u));
    }

    protected void mockRemoveUserNoCallback(@NonNull UserHandle user, @RemoveResult int result) {
        mockRemoveUserNoCallback(user, /* overrideDevicePolicy= */ false, result);
    }

    protected void mockRemoveUserNoCallback(@NonNull UserHandle user, boolean overrideDevicePolicy,
            @RemoveResult int result) {
        mockUmRemoveUserWhenPossible(mMockedUserManager, user, overrideDevicePolicy, result,
                /* listener= */ null);
    }

    protected void mockHalGetInitialInfo(@UserIdInt int currentUserId,
            @NonNull InitialUserInfoResponse response) {
        UsersInfo usersInfo = newUsersInfo(currentUserId);
        doAnswer((invocation) -> {
            Log.d(TAG, "Answering " + invocation + " with " + response);
            @SuppressWarnings("unchecked")
            HalCallback<InitialUserInfoResponse> callback =
                    (HalCallback<InitialUserInfoResponse>) invocation.getArguments()[3];
            callback.onResponse(HalCallback.STATUS_OK, response);
            return null;
        }).when(mUserHal).getInitialUserInfo(anyInt(), eq(mAsyncCallTimeoutMs),
                eq(usersInfo), notNull());
    }

    protected void mockIsHeadlessSystemUser(@UserIdInt int userId, boolean mode) {
        doReturn(mode).when(() -> UserHelperLite.isHeadlessSystemUser(userId));
    }

    protected void mockHalSwitch(@UserIdInt int currentUserId,
            @NonNull UserHandle androidTargetUser, @Nullable SwitchUserResponse response) {
        mockHalSwitch(currentUserId, HalCallback.STATUS_OK, response, androidTargetUser);
    }

    @NonNull
    protected ArgumentCaptor<CreateUserRequest> mockHalCreateUser(
            @HalCallbackStatus int callbackStatus, int responseStatus) {
        CreateUserResponse response = new CreateUserResponse();
        response.status = responseStatus;
        return mockHalCreateUser(callbackStatus, response);
    }

    @NonNull
    protected ArgumentCaptor<CreateUserRequest> mockHalCreateUser(
            @HalCallbackStatus int callbackStatus, CreateUserResponse response) {
        ArgumentCaptor<CreateUserRequest> captor = ArgumentCaptor.forClass(CreateUserRequest.class);
        doAnswer((invocation) -> {
            Log.d(TAG, "Answering " + invocation + " with " + response);
            @SuppressWarnings("unchecked")
            HalCallback<CreateUserResponse> callback =
                    (HalCallback<CreateUserResponse>) invocation.getArguments()[2];
            callback.onResponse(callbackStatus, response);
            return null;
        }).when(mUserHal).createUser(captor.capture(), eq(mAsyncCallTimeoutMs), notNull());
        return captor;
    }

    protected void mockHalCreateUserThrowsRuntimeException(Exception exception) {
        doThrow(exception).when(mUserHal).createUser(any(), eq(mAsyncCallTimeoutMs), notNull());
    }

    protected void mockCallerUid(int uid, boolean returnCorrectUid) throws Exception {
        String packageName = "packageName";
        String className = "className";
        when(mMockedResources.getString(anyInt())).thenReturn(packageName + "/" + className);
        when(mMockContext.createContextAsUser(any(), anyInt())).thenReturn(mMockContext);
        when(mMockContext.getPackageManager()).thenReturn(mPackageManager);

        if (returnCorrectUid) {
            when(mPackageManager.getPackageUid(any(), anyInt())).thenReturn(uid);
        } else {
            when(mPackageManager.getPackageUid(any(), anyInt())).thenReturn(uid + 1);
        }
    }

    protected BlockingAnswer<Void> mockHalSwitchLateResponse(@UserIdInt int currentUserId,
            @NonNull UserHandle androidTargetUser, @Nullable SwitchUserResponse response) {
        android.hardware.automotive.vehicle.UserInfo halTargetUser =
                new android.hardware.automotive.vehicle.UserInfo();
        halTargetUser.userId = androidTargetUser.getIdentifier();
        halTargetUser.flags = UserHalHelper.convertFlags(mMockedUserHandleHelper,
                androidTargetUser);
        UsersInfo usersInfo = newUsersInfo(currentUserId);
        SwitchUserRequest request = UserHalHelper.emptySwitchUserRequest();
        request.targetUser = halTargetUser;
        request.usersInfo = usersInfo;

        BlockingAnswer<Void> blockingAnswer = BlockingAnswer.forVoidReturn(10_000, (invocation) -> {
            Log.d(TAG, "Answering " + invocation + " with " + response);
            @SuppressWarnings("unchecked")
            HalCallback<SwitchUserResponse> callback = (HalCallback<SwitchUserResponse>) invocation
                    .getArguments()[2];
            callback.onResponse(HalCallback.STATUS_OK, response);
        });
        doAnswer(blockingAnswer).when(mUserHal).switchUser(eq(request), eq(mAsyncCallTimeoutMs),
                notNull());
        return blockingAnswer;
    }

    protected void mockHalSwitch(@UserIdInt int currentUserId,
            @HalCallback.HalCallbackStatus int callbackStatus,
            @Nullable SwitchUserResponse response, @NonNull UserHandle androidTargetUser) {
        android.hardware.automotive.vehicle.UserInfo halTargetUser =
                new android.hardware.automotive.vehicle.UserInfo();
        halTargetUser.userId = androidTargetUser.getIdentifier();
        halTargetUser.flags = UserHalHelper.convertFlags(mMockedUserHandleHelper,
                androidTargetUser);
        UsersInfo usersInfo = newUsersInfo(currentUserId);
        SwitchUserRequest request = UserHalHelper.emptySwitchUserRequest();
        request.targetUser = halTargetUser;
        request.usersInfo = usersInfo;

        doAnswer((invocation) -> {
            Log.d(TAG, "Answering " + invocation + " with " + response);
            @SuppressWarnings("unchecked")
            HalCallback<SwitchUserResponse> callback =
                    (HalCallback<SwitchUserResponse>) invocation.getArguments()[2];
            callback.onResponse(callbackStatus, response);
            return null;
        }).when(mUserHal).switchUser(eq(request), eq(mAsyncCallTimeoutMs), notNull());
    }

    protected void mockHalGetUserIdentificationAssociation(@NonNull UserHandle user,
            @NonNull int[] types, @NonNull int[] values,  @Nullable String errorMessage) {
        assertWithMessage("mismatch on number of types and values").that(types.length)
                .isEqualTo(values.length);

        UserIdentificationResponse response = new UserIdentificationResponse();
        response.numberAssociation = types.length;
        response.errorMessage = errorMessage;
        response.associations = new UserIdentificationAssociation[types.length];
        for (int i = 0; i < types.length; i++) {
            UserIdentificationAssociation association = new UserIdentificationAssociation();
            association.type = types[i];
            association.value = values[i];
            response.associations[i] = association;
        }

        when(mUserHal.getUserAssociation(isUserIdentificationGetRequest(user, types)))
                .thenReturn(response);
    }

    protected void mockHalSetUserIdentificationAssociationSuccess(@NonNull UserHandle user,
            @NonNull int[] types, @NonNull int[] values,  @Nullable String errorMessage) {
        assertWithMessage("mismatch on number of types and values").that(types.length)
                .isEqualTo(values.length);

        UserIdentificationResponse response = new UserIdentificationResponse();
        response.numberAssociation = types.length;
        response.errorMessage = errorMessage;
        response.associations = new UserIdentificationAssociation[types.length];
        for (int i = 0; i < types.length; i++) {
            UserIdentificationAssociation association = new UserIdentificationAssociation();
            association.type = types[i];
            association.value = values[i];
            response.associations[i] = association;
        }

        doAnswer((invocation) -> {
            Log.d(TAG, "Answering " + invocation + " with " + response);
            @SuppressWarnings("unchecked")
            UserIdentificationSetRequest request =
                    (UserIdentificationSetRequest) invocation.getArguments()[1];
            assertWithMessage("Wrong user on %s", request)
                    .that(request.userInfo.userId)
                    .isEqualTo(user.getIdentifier());
            assertWithMessage("Wrong flags on %s", request)
                    .that(request.userInfo.flags)
                    .isEqualTo(UserHalHelper.convertFlags(mMockedUserHandleHelper, user));
            @SuppressWarnings("unchecked")
            HalCallback<UserIdentificationResponse> callback =
                    (HalCallback<UserIdentificationResponse>) invocation.getArguments()[2];
            callback.onResponse(HalCallback.STATUS_OK, response);
            return null;
        }).when(mUserHal).setUserAssociation(eq(mAsyncCallTimeoutMs), notNull(), notNull());
    }

    protected void mockHalSetUserIdentificationAssociationFailure(@NonNull String errorMessage) {
        UserIdentificationResponse response = new UserIdentificationResponse();
        response.errorMessage = errorMessage;
        doAnswer((invocation) -> {
            Log.d(TAG, "Answering " + invocation + " with " + response);
            @SuppressWarnings("unchecked")
            HalCallback<UserIdentificationResponse> callback =
                    (HalCallback<UserIdentificationResponse>) invocation.getArguments()[2];
            callback.onResponse(HalCallback.STATUS_WRONG_HAL_RESPONSE, response);
            return null;
        }).when(mUserHal).setUserAssociation(eq(mAsyncCallTimeoutMs), notNull(), notNull());
    }

    protected void mockInteractAcrossUsersPermission(boolean granted) {
        int result = granted ? android.content.pm.PackageManager.PERMISSION_GRANTED
                : android.content.pm.PackageManager.PERMISSION_DENIED;
        doReturn(result).when(() -> ActivityManagerHelper.checkComponentPermission(
                eq(android.Manifest.permission.INTERACT_ACROSS_USERS),
                anyInt(), anyInt(), eq(true)));
        doReturn(result).when(() -> ActivityManagerHelper.checkComponentPermission(
                eq(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL),
                anyInt(), anyInt(), eq(true)));
    }

    protected void mockManageUsersPermission(String permission, boolean granted) {
        int result = granted ? android.content.pm.PackageManager.PERMISSION_GRANTED
                : android.content.pm.PackageManager.PERMISSION_DENIED;
        doReturn(result).when(() -> ActivityManagerHelper.checkComponentPermission(eq(permission),
                anyInt(), anyInt(), eq(true)));
    }

    protected void mockUserHalSupported(boolean result) {
        when(mUserHal.isSupported()).thenReturn(result);
    }

    protected void mockUserHalUserAssociationSupported(boolean result) {
        when(mUserHal.isUserAssociationSupported()).thenReturn(result);
    }

    protected CarUxRestrictions getUxRestrictions(boolean restricted) {
        int restrictions = CarUxRestrictions.UX_RESTRICTIONS_BASELINE;
        if (restricted) {
            restrictions |= CarUxRestrictions.UX_RESTRICTIONS_NO_SETUP;
        }
        return new CarUxRestrictions.Builder(/* reqOpt= */ false, restrictions,
                System.currentTimeMillis()).build();
    }

    protected void updateUxRestrictions(ICarUxRestrictionsChangeListener listener,
            boolean restricted) throws RemoteException {
        CarUxRestrictions restrictions = getUxRestrictions(restricted);
        Log.v(TAG, "updateUxRestrictions(" + restricted + "): sending UX restrictions ("
                + restrictions + ") to " + listener);
        listener.onUxRestrictionsChanged(restrictions);
    }


    protected void mockGetUxRestrictions(boolean restricted) {
        CarUxRestrictions restrictions = getUxRestrictions(restricted);
        Log.v(TAG, "mockUxRestrictions(" + restricted + ") mocking getCurrentUxRestrictions() to "
                + "return " + restrictions);
        when(mCarUxRestrictionService.getCurrentUxRestrictions()).thenReturn(restrictions);
    }

    /**
     * Asserts a {@link UsersInfo} that was created based on {@link #mockCurrentUsers(UserInfo)}.
     */
    protected void assertDefaultUsersInfo(UsersInfo actual, UserHandle currentUser) {
        // TODO(b/150413515): figure out why this method is not called in other places
        assertThat(actual).isNotNull();
        assertSameUser(actual.currentUser, currentUser);
        assertThat(actual.numberUsers).isEqualTo(mExistingUsers.size());
        for (int i = 0; i < actual.numberUsers; i++) {
            assertSameUser(actual.existingUsers[i], mExistingUsers.get(i));
        }
    }

    protected void assertSameUser(android.hardware.automotive.vehicle.UserInfo halUser,
            UserHandle androidUser) {
        assertThat(halUser.userId).isEqualTo(androidUser.getIdentifier());

        assertWithMessage("flags mismatch: hal=%s, android=%s",
                halUser.flags,
                UserHalHelper.convertFlags(mMockedUserHandleHelper, androidUser))
                .that(halUser.flags).isEqualTo(
                        UserHalHelper.convertFlags(mMockedUserHandleHelper, androidUser));

    }

    protected void verifyUserRemoved(@UserIdInt int userId) {
        verify(mMockedUserManager).removeUser(UserHandle.of(userId));
    }

    protected void verifyNoUserRemoved() {
        verify(mMockedUserManager, never()).removeUserWhenPossible(any(), anyBoolean());
        verify(mMockedUserManager, never()).removeUser(any());
    }

    protected void verifyAnyUserSwitch() throws Exception {
        verify(mMockedActivityManager).switchUser(any());
    }

    protected void verifyNoUserSwitch() throws Exception {
        verify(mMockedActivityManager, never()).switchUser(any());
    }

    // Note: tests must explicitly call it, as Mockito would return 0 by default, which is the same
    // value of UserManager.USER_OPERATION_SUCCESS
    protected void verifyLogoutUser() {
        verify(mMockedDevicePolicyManager).logoutUser();
    }

    protected void verifyNoLogoutUser() {
        verify(mMockedDevicePolicyManager, never()).logoutUser();
    }

    @NonNull
    protected UsersInfo newUsersInfo(@UserIdInt int currentUserId) {
        UsersInfo infos = UserHalHelper.emptyUsersInfo();
        infos.numberUsers = mExistingUsers.size();
        boolean foundCurrentUser = false;
        infos.existingUsers = new android.hardware.automotive.vehicle.UserInfo[infos.numberUsers];
        int i = 0;
        for (UserHandle handle : mExistingUsers) {
            android.hardware.automotive.vehicle.UserInfo existingUser =
                    new android.hardware.automotive.vehicle.UserInfo();
            int flags = 0;
            if (handle.getIdentifier() == UserHandle.USER_SYSTEM) {
                flags |= android.hardware.automotive.vehicle.UserInfo.USER_FLAG_SYSTEM;
            }
            if (mMockedUserHandleHelper.isAdminUser(handle)) {
                flags |= android.hardware.automotive.vehicle.UserInfo.USER_FLAG_ADMIN;
            }
            if (mMockedUserHandleHelper.isGuestUser(handle)) {
                flags |= android.hardware.automotive.vehicle.UserInfo.USER_FLAG_GUEST;
            }
            if (mMockedUserHandleHelper.isEphemeralUser(handle)) {
                flags |= android.hardware.automotive.vehicle.UserInfo.USER_FLAG_EPHEMERAL;
            }
            existingUser.userId = handle.getIdentifier();
            existingUser.flags = flags;
            if (handle.getIdentifier() == currentUserId) {
                foundCurrentUser = true;
                infos.currentUser.userId = handle.getIdentifier();
                infos.currentUser.flags = flags;
            }
            infos.existingUsers[i] = existingUser;
            i++;
        }
        Preconditions.checkArgument(foundCurrentUser,
                "no user with id " + currentUserId + " on " + mExistingUsers);
        return infos;
    }

    protected void assertNoPostSwitch() {
        verify(mUserHal, never()).postSwitchResponse(any());
    }

    protected void assertPostSwitch(int requestId, int currentId, int targetId) {
        verify(mUserHal).postSwitchResponse(isSwitchUserRequest(requestId, currentId, targetId));
    }

    protected void assertHalSwitch(int currentId, int targetId) {
        verify(mUserHal).switchUser(isSwitchUserRequest(0, currentId, targetId),
                eq(mAsyncCallTimeoutMs), any());
    }

    protected void assertHalSwitchAnyUser() {
        verify(mUserHal).switchUser(any(), eq(mAsyncCallTimeoutMs), any());
    }

    protected void assertNoHalUserSwitch() {
        verify(mUserHal, never()).switchUser(any(), anyInt(), any());
    }

    protected void assertNoHalUserCreation() {
        verify(mUserHal, never()).createUser(any(), anyInt(), any());
    }

    protected void assertNoHalUserRemoval() {
        verify(mUserHal, never()).removeUser(any());
    }

    protected void assertHalRemove(@NonNull UserHandle currentUser,
            @NonNull UserHandle removeUser) {
        assertHalRemove(currentUser, removeUser, /* overrideDevicePolicy= */ false);
    }

    protected void assertHalRemove(@NonNull UserHandle currentUser, @NonNull UserHandle removeUser,
            boolean overrideDevicePolicy) {
        verify(mMockedUserManager).removeUserWhenPossible(removeUser, overrideDevicePolicy);
        ArgumentCaptor<RemoveUserRequest> requestCaptor =
                ArgumentCaptor.forClass(RemoveUserRequest.class);
        verify(mUserHal).removeUser(requestCaptor.capture());
        RemoveUserRequest request = requestCaptor.getValue();
        assertThat(request.removedUserInfo.userId).isEqualTo(removeUser.getIdentifier());
        assertThat(request.removedUserInfo.flags)
                .isEqualTo(UserHalHelper.convertFlags(mMockedUserHandleHelper, removeUser));
        assertThat(request.usersInfo.currentUser.userId).isEqualTo(currentUser.getIdentifier());
    }

    protected void assertUserRemovalResultStatus(UserRemovalResult result,
            @UserRemovalResult.Status int expectedStatus) {
        int actualStatus = result.getStatus();
        assertWithMessage("UserRemovalResult status (where %s=%s, %s=%s)",
                expectedStatus, UserRemovalResult.statusToString(expectedStatus),
                actualStatus, UserRemovalResult.statusToString(actualStatus))
                .that(actualStatus).isEqualTo(expectedStatus);
    }

    @NonNull
    protected static SwitchUserRequest isSwitchUserRequest(int requestId,
            @UserIdInt int currentUserId, @UserIdInt int targetUserId) {
        return argThat(new SwitchUserRequestMatcher(requestId, currentUserId, targetUserId));
    }

    protected void sendUserLifecycleEvent(@UserIdInt int fromUserId, @UserIdInt int toUserId,
            @UserLifecycleEventType int eventType) {
        mCarUserService.onUserLifecycleEvent(eventType, fromUserId,
                toUserId);
    }

    protected void sendUserUnlockedEvent(@UserIdInt int userId) {
        sendUserLifecycleEvent(/* fromUser */ 0, userId,
                CarUserManager.USER_LIFECYCLE_EVENT_TYPE_UNLOCKED);
    }

    protected void sendUserSwitchingEvent(@UserIdInt int fromUserId, @UserIdInt int toUserId) {
        sendUserLifecycleEvent(fromUserId, toUserId,
                CarUserManager.USER_LIFECYCLE_EVENT_TYPE_SWITCHING);
    }

    @NonNull
    protected UserIdentificationGetRequest isUserIdentificationGetRequest(
            @NonNull UserHandle user, @NonNull int[] types) {
        return argThat(new UserIdentificationGetRequestMatcher(user, types));
    }

    protected final class UserIdentificationGetRequestMatcher implements
            ArgumentMatcher<UserIdentificationGetRequest> {

        private final @UserIdInt int mUserId;
        private final int mHalFlags;
        private final @NonNull int[] mTypes;

        private UserIdentificationGetRequestMatcher(@NonNull UserHandle user,
                @NonNull int[] types) {
            mUserId = user.getIdentifier();
            mHalFlags = UserHalHelper.convertFlags(mMockedUserHandleHelper, user);
            mTypes = types;
        }

        @Override
        public boolean matches(UserIdentificationGetRequest argument) {
            if (argument == null) {
                Log.w(TAG, "null argument");
                return false;
            }
            if (argument.userInfo.userId != mUserId) {
                Log.w(TAG, "wrong user id on " + argument + "; expected " + mUserId);
                return false;
            }
            if (argument.userInfo.flags != mHalFlags) {
                Log.w(TAG, "wrong flags on " + argument + "; expected " + mHalFlags);
                return false;
            }
            if (argument.numberAssociationTypes != mTypes.length) {
                Log.w(TAG, "wrong numberAssociationTypes on " + argument + "; expected "
                        + mTypes.length);
                return false;
            }
            if (argument.associationTypes.length != mTypes.length) {
                Log.w(TAG, "wrong associationTypes size on " + argument + "; expected "
                        + mTypes.length);
                return false;
            }
            for (int i = 0; i < mTypes.length; i++) {
                if (argument.associationTypes[i] != mTypes[i]) {
                    Log.w(TAG, "wrong association type on index " + i + " on " + argument
                            + "; expected types: " + Arrays.toString(mTypes));
                    return false;
                }
            }
            Log.d(TAG, "Good News, Everyone! " + argument + " matches " + this);
            return true;
        }

        @Override
        public String toString() {
            return "isUserIdentificationGetRequest(userId=" + mUserId + ", flags="
                    + UserHalHelper.userFlagsToString(mHalFlags) + ", types="
                    + Arrays.toString(mTypes) + ")";
        }
    }

    static final class SwitchUserRequestMatcher
            implements ArgumentMatcher<SwitchUserRequest> {
        private static final String MY_TAG = UsersInfo.class.getSimpleName();

        private final int mRequestId;
        private final @UserIdInt int mCurrentUserId;
        private final @UserIdInt int mTargetUserId;


        private SwitchUserRequestMatcher(int requestId, @UserIdInt int currentUserId,
                @UserIdInt int targetUserId) {
            mCurrentUserId = currentUserId;
            mTargetUserId = targetUserId;
            mRequestId = requestId;
        }

        @Override
        public boolean matches(SwitchUserRequest argument) {
            if (argument == null) {
                Log.w(MY_TAG, "null argument");
                return false;
            }
            if (argument.usersInfo.currentUser.userId != mCurrentUserId) {
                Log.w(MY_TAG,
                        "wrong current user id on " + argument + "; expected " + mCurrentUserId);
                return false;
            }

            if (argument.targetUser.userId != mTargetUserId) {
                Log.w(MY_TAG,
                        "wrong target user id on " + argument + "; expected " + mTargetUserId);
                return false;
            }

            if (argument.requestId != mRequestId) {
                Log.w(MY_TAG,
                        "wrong request Id on " + argument + "; expected " + mTargetUserId);
                return false;
            }

            Log.d(MY_TAG, "Good News, Everyone! " + argument + " matches " + this);
            return true;
        }
    }
}