summaryrefslogtreecommitdiff
path: root/tests/unittests/src/com/android/server/healthconnect/migration/MigrationStateManagerTest.java
blob: fc9c2a3e7ffee686d073a4a837d7c99643d941ec (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
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
/*
 * Copyright (C) 2023 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.server.healthconnect.migration;

import static android.health.connect.HealthConnectDataState.MIGRATION_STATE_ALLOWED;
import static android.health.connect.HealthConnectDataState.MIGRATION_STATE_APP_UPGRADE_REQUIRED;
import static android.health.connect.HealthConnectDataState.MIGRATION_STATE_COMPLETE;
import static android.health.connect.HealthConnectDataState.MIGRATION_STATE_IDLE;
import static android.health.connect.HealthConnectDataState.MIGRATION_STATE_IN_PROGRESS;
import static android.health.connect.HealthConnectDataState.MIGRATION_STATE_MODULE_UPGRADE_REQUIRED;

import static com.android.server.healthconnect.migration.MigrationConstants.CURRENT_STATE_START_TIME_KEY;
import static com.android.server.healthconnect.migration.MigrationConstants.HAVE_CANCELED_OLD_MIGRATION_JOBS_KEY;
import static com.android.server.healthconnect.migration.MigrationConstants.HAVE_RESET_MIGRATION_STATE_KEY;
import static com.android.server.healthconnect.migration.MigrationConstants.IDLE_TIMEOUT_REACHED_KEY;
import static com.android.server.healthconnect.migration.MigrationConstants.IN_PROGRESS_TIMEOUT_REACHED_KEY;
import static com.android.server.healthconnect.migration.MigrationConstants.MIGRATION_COMPLETE_JOB_NAME;
import static com.android.server.healthconnect.migration.MigrationConstants.MIGRATION_PAUSE_JOB_NAME;
import static com.android.server.healthconnect.migration.MigrationConstants.MIGRATION_STARTS_COUNT_KEY;
import static com.android.server.healthconnect.migration.MigrationConstants.MIGRATION_STATE_PREFERENCE_KEY;
import static com.android.server.healthconnect.migration.MigrationConstants.MIN_DATA_MIGRATION_SDK_EXTENSION_VERSION_KEY;
import static com.android.server.healthconnect.migration.MigrationConstants.PREMATURE_MIGRATION_TIMEOUT_DATE;
import static com.android.server.healthconnect.migration.MigrationTestUtils.MOCK_CERTIFICATE_ONE;
import static com.android.server.healthconnect.migration.MigrationTestUtils.MOCK_CERTIFICATE_TWO;
import static com.android.server.healthconnect.migration.MigrationTestUtils.MOCK_CONFIGURED_PACKAGE;
import static com.android.server.healthconnect.migration.MigrationTestUtils.MOCK_UNCONFIGURED_PACKAGE_ONE;
import static com.android.server.healthconnect.migration.MigrationTestUtils.PERMISSIONS_TO_CHECK;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import android.content.Context;
import android.content.pm.InstallSourceInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.content.pm.SigningInfo;
import android.content.res.Resources;
import android.health.connect.HealthConnectDataState;
import android.os.Build;
import android.os.UserHandle;
import android.os.ext.SdkExtensions;

import androidx.test.runner.AndroidJUnit4;

import com.android.dx.mockito.inline.extended.ExtendedMockito;
import com.android.server.healthconnect.HealthConnectDeviceConfigManager;
import com.android.server.healthconnect.migration.MigrationStateManager.IllegalMigrationStateException;
import com.android.server.healthconnect.storage.datatypehelpers.PreferenceHelper;

import libcore.util.HexEncoding;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.MockitoSession;
import org.mockito.quality.Strictness;

import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/** Test class for the MigrationStateManager class. */
@RunWith(AndroidJUnit4.class)
public class MigrationStateManagerTest {
    @Mock private Context mContext;
    @Mock private PackageManager mPackageManager;
    @Mock private PreferenceHelper mPreferenceHelper;
    @Mock private Resources mResources;
    @Mock private PackageInfo mPackageInfo;
    @Mock private SigningInfo mSigningInfo;
    @Mock private MockListener mMockListener;
    @Mock private HealthConnectDeviceConfigManager mHealthConnectDeviceConfigManager;
    private MigrationStateManager mMigrationStateManager;
    private MockitoSession mStaticMockSession;
    private static final UserHandle DEFAULT_USER_HANDLE = UserHandle.of(UserHandle.myUserId());
    private static final long EXECUTION_TIME_BUFFER_MOCK_VALUE =
            TimeUnit.MINUTES.toMillis(
                    HealthConnectDeviceConfigManager
                            .EXECUTION_TIME_BUFFER_MINUTES_DEFAULT_FLAG_VALUE);
    private static final Duration NON_IDLE_STATE_TIMEOUT_MOCK_VALUE =
            Duration.ofDays(
                    HealthConnectDeviceConfigManager
                            .NON_IDLE_STATE_TIMEOUT_DAYS_DEFAULT_FLAG_VALUE);
    private static final int MAX_START_MIGRATION_CALLS_MOCK_VALUE =
            HealthConnectDeviceConfigManager.MAX_START_MIGRATION_CALLS_DEFAULT_FLAG_VALUE;

    @Before
    public void setUp() {
        mStaticMockSession =
                ExtendedMockito.mockitoSession()
                        .mockStatic(PreferenceHelper.class)
                        .mockStatic(MigrationStateChangeJob.class)
                        .mockStatic(HexEncoding.class)
                        .mockStatic(HealthConnectDeviceConfigManager.class)
                        .strictness(Strictness.LENIENT)
                        .startMocking();
        MockitoAnnotations.initMocks(this);
        when(mContext.getResources()).thenReturn(mResources);
        when(mResources.getIdentifier(anyString(), anyString(), anyString())).thenReturn(1);
        when(mResources.getString(anyInt())).thenReturn(MOCK_CONFIGURED_PACKAGE);
        when(mContext.getPackageManager()).thenReturn(mPackageManager);
        when(PreferenceHelper.getInstance()).thenReturn(mPreferenceHelper);
        when(HealthConnectDeviceConfigManager.getInitialisedInstance())
                .thenReturn(mHealthConnectDeviceConfigManager);
        when(mHealthConnectDeviceConfigManager.getExecutionTimeBuffer())
                .thenReturn(EXECUTION_TIME_BUFFER_MOCK_VALUE);
        when(mHealthConnectDeviceConfigManager.getNonIdleStateTimeoutPeriod())
                .thenReturn(NON_IDLE_STATE_TIMEOUT_MOCK_VALUE);
        when(mHealthConnectDeviceConfigManager.getMaxStartMigrationCalls())
                .thenReturn(MAX_START_MIGRATION_CALLS_MOCK_VALUE);
        MigrationStateManager.initializeInstance(DEFAULT_USER_HANDLE.getIdentifier());
        mMigrationStateManager = MigrationStateManager.getInitialisedInstance();
        mMigrationStateManager.clearListeners();
        mMigrationStateManager.addStateChangedListener(mMockListener::onMigrationStateChanged);
    }

    @After
    public void tearDown() {
        mMigrationStateManager.clearListeners();
        clearInvocations(mPreferenceHelper);
        mStaticMockSession.finishMocking();
    }

    /**
     * Tests on package install method if the package is migration aware. Expected behavior: Move to
     * allowed state.
     */
    @Test
    public void testOnPackageInstalledOrChanged_fromIdleState_migrationAwarePackage() {
        setMigrationState(MIGRATION_STATE_IDLE);
        // Configure migration aware package available
        configureMigrationAwarePackage();
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyStateChange(MIGRATION_STATE_ALLOWED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on package install method if the package is migration unaware. Expected behavior: Move
     * to app upgrade required state.
     */
    @Test
    public void testOnPackageInstalledOrChanged_fromIdleState_migrationUnawarePackage()
            throws PackageManager.NameNotFoundException {
        setMigrationState(MIGRATION_STATE_IDLE);
        // configure migration unaware package available
        configureMigrationUnAwarePackage();
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyStateChange(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /** Expected behavior: No state change. */
    @Test
    public void testOnPackageInstalledOrChanged_fromIdleState_migrationUnawareStubPackage()
            throws PackageManager.NameNotFoundException {
        setMigrationState(MIGRATION_STATE_IDLE);
        // configure migration unaware package available
        configureMigrationUnAwarePackage();
        configureStubMigratorPackage();
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyNoStateChange();
    }

    /** Expected behavior: Move to allowed state. */
    @Test
    public void
            testOnPackageInstalledOrChanged_fromAppUpgradeRequiredState_migrationAwarePackage() {
        setMigrationState(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        // configure migration unaware package available
        configureMigrationAwarePackage();
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyStateChange(MIGRATION_STATE_ALLOWED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on package install or change in appUpgradeRequired state.If package is migration
     * unaware, there shouldn't be any state change. Expected behavior: No state change.
     */
    @Test
    public void
            testOnPackageInstalledOrChanged_fromAppUpgradeRequiredState_migrationUnAwarePackage()
                    throws PackageManager.NameNotFoundException {
        setMigrationState(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        // configure migration unaware package available
        configureMigrationUnAwarePackage();
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyNoStateChange();
        verifyNoJobCancelled();
        verifyNoJobScheduled();
    }

    /**
     * Package install/change should not have any effect to the state with this state. Expected
     * behavior: No state change.
     */
    @Test
    public void testOnPackageInstalledOrChanged_fromAllowedState() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_ALLOWED);
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyNoStateChange();
        verifyNoJobCancelled();
        verifyNoJobScheduled();
    }

    /**
     * Package install/change should not have any effect to the state with this state. Expected
     * behavior: No state change.
     */
    @Test
    public void testOnPackageInstalledOrChanged_fromInProgressState() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_IN_PROGRESS);
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyNoStateChange();
        verifyNoJobCancelled();
        verifyNoJobScheduled();
    }

    /**
     * Package install/change should not have any effect to the state with this state. Expected
     * behavior: No state change.
     */
    @Test
    public void testOnPackageInstalledOrChanged_fromModuleUpgradeRequiredState() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_MODULE_UPGRADE_REQUIRED);
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyNoStateChange();
        verifyNoJobCancelled();
        verifyNoJobScheduled();
    }

    /**
     * Package install/change should not have any effect to the state with this state. Expected
     * behavior: No state change.
     */
    @Test
    public void testOnPackageInstalledOrChanged_fromCompleteState() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_COMPLETE);
        mMigrationStateManager.onPackageInstalledOrChanged(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyNoStateChange();
        verifyNoJobCancelled();
        verifyNoJobScheduled();
    }

    /** Expected behavior: No state change. */
    @Test
    public void testOnPackageRemoved_migratorPackageExists_nonMigratorPackagePassed() {
        configureMigrationAwarePackage();
        when(mResources.getIdentifier(anyString(), any(), any())).thenReturn(1);
        setMigrationState(MIGRATION_STATE_ALLOWED);
        mMigrationStateManager.onPackageRemoved(mContext, MOCK_UNCONFIGURED_PACKAGE_ONE);
        verifyNoMoreInteractions(mPreferenceHelper);
        verifyNoStateChange();
        verifyNoJobCancelled();
        verifyNoJobScheduled();
    }

    /**
     * Tests on package removed while migration is in idle state. Expected behavior: Move to
     * complete state.
     */
    @Test
    public void testOnPackageRemoved_fromIdleState_migrationAwarePackage() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_IDLE);
        mMigrationStateManager.onPackageRemoved(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
        verifyNoJobScheduled();
    }

    /**
     * Tests on package removed while migration is in app upgrade required state. Expected behavior:
     * Move to complete state.
     */
    @Test
    public void testOnPackageRemoved_fromAppUpgradeRequiredState_migrationAwarePackage() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        mMigrationStateManager.onPackageRemoved(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
        verifyNoJobScheduled();
    }

    /**
     * Tests on package removed while migration is in module upgrade required state. Expected
     * behavior: Move to complete state.
     */
    @Test
    public void testOnPackageRemoved_fromModuleUpgradeRequiredState_migrationAwarePackage() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_MODULE_UPGRADE_REQUIRED);
        mMigrationStateManager.onPackageRemoved(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
        verifyNoJobScheduled();
    }

    /**
     * Tests on package removed while migration is in allowed state. Expected behavior: Move to
     * complete state.
     */
    @Test
    public void testOnPackageRemoved_fromAllowedState_migrationAwarePackage() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_ALLOWED);
        mMigrationStateManager.onPackageRemoved(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
        verifyNoJobScheduled();
    }

    /**
     * Tests on package removed while migration is in progress state. Expected behavior: Move to
     * complete state.
     */
    @Test
    public void testOnPackageRemoved_fromInProgressState_migrationAwarePackage() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_IN_PROGRESS);
        mMigrationStateManager.onPackageRemoved(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
        verifyNoJobScheduled();
    }

    /** Expected behavior: No state change. */
    @Test
    public void testOnPackageRemoved_fromCompleteState_migrationAwarePackage() {
        configureMigrationAwarePackage();
        setMigrationState(MIGRATION_STATE_COMPLETE);
        mMigrationStateManager.onPackageRemoved(mContext, MOCK_CONFIGURED_PACKAGE);
        verifyNoStateChange();
        verifyNoJobCancelled();
        verifyNoJobScheduled();
    }

    /** Expected behavior: Move to allowed state. */
    @Test
    public void
            testReconcilePackageChangesWithStates_fromIdleState_migrationAwarePackageAvailable() {
        setMigrationState(MIGRATION_STATE_IDLE);
        // Configure migration aware package available
        configureMigrationAwarePackage();
        ExtendedMockito.doReturn(true)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyStateChange(MIGRATION_STATE_ALLOWED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /** Expected behavior: Move to app upgrade required state. */
    @Test
    public void
            testReconcilePackageChangesWithStates_fromIdleState_migrationUnawarePackageAvailable()
                    throws PackageManager.NameNotFoundException {
        setMigrationState(MIGRATION_STATE_IDLE);
        // Configure migration unaware package available
        configureMigrationUnAwarePackage();
        ExtendedMockito.doReturn(true)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyStateChange(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /** Expected behavior: No state change. */
    @Test
    public void testReconcilePackageChangesWithStates_fromIdleState_migrationUnawareStubPackage()
            throws PackageManager.NameNotFoundException {
        setMigrationState(MIGRATION_STATE_IDLE);
        // Configure migration unaware package available
        configureMigrationUnAwarePackage();
        configureStubMigratorPackage();
        ExtendedMockito.doReturn(true)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoStateChange();
    }

    /** Expected behavior: No state change */
    @Test
    public void testReconcilePackageChangesWithStates_fromIdleState_noMigratorPackageAvailable() {
        setMigrationState(MIGRATION_STATE_IDLE);
        // Configure no migrator package available
        configureNoMigratorPackage();
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests if migration state is ALLOWED and there is no migrator package, migration should be
     * completed. Expected behavior: Move to complete state.
     */
    @Test
    public void
            testReconcilePackageChangesWithStates_fromAllowedState_noMigratorPackageAvailable() {
        setMigrationState(MIGRATION_STATE_ALLOWED);
        // Configure no migrator package available
        configureNoMigratorPackage();
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
    }

    /**
     * Tests on user boot/switch with the module sdk extension version equal to the one saved in
     * preferences. Expected behavior: Move to allowed state, and schedule a migration completion
     * job.
     */
    @Test
    public void testHandleIsUpdateStillRequired_isMinSdkExtensionVersion() {
        setMigrationState(MIGRATION_STATE_MODULE_UPGRADE_REQUIRED);
        configureMigrationAwarePackage();
        when(mPreferenceHelper.getPreference(MIN_DATA_MIGRATION_SDK_EXTENSION_VERSION_KEY))
                .thenReturn(
                        String.valueOf(
                                SdkExtensions.getExtensionVersion(
                                        Build.VERSION_CODES.UPSIDE_DOWN_CAKE)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyStateChange(MIGRATION_STATE_ALLOWED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on user boot/switch with the module sdk extension version earlier than the one saved in
     * preferences. Expected behavior: No state change.
     */
    @Test
    public void testHandleIsUpdateStillRequired_isNotMinSdkExtensionVersion() {
        setMigrationState(MIGRATION_STATE_MODULE_UPGRADE_REQUIRED);
        configureMigrationAwarePackage();
        when(mPreferenceHelper.getPreference(MIN_DATA_MIGRATION_SDK_EXTENSION_VERSION_KEY))
                .thenReturn(
                        String.valueOf(
                                SdkExtensions.getExtensionVersion(
                                                Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
                                        + 1));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoStateChange();
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on user boot/switch while no migration aware package installed. Expected behavior: Move
     * to complete state.
     */
    @Test
    public void testHandleIsUpdateStillRequired_noMigratorPackageAvailable() {
        setMigrationState(MIGRATION_STATE_MODULE_UPGRADE_REQUIRED);
        configureNoMigratorPackage();
        when(mPreferenceHelper.getPreference(MIN_DATA_MIGRATION_SDK_EXTENSION_VERSION_KEY))
                .thenReturn(
                        String.valueOf(
                                SdkExtensions.getExtensionVersion(
                                                Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
                                        + 1));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
    }

    /**
     * Tests state change no when app upgrade is required and there is no migration aware package.
     * Expected behavior: Move to complete state.
     */
    @Test
    public void
            testReconcilePackageChangesWithStates_fromAppUpgradeRequiredState_noMigratorPackage() {
        setMigrationState(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        configureNoMigratorPackage();
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
    }

    /**
     * Tests state change no when app upgrade is required and there is a migration aware package.
     * Expected behavior: Move to allowed state.
     */
    @Test
    public void
            testReconcilePackageChangesWithStates_fromAppUpgradeRequiredState_migratorPackage() {
        setMigrationState(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        configureMigrationAwarePackage();
        ExtendedMockito.doReturn(true)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyStateChange(MIGRATION_STATE_ALLOWED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on user boot/switch while migration state is in_progress and there is no migration
     * aware package. Expected behavior: Move to complete state.
     */
    @Test
    public void
            testReconcilePackageChangesWithStates_fromInProgressState_noMigratorPackageAvailable() {
        setMigrationState(MIGRATION_STATE_IN_PROGRESS);
        // Configure no migrator package available
        configureNoMigratorPackage();
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
    }

    /**
     * Tests on user boot/switch while migration state is in_progress and there is a migration aware
     * package. Expected behavior: No state change.
     */
    @Test
    public void
            testReconcilePackageChangesWithStates_fromInProgressState_migratorPackageAvailable() {
        setMigrationState(MIGRATION_STATE_IN_PROGRESS);
        // Configure a migrator package available
        configureMigrationAwarePackage();
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoStateChange();
        verifyCancelAllJobs();
        verifyScheduleMigrationPauseJob();
    }

    /**
     * Tests on user boot/switch while migration state is complete. Expected behavior: No state
     * change.
     */
    @Test
    public void testReconcilePackageChangesWithStates_fromCompleteState() {
        setMigrationState(MIGRATION_STATE_COMPLETE);
        // Configure a migrator package available
        configureMigrationAwarePackage();
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoStateChange();
        verifyCancelAllJobs();
        verifyNoJobScheduled();
    }

    @Test
    public void testStartMigration_startMigrationCountIsUpdated() {
        int count = 0;
        setMigrationState(MIGRATION_STATE_ALLOWED);
        when(mPreferenceHelper.getPreference(eq(MIGRATION_STARTS_COUNT_KEY)))
                .thenReturn(String.valueOf(count));
        mMigrationStateManager.updateMigrationState(mContext, MIGRATION_STATE_IN_PROGRESS);
        verify(mPreferenceHelper)
                .insertOrReplacePreference(MIGRATION_STARTS_COUNT_KEY, String.valueOf(count + 1));
    }

    @Test
    public void testPauseMigration_maxStartMigrationCountReached_shouldCompleteMigration() {
        int maxStartMigrationCount = MAX_START_MIGRATION_CALLS_MOCK_VALUE;
        setMigrationState(MIGRATION_STATE_IN_PROGRESS);
        when(mPreferenceHelper.getPreference(eq(MIGRATION_STARTS_COUNT_KEY)))
                .thenReturn(String.valueOf(maxStartMigrationCount));
        mMigrationStateManager.updateMigrationState(mContext, MIGRATION_STATE_ALLOWED);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        ExtendedMockito.verify(() -> MigrationStateChangeJob.cancelAllJobs(eq(mContext)));
    }

    @Ignore("b/294458689")
    @Test
    public void testPauseMigration_maxStartMigrationCountNotReached_shouldNotCompleteMigration() {
        int maxStartMigrationCount = MAX_START_MIGRATION_CALLS_MOCK_VALUE;
        setMigrationState(MIGRATION_STATE_IN_PROGRESS);
        when(mPreferenceHelper.getPreference(eq(MIGRATION_STARTS_COUNT_KEY)))
                .thenReturn(String.valueOf(maxStartMigrationCount - 1));
        mMigrationStateManager.updateMigrationState(mContext, MIGRATION_STATE_ALLOWED);
        verifyStateChange(MIGRATION_STATE_ALLOWED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Expected behavior: - Change state, - Cancel any completion job available, - Schedule new
     * pause job
     */
    @Test
    public void testUpdateState_toInProgress_shouldSchedulePauseJob() {
        mMigrationStateManager.updateMigrationState(mContext, MIGRATION_STATE_IN_PROGRESS);
        verifyStateChange(MIGRATION_STATE_IN_PROGRESS);
        verifyCancelAllJobs();
        verifyScheduleMigrationPauseJob();
    }

    /**
     * Expected behavior: - Change state, - Cancel all jobs available, - Schedule new completion job
     */
    @Test
    public void testUpdateState_toComplete_shouldCancelAllJobs() {
        mMigrationStateManager.updateMigrationState(mContext, MIGRATION_STATE_COMPLETE);
        verifyStateChange(MIGRATION_STATE_COMPLETE);
        verifyCancelAllJobs();
    }

    /**
     * Expected behavior: - Change state, - Cancel any completion job available, - Schedule new
     * completion job
     */
    @Test
    public void testUpdateState_toAppUpgradeRequired_shouldScheduleCompletionJob() {
        mMigrationStateManager.updateMigrationState(mContext, MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        verifyStateChange(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Expected behavior: - Change state, - Cancel any completion job available, - Schedule new
     * completion job
     */
    @Test
    public void testUpdateState_toModuleUpgradeRequired_shouldScheduleCompletionJob() {
        mMigrationStateManager.updateMigrationState(
                mContext, MIGRATION_STATE_MODULE_UPGRADE_REQUIRED);
        verifyStateChange(MIGRATION_STATE_MODULE_UPGRADE_REQUIRED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Expected behavior: - Change state, - Cancel all jobs available, - Schedule new completion job
     */
    @Test
    public void testUpdateState_toAllowed_shouldScheduleCompletionJob() {
        mMigrationStateManager.updateMigrationState(mContext, MIGRATION_STATE_ALLOWED);
        verifyStateChange(MIGRATION_STATE_ALLOWED);
        verifyCancelAllJobs();
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on user boot/switch. If no migration completion job scheduled, it should be scheduled.
     */
    @Test
    public void testReconcileStateChangeJob_fromIdleState_shouldReschedule() {
        setMigrationState(MIGRATION_STATE_IDLE);
        ExtendedMockito.doReturn(false)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on user boot/switch. If there is a migration completion job, no other should be
     * scheduled.
     */
    @Test
    public void testReconcileStateChangeJob_fromIdleState_shouldNotReschedule() {
        setMigrationState(MIGRATION_STATE_IDLE);
        ExtendedMockito.doReturn(true)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoJobScheduled();
    }

    /**
     * Tests on user boot/switch. If no migration completion job scheduled, it should be scheduled.
     */
    @Test
    public void testReconcileStateChangeJob_fromAppUpgradeRequiredState_shouldReschedule() {
        setMigrationState(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        ExtendedMockito.doReturn(false)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on user boot/switch. If there is a migration completion job, no other should be
     * scheduled.
     */
    @Test
    public void testReconcileStateChangeJob_fromAppUpgradeRequiredState_shouldNotReschedule() {
        setMigrationState(MIGRATION_STATE_APP_UPGRADE_REQUIRED);
        ExtendedMockito.doReturn(true)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoJobScheduled();
    }

    /**
     * Tests on user boot/switch. If no migration completion job scheduled, it should be scheduled.
     */
    @Test
    public void testReconcileStateChangeJob_fromAllowedState_shouldReschedule() {
        setMigrationState(MIGRATION_STATE_ALLOWED);
        ExtendedMockito.doReturn(false)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyScheduleMigrationCompletionJob();
    }

    /**
     * Tests on user boot/switch. If there is a migration completion job, no other should be
     * scheduled.
     */
    @Test
    public void testReconcileStateChangeJob_fromAllowedState_shouldNotReschedule() {
        setMigrationState(MIGRATION_STATE_ALLOWED);
        ExtendedMockito.doReturn(true)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_COMPLETE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoJobScheduled();
    }

    /** Tests on user boot/switch. If no migration pause job scheduled, it should be scheduled. */
    @Test
    public void testReconcileStateChangeJob_fromInProgressState_shouldReschedule() {
        setMigrationState(MIGRATION_STATE_IN_PROGRESS);
        ExtendedMockito.doReturn(false)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_PAUSE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyScheduleMigrationPauseJob();
    }

    /**
     * Tests on user boot/switch. If there is a migration pause job, no other should be scheduled.
     */
    @Test
    public void testReconcileStateChangeJob_fromInProgressState_shouldNotReschedule() {
        setMigrationState(MIGRATION_STATE_IN_PROGRESS);
        ExtendedMockito.doReturn(true)
                .when(
                        () ->
                                MigrationStateChangeJob.existsAStateChangeJob(
                                        eq(mContext), eq(MIGRATION_PAUSE_JOB_NAME)));
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoJobScheduled();
    }

    /**
     * Tests on user boot/switch. If the state is complete, there should be no jobs scheduled, and
     * all existing ones should be canceled.
     */
    @Test
    public void testReconcileStateChangeJob_fromCompleteState() {
        setMigrationState(MIGRATION_STATE_COMPLETE);
        mMigrationStateManager.switchToSetupForUser(mContext);
        verifyNoJobScheduled();
        verifyCancelAllJobs();
    }

    @Test
    public void testCancelOldMigrationJobs_haveNotCanceled() {
        when(mPreferenceHelper.getPreference(eq(HAVE_CANCELED_OLD_MIGRATION_JOBS_KEY)))
                .thenReturn(null);
        mMigrationStateManager.switchToSetupForUser(mContext);
        ExtendedMockito.verify(
                () -> MigrationStateChangeJob.cleanupOldPersistentMigrationJobs(eq(mContext)));
        verify(mPreferenceHelper)
                .insertOrReplacePreference(
                        eq(HAVE_CANCELED_OLD_MIGRATION_JOBS_KEY), eq(String.valueOf(true)));
    }

    @Test
    public void testCancelOldMigrationJobs_haveAlreadyCanceled() {
        when(mPreferenceHelper.getPreference(eq(HAVE_CANCELED_OLD_MIGRATION_JOBS_KEY)))
                .thenReturn(String.valueOf(true));
        mMigrationStateManager.switchToSetupForUser(mContext);
        ExtendedMockito.verify(
                () -> MigrationStateChangeJob.cleanupOldPersistentMigrationJobs(eq(mContext)),
                never());
        verify(mPreferenceHelper, never())
                .insertOrReplacePreference(eq(HAVE_CANCELED_OLD_MIGRATION_JOBS_KEY), any());
    }

    @Test
    public void testDoesMigrationHandleInfoIntent_returnsFalse_whenDisabledPackage() {
        configureMigrationAwarePackage();
        configureMigratorDisabledPackage();
        setMigrationState(MIGRATION_STATE_ALLOWED);
        assertFalse(mMigrationStateManager.doesMigratorHandleInfoIntent(mContext));
    }

    @Test
    public void testDoesMigrationHandleInfoIntent_returnsTrue_whenEnabledPackage() {
        configureMigrationAwarePackage();
        configureMigratorEnabledPackage();
        setMigrationState(MIGRATION_STATE_ALLOWED);
        assertTrue(mMigrationStateManager.doesMigratorHandleInfoIntent(mContext));
    }

    @Test
    public void testHasInProgressStateTimedOut_returnsTrue_whenTrue() {
        when(mPreferenceHelper.getPreference(eq(IN_PROGRESS_TIMEOUT_REACHED_KEY)))
                .thenReturn(String.valueOf(true));
        assertTrue(mMigrationStateManager.hasInProgressStateTimedOut());
    }

    @Test
    public void testHasInProgressStateTimedOut_returnsFalse_whenNotSet() {
        when(mPreferenceHelper.getPreference(eq(IN_PROGRESS_TIMEOUT_REACHED_KEY))).thenReturn(null);
        assertFalse(mMigrationStateManager.hasInProgressStateTimedOut());
    }

    @Test
    public void testHasIdleStateTimedOut_returnsTrue_whenTrue() {
        when(mPreferenceHelper.getPreference(eq(IDLE_TIMEOUT_REACHED_KEY)))
                .thenReturn(String.valueOf(true));
        assertTrue(mMigrationStateManager.hasIdleStateTimedOut());
    }

    @Test
    public void testHasIdleStateTimedOut_returnsFalse_whenNotSet() {
        when(mPreferenceHelper.getPreference(eq(IDLE_TIMEOUT_REACHED_KEY))).thenReturn(null);
        assertFalse(mMigrationStateManager.hasIdleStateTimedOut());
    }

    @Test
    public void testSwitchToSetupForUser_migrationHasTimedOutPrematurely() {
        Instant mockStartTime =
                PREMATURE_MIGRATION_TIMEOUT_DATE
                        .minusDays(10)
                        .atStartOfDay()
                        .toInstant(ZoneOffset.UTC);
        when(mPreferenceHelper.getPreference(eq(CURRENT_STATE_START_TIME_KEY)))
                .thenReturn(mockStartTime.toString());
        setMigrationState(MIGRATION_STATE_COMPLETE);
        mMigrationStateManager.resetMigrationStateIfNeeded(mContext);
        verifyStateChange(MIGRATION_STATE_IDLE);
    }

    @Test
    public void testSwitchToSetupForUser_migrationHasNotTimedOut() {
        setMigrationState(MIGRATION_STATE_IDLE);
        mMigrationStateManager.resetMigrationStateIfNeeded(mContext);
        verifyNoStateChange();
    }

    @Test
    public void testSwitchToSetupForUser_migrationHasTimedOutNotPrematurely() {
        Instant mockStartTime =
                PREMATURE_MIGRATION_TIMEOUT_DATE
                        .plusDays(10)
                        .atStartOfDay()
                        .toInstant(ZoneOffset.UTC);
        when(mPreferenceHelper.getPreference(eq(CURRENT_STATE_START_TIME_KEY)))
                .thenReturn(mockStartTime.toString());
        setMigrationState(MIGRATION_STATE_COMPLETE);
        mMigrationStateManager.resetMigrationStateIfNeeded(mContext);
        verifyNoStateChange();
    }

    @Test
    public void testSwitchToSetupForUser_migrationHasTimedOutPrematurely_stateAlreadyReset() {
        Instant mockStartTime =
                PREMATURE_MIGRATION_TIMEOUT_DATE
                        .minusDays(10)
                        .atStartOfDay()
                        .toInstant(ZoneOffset.UTC);
        when(mPreferenceHelper.getPreference(eq(HAVE_RESET_MIGRATION_STATE_KEY)))
                .thenReturn(String.valueOf(true));
        when(mPreferenceHelper.getPreference(eq(CURRENT_STATE_START_TIME_KEY)))
                .thenReturn(mockStartTime.toString());
        setMigrationState(MIGRATION_STATE_COMPLETE);
        mMigrationStateManager.resetMigrationStateIfNeeded(mContext);
        verifyNoStateChange();
    }

    private void setMigrationState(int state) {
        when(mPreferenceHelper.getPreference(eq(MIGRATION_STATE_PREFERENCE_KEY)))
                .thenReturn(String.valueOf(state));
    }

    private void configureMigrationAwarePackage() {
        when(mContext.getString(anyInt())).thenReturn(MOCK_CONFIGURED_PACKAGE);
        ArrayList<PackageInfo> packageInfoArray = createPackageInfoArray(MOCK_CONFIGURED_PACKAGE);
        when(mPackageManager.getPackagesHoldingPermissions(
                        eq(PERMISSIONS_TO_CHECK), argThat(flag -> (flag.getValue() == 0))))
                .thenReturn(packageInfoArray);
        MigrationTestUtils.setResolveActivityResult(
                new ResolveInfo(),
                mPackageManager,
                PackageManager.MATCH_ALL | PackageManager.MATCH_DISABLED_COMPONENTS);
    }

    private void configureMigrationUnAwarePackage() throws PackageManager.NameNotFoundException {
        when(mContext.getString(anyInt())).thenReturn(MOCK_CONFIGURED_PACKAGE);
        when(mResources.getStringArray(anyInt())).thenReturn(getCorrectKnownSignerCertificates());
        when(mPackageManager.getPackageInfo(
                        eq(MOCK_CONFIGURED_PACKAGE), eq(PackageManager.GET_SIGNING_CERTIFICATES)))
                .thenReturn(mPackageInfo);
        mPackageInfo.signingInfo = mSigningInfo;

        when(mSigningInfo.getApkContentsSigners())
                .thenReturn(
                        new Signature[] {new Signature(getCorrectKnownSignerCertificates()[0])});
        ExtendedMockito.doReturn(getCorrectKnownSignerCertificates()[0])
                .when(() -> HexEncoding.encodeToString(any(), anyBoolean()));
        when(mPackageManager.getInstalledPackages(PackageManager.GET_SIGNING_CERTIFICATES))
                .thenReturn(createPackageInfoArray(MOCK_CONFIGURED_PACKAGE));

        InstallSourceInfo installSourceInfo = mock(InstallSourceInfo.class);
        when(mPackageManager.getInstallSourceInfo(any())).thenReturn(installSourceInfo);
        when(installSourceInfo.getInstallingPackageName()).thenReturn(MOCK_CONFIGURED_PACKAGE);
    }

    private void configureNoMigratorPackage() {
        when(mContext.getString(anyInt())).thenReturn(MOCK_UNCONFIGURED_PACKAGE_ONE);
    }

    private void configureMigratorDisabledPackage() {
        List<ResolveInfo> enabledComponents = new ArrayList<ResolveInfo>();
        when(mPackageManager.queryIntentActivities(any(), any())).thenReturn(enabledComponents);
    }

    private void configureMigratorEnabledPackage() {
        List<ResolveInfo> enabledComponents = new ArrayList<ResolveInfo>();
        enabledComponents.add(new ResolveInfo());
        when(mPackageManager.queryIntentActivities(any(), any())).thenReturn(enabledComponents);
    }

    private void configureStubMigratorPackage() throws PackageManager.NameNotFoundException {
        InstallSourceInfo installSourceInfo = mock(InstallSourceInfo.class);
        when(mPackageManager.getInstallSourceInfo(any())).thenReturn(installSourceInfo);
        when(installSourceInfo.getInstallingPackageName()).thenReturn(null);
    }

    private void verifyStateChange(int state) {
        verify(mPreferenceHelper)
                .insertOrReplacePreferencesTransaction(
                        argThat(
                                map ->
                                        map.getOrDefault(
                                                        MIGRATION_STATE_PREFERENCE_KEY,
                                                        String.valueOf(-1))
                                                .equals(String.valueOf(state))));

        verify(mMockListener).onMigrationStateChanged(state);
    }

    private void verifyNoStateChange() {
        verify(mPreferenceHelper, never()).insertOrReplacePreferencesTransaction(any());
    }

    private String[] getCorrectKnownSignerCertificates() {
        return new String[] {MOCK_CERTIFICATE_ONE, MOCK_CERTIFICATE_TWO};
    }

    private void verifyCancelAllJobs() {
        ExtendedMockito.verify(
                () -> MigrationStateChangeJob.cancelAllJobs(eq(mContext)), atLeastOnce());
    }

    private void verifyScheduleMigrationCompletionJob() {
        ExtendedMockito.verify(
                () ->
                        MigrationStateChangeJob.scheduleMigrationCompletionJob(
                                eq(mContext), anyInt()));
    }

    private void verifyScheduleMigrationPauseJob() {
        ExtendedMockito.verify(
                () -> MigrationStateChangeJob.scheduleMigrationPauseJob(eq(mContext), anyInt()));
    }

    private void verifyNoJobScheduled() {
        ExtendedMockito.verify(
                () -> MigrationStateChangeJob.scheduleMigrationPauseJob(eq(mContext), anyInt()),
                never());
        ExtendedMockito.verify(
                () ->
                        MigrationStateChangeJob.scheduleMigrationCompletionJob(
                                eq(mContext), anyInt()),
                never());
    }

    private void verifyNoJobCancelled() {
        ExtendedMockito.verify(() -> MigrationStateChangeJob.cancelAllJobs(eq(mContext)), never());
    }

    private ArrayList<PackageInfo> createPackageInfoArray(String... packageNames) {
        ArrayList<PackageInfo> packageInfoArray = new ArrayList<PackageInfo>();
        for (String packageName : packageNames) {
            PackageInfo packageInfo = new PackageInfo();
            packageInfo.packageName = packageName;
            packageInfo.signingInfo = mSigningInfo;
            packageInfoArray.add(packageInfo);
        }
        return packageInfoArray;
    }

    public static class MockListener {
        void onMigrationStateChanged(@HealthConnectDataState.DataMigrationState int state) {}
    }

    @Test
    public void testValidateSetMinSdkVersion_stateAllowed_allowedToSetSdkVersion()
            throws IllegalMigrationStateException {
        when(mPreferenceHelper.getPreference(eq(MIGRATION_STATE_PREFERENCE_KEY)))
                .thenReturn(Integer.toString(MIGRATION_STATE_ALLOWED));
        mMigrationStateManager.validateSetMinSdkVersion();
    }

    @Test(expected = IllegalMigrationStateException.class)
    public void testValidateSetMinSdkVersion_stateInProgress_notAllowedToSetSdkVersion()
            throws IllegalMigrationStateException {
        when(mPreferenceHelper.getPreference(eq(MIGRATION_STATE_PREFERENCE_KEY)))
                .thenReturn(Integer.toString(MIGRATION_STATE_IN_PROGRESS));
        mMigrationStateManager.validateSetMinSdkVersion();
    }

    @Test(expected = IllegalMigrationStateException.class)
    public void testValidateSetMinSdkVersion_stateComplete_notAllowedToSetSdkVersion()
            throws IllegalMigrationStateException {
        when(mPreferenceHelper.getPreference(eq(MIGRATION_STATE_PREFERENCE_KEY)))
                .thenReturn(Integer.toString(MIGRATION_STATE_COMPLETE));
        mMigrationStateManager.validateSetMinSdkVersion();
    }
}