summaryrefslogtreecommitdiff
path: root/adservices/tests/unittest/service-core/src/com/android/adservices/service/topics/TopicsWorkerTest.java
blob: c5ddc5b4b26f80c2616b88fea8d0f405980ce1f6 (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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
/*
 * Copyright (C) 2022 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.adservices.service.topics;

import static android.adservices.common.AdServicesStatusUtils.STATUS_SUCCESS;

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

import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.adservices.topics.GetTopicsResult;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Pair;

import androidx.test.core.app.ApplicationProvider;

import com.android.adservices.MockRandom;
import com.android.adservices.data.DbHelper;
import com.android.adservices.data.DbTestUtil;
import com.android.adservices.data.topics.Topic;
import com.android.adservices.data.topics.TopicsDao;
import com.android.adservices.data.topics.TopicsTables;
import com.android.adservices.service.Flags;
import com.android.adservices.service.stats.AdServicesLogger;

import com.google.common.collect.ImmutableList;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/** Unit test for {@link com.android.adservices.service.topics.TopicsWorker}. */
public class TopicsWorkerTest {
    // Spy the Context to test app reconciliation
    private final Context mContext = spy(ApplicationProvider.getApplicationContext());
    private final DbHelper mDbHelper = spy(DbTestUtil.getDbHelperForTest());

    private TopicsWorker mTopicsWorker;
    private TopicsDao mTopicsDao;
    private CacheManager mCacheManager;
    private BlockedTopicsManager mBlockedTopicsManager;
    // Spy DbHelper to mock supportsTopContributorsTable feature.

    @Mock private EpochManager mMockEpochManager;
    @Mock private Flags mMockFlags;
    @Mock AdServicesLogger mLogger;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        // Clean DB before each test
        DbTestUtil.deleteTable(TopicsTables.TaxonomyContract.TABLE);
        DbTestUtil.deleteTable(TopicsTables.AppClassificationTopicsContract.TABLE);
        DbTestUtil.deleteTable(TopicsTables.CallerCanLearnTopicsContract.TABLE);
        DbTestUtil.deleteTable(TopicsTables.TopTopicsContract.TABLE);
        DbTestUtil.deleteTable(TopicsTables.ReturnedTopicContract.TABLE);
        DbTestUtil.deleteTable(TopicsTables.UsageHistoryContract.TABLE);
        DbTestUtil.deleteTable(TopicsTables.AppUsageHistoryContract.TABLE);
        DbTestUtil.deleteTable(TopicsTables.BlockedTopicsContract.TABLE);
        DbTestUtil.deleteTable(TopicsTables.TopicContributorsContract.TABLE);

        mTopicsDao = new TopicsDao(mDbHelper);
        mCacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags, mLogger);
        AppUpdateManager appUpdateManager =
                new AppUpdateManager(mDbHelper, mTopicsDao, new Random(), mMockFlags);
        mBlockedTopicsManager = new BlockedTopicsManager(mTopicsDao);
        mTopicsWorker =
                new TopicsWorker(
                        mMockEpochManager,
                        mCacheManager,
                        mBlockedTopicsManager,
                        appUpdateManager,
                        mMockFlags);
    }

    @Test
    public void testGetTopics() {
        final long epochId = 4L;
        final int numberOfLookBackEpochs = 3;
        final Pair<String, String> appSdkKey = Pair.create("app", "sdk");
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        Topic[] topics = {topic1, topic2, topic3};
        // persist returned topics into DB
        for (int numEpoch = 1; numEpoch <= numberOfLookBackEpochs; numEpoch++) {
            Topic currentTopic = topics[numberOfLookBackEpochs - numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();
            returnedAppSdkTopicsMap.put(appSdkKey, currentTopic);
            mTopicsDao.persistReturnedAppTopicsMap(numEpoch, returnedAppSdkTopicsMap);
        }

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(epochId);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);

        // Real Cache Manager requires loading cache before getTopics() being called.
        mTopicsWorker.loadCache();

        GetTopicsResult getTopicsResult = mTopicsWorker.getTopics("app", "sdk");

        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Arrays.asList(1L, 2L, 3L))
                        .setModelVersions(Arrays.asList(4L, 5L, 6L))
                        .setTopics(Arrays.asList(1, 2, 3))
                        .build();

        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResult.getResultCode())
                .isEqualTo(expectedGetTopicsResult.getResultCode());
        assertThat(getTopicsResult.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTaxonomyVersions());
        assertThat(getTopicsResult.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getModelVersions());
        assertThat(getTopicsResult.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTopics());

        // getTopic() + loadCache() + handleSdkTopicsAssignmentForAppInstallation()
        verify(mMockEpochManager, times(3)).getCurrentEpochId();
        verify(mMockFlags, times(3)).getTopicsNumberOfLookBackEpochs();
    }

    @Test
    public void testGetTopics_emptyCache() {
        final long epochId = 4L;

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(epochId);

        // // There is no returned Topics persisted in the DB so cache is empty
        mTopicsWorker.loadCache();

        GetTopicsResult getTopicsResult = mTopicsWorker.getTopics("app", "sdk");

        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();

        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResult.getResultCode())
                .isEqualTo(expectedGetTopicsResult.getResultCode());
        assertThat(getTopicsResult.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTaxonomyVersions());
        assertThat(getTopicsResult.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getModelVersions());
        assertThat(getTopicsResult.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTopics());
    }

    @Test
    public void testGetTopics_appNotInCache() {
        final long epochId = 4L;
        final int numberOfLookBackEpochs = 1;
        final Pair<String, String> appSdkKey = Pair.create("app", "sdk");
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic[] topics = {topic1};
        // persist returned topics into DB
        for (int numEpoch = 1; numEpoch <= numberOfLookBackEpochs; numEpoch++) {
            Topic currentTopic = topics[numberOfLookBackEpochs - numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();
            returnedAppSdkTopicsMap.put(appSdkKey, currentTopic);
            mTopicsDao.persistReturnedAppTopicsMap(numEpoch, returnedAppSdkTopicsMap);
        }

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(epochId);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);

        // Real Cache Manager requires loading cache before getTopics() being called.
        mTopicsWorker.loadCache();

        GetTopicsResult getTopicsResult = mTopicsWorker.getTopics("app_not_in_cache", "sdk");

        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();

        assertThat(getTopicsResult).isEqualTo(expectedGetTopicsResult);
    }

    @Test
    public void testGetTopics_sdkNotInCache() {
        final long epochId = 4L;
        final int numberOfLookBackEpochs = 1;
        final Pair<String, String> appSdkKey = Pair.create("app", "sdk");
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic[] topics = {topic1};
        // persist returned topics into DB
        for (int numEpoch = 1; numEpoch <= numberOfLookBackEpochs; numEpoch++) {
            Topic currentTopic = topics[numberOfLookBackEpochs - numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();
            returnedAppSdkTopicsMap.put(appSdkKey, currentTopic);
            mTopicsDao.persistReturnedAppTopicsMap(numEpoch, returnedAppSdkTopicsMap);
        }

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(epochId);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);

        // Real Cache Manager requires loading cache before getTopics() being called.
        mTopicsWorker.loadCache();

        GetTopicsResult getTopicsResult = mTopicsWorker.getTopics("app", "sdk_not_in_cache");

        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();

        assertThat(getTopicsResult).isEqualTo(expectedGetTopicsResult);
    }

    @Test
    public void testGetTopics_handleSdkTopicAssignment() {
        final int numberOfLookBackEpochs = 3;
        final long currentEpochId = 5L;

        final String app = "app";
        final String sdk = "sdk";

        Pair<String, String> appOnlyCaller = Pair.create(app, /* sdk */ "");

        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        Topic[] topics = {topic1, topic2, topic3};

        // persist returned topics into DB
        for (long epoch = 0; epoch < numberOfLookBackEpochs; epoch++) {
            long epochId = currentEpochId - 1 - epoch;
            Topic topic = topics[(int) epoch];

            mTopicsDao.persistReturnedAppTopicsMap(epochId, Map.of(appOnlyCaller, topic));
            // SDK needs to be able to learn this topic in past epochs
            mTopicsDao.persistCallerCanLearnTopics(epochId, Map.of(topic, Set.of(sdk)));
        }

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);

        GetTopicsResult getTopicsResult = mTopicsWorker.getTopics(app, sdk);

        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Arrays.asList(1L, 2L, 3L))
                        .setModelVersions(Arrays.asList(4L, 5L, 6L))
                        .setTopics(Arrays.asList(1, 2, 3))
                        .build();

        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResult.getResultCode())
                .isEqualTo(expectedGetTopicsResult.getResultCode());
        assertThat(getTopicsResult.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTaxonomyVersions());
        assertThat(getTopicsResult.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getModelVersions());
        assertThat(getTopicsResult.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTopics());
    }

    @Test
    public void testGetTopics_handleSdkTopicAssignment_existingTopicsForSdk() {
        final int numberOfLookBackEpochs = 3;
        final long currentEpochId = 5L;

        final String app = "app";
        final String sdk = "sdk";

        Pair<String, String> appOnlyCaller = Pair.create(app, /* sdk */ "");
        Pair<String, String> appSdkCaller = Pair.create(app, sdk);

        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        Topic[] topics = {topic1, topic2, topic3};

        // persist returned topics into DB
        for (long epoch = 0; epoch < numberOfLookBackEpochs; epoch++) {
            long epochId = currentEpochId - 1 - epoch;
            Topic topic = topics[(int) epoch];

            mTopicsDao.persistReturnedAppTopicsMap(epochId, Map.of(appOnlyCaller, topic));
            // SDK needs to be able to learn this topic in past epochs
            mTopicsDao.persistCallerCanLearnTopics(epochId, Map.of(topic, Set.of(sdk)));
        }

        // Sdk has an existing topic in Epoch 1
        mTopicsDao.persistReturnedAppTopicsMap(
                currentEpochId - numberOfLookBackEpochs + 1, Map.of(appSdkCaller, topic1));

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);

        mTopicsWorker.loadCache();
        GetTopicsResult getTopicsResult = mTopicsWorker.getTopics(app, sdk);

        // Only the existing topic will be returned, i.e. No topic assignment has happened.
        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(List.of(1L))
                        .setModelVersions(List.of(4L))
                        .setTopics(List.of(1))
                        .build();

        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResult.getResultCode())
                .isEqualTo(expectedGetTopicsResult.getResultCode());
        assertThat(getTopicsResult.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTaxonomyVersions());
        assertThat(getTopicsResult.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getModelVersions());
        assertThat(getTopicsResult.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTopics());
    }

    @Test
    public void testRecordUsage() {
        mTopicsWorker.recordUsage("app", "sdk");
        verify(mMockEpochManager, only()).recordUsageHistory(eq("app"), eq("sdk"));
    }

    @Test
    public void testComputeEpoch() {
        mTopicsWorker.computeEpoch();
        verify(mMockEpochManager, times(1)).processEpoch();
    }

    @Test
    public void testGetKnownTopicsWithConsent_oneTopicBlocked() {
        final long lastEpoch = 3;
        final int numberOfLookBackEpochs = 3;
        final Pair<String, String> appSdkKey = Pair.create("app", "sdk");
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        Topic[] topics = {topic1, topic2, topic3};
        // persist returned topics into Db
        // populate topics for different epochs to get realistic state of the Db for testing
        // blocked topics.
        for (int numEpoch = 1; numEpoch <= numberOfLookBackEpochs; numEpoch++) {
            Topic currentTopic = topics[numberOfLookBackEpochs - numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();
            returnedAppSdkTopicsMap.put(appSdkKey, currentTopic);
            mTopicsDao.persistReturnedAppTopicsMap(numEpoch, returnedAppSdkTopicsMap);
        }
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(lastEpoch);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);
        Topic blockedTopic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        mTopicsDao.recordBlockedTopic(blockedTopic1);

        mTopicsWorker.loadCache();
        ImmutableList<Topic> knownTopicsWithConsent = mTopicsWorker.getKnownTopicsWithConsent();
        ImmutableList<Topic> topicsWithRevokedConsent = mTopicsWorker.getTopicsWithRevokedConsent();

        // there is only one blocked topic.
        assertThat(topicsWithRevokedConsent).hasSize(1);
        assertThat(topicsWithRevokedConsent).containsExactly(blockedTopic1);
        // out of 3 existing topics, 2 of them are not blocked.
        assertThat(knownTopicsWithConsent).hasSize(2);
        assertThat(knownTopicsWithConsent).containsExactly(topic2, topic3);
    }

    @Test
    public void testGetKnownTopicsWithConsent_allTopicsBlocked() {
        final long lastEpoch = 3;
        final int numberOfLookBackEpochs = 3;
        final Pair<String, String> appSdkKey = Pair.create("app", "sdk");
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        Topic[] topics = {topic1, topic2, topic3};
        // persist returned topics into DB
        for (int numEpoch = 1; numEpoch <= numberOfLookBackEpochs; numEpoch++) {
            Topic currentTopic = topics[numberOfLookBackEpochs - numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();
            returnedAppSdkTopicsMap.put(appSdkKey, currentTopic);
            mTopicsDao.persistReturnedAppTopicsMap(numEpoch, returnedAppSdkTopicsMap);
        }
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(lastEpoch);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);
        // block all topics
        mTopicsDao.recordBlockedTopic(topic1);
        mTopicsDao.recordBlockedTopic(topic2);
        mTopicsDao.recordBlockedTopic(topic3);

        mTopicsWorker.loadCache();
        ImmutableList<Topic> knownTopicsWithConsent = mTopicsWorker.getKnownTopicsWithConsent();

        assertThat(knownTopicsWithConsent).isEmpty();
    }

    @Test
    public void testTopicsWithRevokedConsent() {
        Topic blockedTopic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic blockedTopic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic blockedTopic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        // block all blockedTopics
        mTopicsDao.recordBlockedTopic(blockedTopic1);
        mTopicsDao.recordBlockedTopic(blockedTopic2);
        mTopicsDao.recordBlockedTopic(blockedTopic3);

        // persist one not blocked topic.
        final Pair<String, String> appSdkKey = Pair.create("app", "sdk");
        Topic topic1 =
                Topic.create(/* topic */ 4, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();
        returnedAppSdkTopicsMap.put(appSdkKey, topic1);
        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 1, returnedAppSdkTopicsMap);

        mTopicsWorker.loadCache();
        ImmutableList<Topic> topicsWithRevokedConsent = mTopicsWorker.getTopicsWithRevokedConsent();

        // Three topics are persisted into blocked topic table
        assertThat(topicsWithRevokedConsent).hasSize(3);
        assertThat(topicsWithRevokedConsent)
                .containsExactly(blockedTopic1, blockedTopic2, blockedTopic3);
    }

    @Test
    public void testTopicsWithRevokedConsent_noTopicsBlocked() {
        final int numberOfLookBackEpochs = 3;
        final Pair<String, String> appSdkKey = Pair.create("app", "sdk");
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        Topic[] topics = {topic1, topic2, topic3};
        // persist returned topics into DB
        // populate topics for different epochs to get realistic state of the Db for testing
        // blocked topics.
        for (int numEpoch = 1; numEpoch <= numberOfLookBackEpochs; numEpoch++) {
            Topic currentTopic = topics[numberOfLookBackEpochs - numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();
            returnedAppSdkTopicsMap.put(appSdkKey, currentTopic);
            mTopicsDao.persistReturnedAppTopicsMap(numEpoch, returnedAppSdkTopicsMap);
        }

        mTopicsWorker.loadCache();
        ImmutableList<Topic> topicsWithRevokedConsent = mTopicsWorker.getTopicsWithRevokedConsent();

        assertThat(topicsWithRevokedConsent).isEmpty();
    }

    @Test
    public void testRevokeConsent() {
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        mTopicsWorker.loadCache();
        mTopicsWorker.revokeConsentForTopic(topic1);

        ImmutableList<Topic> topicsWithRevokedConsent = mTopicsWorker.getTopicsWithRevokedConsent();

        assertThat(topicsWithRevokedConsent).hasSize(1);
        assertThat(topicsWithRevokedConsent).containsExactly(topic1);

        // TODO(b/234214293): add checks on getTopics method.
    }

    @Test
    public void testRevokeAndRestoreConsent() {
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        mTopicsWorker.loadCache();

        // Revoke consent for topic1
        mTopicsWorker.revokeConsentForTopic(topic1);
        ImmutableList<Topic> topicsWithRevokedConsent = mTopicsWorker.getTopicsWithRevokedConsent();

        assertThat(topicsWithRevokedConsent).hasSize(1);
        assertThat(topicsWithRevokedConsent).containsExactly(topic1);

        // Restore consent for topic1
        mTopicsWorker.restoreConsentForTopic(topic1);
        topicsWithRevokedConsent = mTopicsWorker.getTopicsWithRevokedConsent();

        assertThat(topicsWithRevokedConsent).isEmpty();

        // TODO(b/234214293): add checks on getTopics method.
    }

    @Test
    public void testClearAllTopicsData() {
        final long epochId = 4L;
        final int numberOfLookBackEpochs = 3;
        final String app = "app";
        final String sdk = "sdk";

        ArrayList<String> tableExclusionList = new ArrayList<>();
        tableExclusionList.add(TopicsTables.BlockedTopicsContract.TABLE);

        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        Topic[] topics = {topic1, topic2, topic3};
        // persist returned topics into DB
        for (int numEpoch = 1; numEpoch <= numberOfLookBackEpochs; numEpoch++) {
            Topic currentTopic = topics[numberOfLookBackEpochs - numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();

            // Test both cases of app and app-sdk calling getTopics()
            returnedAppSdkTopicsMap.put(Pair.create(app, sdk), currentTopic);
            returnedAppSdkTopicsMap.put(Pair.create(app, /* sdk */ ""), currentTopic);
            mTopicsDao.persistReturnedAppTopicsMap(numEpoch, returnedAppSdkTopicsMap);
        }
        mTopicsDao.recordBlockedTopic(topic1);

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(epochId);
        when(mMockEpochManager.supportsTopicContributorFeature()).thenReturn(true);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);

        // Real Cache Manager requires loading cache before getTopics() being called.
        mTopicsWorker.loadCache();

        // Verify topics are persisted in the database
        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Arrays.asList(2L, 3L))
                        .setModelVersions(Arrays.asList(5L, 6L))
                        .setTopics(Arrays.asList(2, 3))
                        .build();
        GetTopicsResult getTopicsResultAppOnly1 = mTopicsWorker.getTopics(app, /* sdk */ "");
        GetTopicsResult getTopicsResultAppSdk1 = mTopicsWorker.getTopics(app, sdk);

        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResultAppOnly1.getResultCode())
                .isEqualTo(expectedGetTopicsResult.getResultCode());
        assertThat(getTopicsResultAppOnly1.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTaxonomyVersions());
        assertThat(getTopicsResultAppOnly1.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getModelVersions());
        assertThat(getTopicsResultAppOnly1.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTopics());
        assertThat(getTopicsResultAppSdk1.getResultCode())
                .isEqualTo(expectedGetTopicsResult.getResultCode());
        assertThat(getTopicsResultAppSdk1.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTaxonomyVersions());
        assertThat(getTopicsResultAppSdk1.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getModelVersions());
        assertThat(getTopicsResultAppSdk1.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTopics());

        // Clear all data in database belonging to app except blocked topics table
        mTopicsWorker.clearAllTopicsData(tableExclusionList);
        assertThat(mTopicsDao.retrieveAllBlockedTopics()).isNotEmpty();

        mTopicsWorker.clearAllTopicsData(new ArrayList<>());
        assertThat(mTopicsDao.retrieveAllBlockedTopics()).isEmpty();

        GetTopicsResult emptyGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();

        assertThat(mTopicsWorker.getTopics(app, sdk)).isEqualTo(emptyGetTopicsResult);
        assertThat(mTopicsWorker.getTopics(app, /* sdk */ "")).isEqualTo(emptyGetTopicsResult);
    }

    @Test
    public void testClearAllTopicsData_topicContributorsTable() {
        final long epochId = 1;
        final int topicId = 1;
        final String app = "app";
        Map<Integer, Set<String>> topicContributorsMap = Map.of(topicId, Set.of(app));
        mTopicsDao.persistTopicContributors(epochId, topicContributorsMap);

        // To test feature flag is off
        doReturn(false).when(mMockEpochManager).supportsTopicContributorFeature();
        mTopicsWorker.clearAllTopicsData(/* tables to exclude */ new ArrayList<>());
        // TopicContributors table should remain the same
        assertThat(mTopicsDao.retrieveTopicToContributorsMap(epochId))
                .isEqualTo(topicContributorsMap);

        // To test feature flag is on
        doReturn(true).when(mMockEpochManager).supportsTopicContributorFeature();
        mTopicsWorker.clearAllTopicsData(/* tables to exclude */ new ArrayList<>());
        // TopicContributors table be cleared.
        assertThat(mTopicsDao.retrieveTopicToContributorsMap(epochId)).isEmpty();
    }

    @Test
    public void testClearAllTopicsData_ImmutableList() {
        assertThrows(
                ClassCastException.class,
                () -> mTopicsWorker.clearAllTopicsData((ArrayList<String>) List.of("anyString")));
    }

    @Test
    public void testReconcileApplicationUpdate() {
        final String app1 = "app1"; // regular app
        final String app2 = "app2"; // unhandled uninstalled app
        final String app3 = "app3"; // unhandled installed app
        final String app4 = "app4"; // uninstalled app but with only usage
        final String app5 = "app5"; // installed app but with only returned topic
        final String sdk = "sdk";

        final long currentEpochId = 4L;
        final long taxonomyVersion = 1L;
        final long modelVersion = 1L;
        final int numOfLookBackEpochs = 3;
        final int topicsNumberOfTopTopics = 5;
        final int topicsPercentageForRandomTopic = 5;

        Topic topic1 = Topic.create(/* topic */ 1, taxonomyVersion, modelVersion);
        Topic topic2 = Topic.create(/* topic */ 2, taxonomyVersion, modelVersion);
        Topic topic3 = Topic.create(/* topic */ 3, taxonomyVersion, modelVersion);
        Topic topic4 = Topic.create(/* topic */ 4, taxonomyVersion, modelVersion);
        Topic topic5 = Topic.create(/* topic */ 5, taxonomyVersion, modelVersion);
        Topic topic6 = Topic.create(/* topic */ 6, taxonomyVersion, modelVersion);
        List<Topic> topTopics = List.of(topic1, topic2, topic3, topic4, topic5, topic6);

        // In order to mock Package Manager, context also needs to be mocked to return
        // mocked Package Manager
        PackageManager mockPackageManager = Mockito.mock(PackageManager.class);
        when(mContext.getPackageManager()).thenReturn(mockPackageManager);

        // Mock Package Manager for installed applications
        // Note app2 is not here to mock uninstallation, app3 is here to mock installation
        ApplicationInfo appInfo1 = new ApplicationInfo();
        appInfo1.packageName = app1;
        ApplicationInfo appInfo3 = new ApplicationInfo();
        appInfo3.packageName = app3;
        when(mockPackageManager.getInstalledApplications(Mockito.any()))
                .thenReturn(List.of(appInfo1, appInfo3));

        // As selectAssignedTopicFromTopTopics() randomly assigns a top topic, pass in a Mocked
        // Random object to make the result deterministic.
        //
        // In this test, topic 1, 2, and 6 are supposed to be returned. For each topic, it needs 2
        // random draws: the first is to determine whether to select a random topic, the second is
        // draw the actual topic index.
        MockRandom mockRandom =
                new MockRandom(
                        new long[] {
                            topicsPercentageForRandomTopic, // Will select a regular topic
                            0, // Index of first topic
                            topicsPercentageForRandomTopic, // Will select a regular topic
                            1, // Index of second topic
                            0, // Will select a random topic
                            0 // Select the first random topic
                        });
        AppUpdateManager appUpdateManager =
                new AppUpdateManager(mDbHelper, mTopicsDao, mockRandom, mMockFlags);

        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numOfLookBackEpochs);
        when(mMockFlags.getTopicsNumberOfTopTopics()).thenReturn(topicsNumberOfTopTopics);
        when(mMockFlags.getTopicsPercentageForRandomTopic())
                .thenReturn(topicsPercentageForRandomTopic);

        Topic[] topics1 = {topic1, topic2, topic3};
        Topic[] topics2 = {topic4, topic5, topic6};
        for (int numEpoch = 0; numEpoch < numOfLookBackEpochs; numEpoch++) {
            long epochId = currentEpochId - 1 - numEpoch;
            // Persist returned topics into DB
            Topic currentTopic1 = topics1[numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap1 = new HashMap<>();
            returnedAppSdkTopicsMap1.put(Pair.create(app1, sdk), currentTopic1);
            mTopicsDao.persistReturnedAppTopicsMap(epochId, returnedAppSdkTopicsMap1);

            Topic currentTopic2 = topics2[numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap2 = new HashMap<>();
            returnedAppSdkTopicsMap2.put(Pair.create(app2, sdk), currentTopic2);
            mTopicsDao.persistReturnedAppTopicsMap(epochId, returnedAppSdkTopicsMap2);

            // Persist top topics
            mTopicsDao.persistTopTopics(epochId, topTopics);

            // Since AppUpdateManager evaluates previously installed apps through App Usage, usages
            // should be persisted into database.
            //
            // Note app3 doesn't have usage as newly installation. And app4 only has usage but
            // doesn't have returned topics
            mTopicsDao.recordAppUsageHistory(epochId, app1);
            mTopicsDao.recordAppUsageHistory(epochId, app2);
            mTopicsDao.recordAppUsageHistory(epochId, app4);
            // Persist into AppSdkUsage table to mimic reality but this is unnecessary.
            mTopicsDao.recordUsageHistory(epochId, app1, sdk);
            mTopicsDao.recordUsageHistory(epochId, app2, sdk);
            mTopicsDao.recordUsageHistory(epochId, app4, sdk);

            // Persist topics to TopicContributors Table avoid being filtered out
            for (Topic topic : topTopics) {
                mTopicsDao.persistTopicContributors(
                        epochId, Map.of(topic.getTopic(), Set.of(app1, app2, app3, app4)));
            }
        }
        // Persist returned topic to app 5. Note that the epoch id to persist is older than
        // (currentEpochId - numOfLookBackEpochs). Therefore, app5 won't be handled as a newly
        // installed app.
        mTopicsDao.persistReturnedAppTopicsMap(
                currentEpochId - numOfLookBackEpochs - 1, Map.of(Pair.create(app5, ""), topic1));

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numOfLookBackEpochs);
        // Enable Topic Contributors Check Feature
        doReturn(true).when(mDbHelper).supportsTopicContributorsTable();
        when(mMockFlags.getEnableTopicContributorsCheck()).thenReturn(true);

        // Initialize a local TopicsWorker to use mocked AppUpdateManager
        TopicsWorker topicsWorker =
                new TopicsWorker(
                        mMockEpochManager,
                        mCacheManager,
                        mBlockedTopicsManager,
                        appUpdateManager,
                        mMockFlags);
        // Reconcile the unhandled uninstalled apps.
        // As PackageManager is mocked, app2 will be identified as unhandled uninstalled app.
        // All data belonging to app2 will be deleted.
        topicsWorker.reconcileApplicationUpdate(mContext);

        // Both reconciling uninstalled apps and installed apps call these mocked functions
        verify(mContext, times(2)).getPackageManager();
        verify(mockPackageManager, times(2)).getInstalledApplications(Mockito.any());

        // App1 should get topics 1, 2, 3
        GetTopicsResult expectedGetTopicsResult1 =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(
                                Arrays.asList(taxonomyVersion, taxonomyVersion, taxonomyVersion))
                        .setModelVersions(Arrays.asList(modelVersion, modelVersion, modelVersion))
                        .setTopics(Arrays.asList(1, 2, 3))
                        .build();
        GetTopicsResult getTopicsResult1 = topicsWorker.getTopics(app1, sdk);
        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResult1.getResultCode())
                .isEqualTo(expectedGetTopicsResult1.getResultCode());
        assertThat(getTopicsResult1.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult1.getTaxonomyVersions());
        assertThat(getTopicsResult1.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult1.getModelVersions());
        assertThat(getTopicsResult1.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult1.getTopics());

        // App2 is uninstalled so should return empty topics.
        GetTopicsResult emptyGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();
        assertThat((topicsWorker.getTopics(app2, sdk))).isEqualTo(emptyGetTopicsResult);

        // App4 is uninstalled so usage table should be clear. As it originally doesn't have
        // returned topic, getTopic won't be checked
        assertThat(
                        mTopicsDao.retrieveDistinctAppsFromTables(
                                List.of(TopicsTables.AppUsageHistoryContract.TABLE),
                                List.of(TopicsTables.AppUsageHistoryContract.APP)))
                .doesNotContain(app4);

        // App3 is newly installed and should topics 1, 2, 6
        GetTopicsResult expectedGetTopicsResult3 =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(
                                Arrays.asList(taxonomyVersion, taxonomyVersion, taxonomyVersion))
                        .setModelVersions(Arrays.asList(modelVersion, modelVersion, modelVersion))
                        .setTopics(Arrays.asList(1, 2, 6))
                        .build();
        GetTopicsResult getTopicsResult3 = topicsWorker.getTopics(app3, /* sdk */ "");
        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResult3.getResultCode())
                .isEqualTo(expectedGetTopicsResult3.getResultCode());
        assertThat(getTopicsResult3.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult3.getTaxonomyVersions());
        assertThat(getTopicsResult3.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult3.getModelVersions());
        assertThat(getTopicsResult3.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult3.getTopics());

        // App5 has a returned topic in old epoch, so it won't be regarded as newly installed app
        // Therefore, it won't get any topic in recent epochs.
        assertThat((topicsWorker.getTopics(app5, sdk))).isEqualTo(emptyGetTopicsResult);

        verify(mMockFlags).getTopicsNumberOfTopTopics();
        verify(mMockFlags).getTopicsPercentageForRandomTopic();
    }

    @Test
    public void testHandleAppUninstallation() {
        final long epochId = 4L;
        final int numberOfLookBackEpochs = 3;
        final String app = "app";
        final String sdk = "sdk";

        final Pair<String, String> appSdkKey = Pair.create(app, sdk);
        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 4L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 2L, /* modelVersion = */ 5L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 3L, /* modelVersion = */ 6L);
        Topic[] topics = {topic1, topic2, topic3};
        // persist returned topics into DB
        for (int numEpoch = 1; numEpoch <= numberOfLookBackEpochs; numEpoch++) {
            Topic currentTopic = topics[numberOfLookBackEpochs - numEpoch];
            Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap = new HashMap<>();
            returnedAppSdkTopicsMap.put(appSdkKey, currentTopic);
            mTopicsDao.persistReturnedAppTopicsMap(numEpoch, returnedAppSdkTopicsMap);
        }

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(epochId);
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numberOfLookBackEpochs);

        // Real Cache Manager requires loading cache before getTopics() being called.
        mTopicsWorker.loadCache();

        GetTopicsResult getTopicsResult = mTopicsWorker.getTopics(app, sdk);

        verify(mMockEpochManager, times(3)).getCurrentEpochId();
        verify(mMockFlags, times(3)).getTopicsNumberOfLookBackEpochs();

        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Arrays.asList(1L, 2L, 3L))
                        .setModelVersions(Arrays.asList(4L, 5L, 6L))
                        .setTopics(Arrays.asList(1, 2, 3))
                        .build();

        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResult.getResultCode())
                .isEqualTo(expectedGetTopicsResult.getResultCode());
        assertThat(getTopicsResult.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTaxonomyVersions());
        assertThat(getTopicsResult.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getModelVersions());
        assertThat(getTopicsResult.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTopics());

        // Delete data belonging to the app
        Uri packageUri = Uri.parse("package:" + app);
        mTopicsWorker.handleAppUninstallation(packageUri);

        GetTopicsResult emptyGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();
        assertThat((mTopicsWorker.getTopics(app, sdk))).isEqualTo(emptyGetTopicsResult);
    }

    @Test
    public void testHandleAppUninstallation_handleTopTopicsWithoutContributors() {
        // The test sets up to handle below scenarios:
        // * Both app1 and app2 have usage in the epoch and all 6 topics are top topics.
        // * app1 is classified to topic1, topic2. app2 is classified to topic1 and topic3.
        // * Both app1 and app2 calls Topics API via .
        // * In Epoch1, as app2 is able to learn topic2 via sdk, though topic2 is not a classified
        //   topic of app2, both app1 and app2 can have topic2 as the returned topic.
        // * In Epoch4, app1 gets uninstalled. Since app1 is the only contributor of topic2, topic2
        //   will be deleted from epoch1. Therefore, app2 will also have empty returned topic in
        //   Epoch1, along with app1.
        // * Comparison case in Epoch2 (multiple contributors): Both app1 and app3 has usages and
        //   are classified topic1 and topic2 with topic1 as the returned topic . When app1 gets
        //   uninstalled in Epoch4, app3 will still be able to return topic2 which comes from
        //   Epoch2.
        // * Comparison case in Epoch3 (the feature topic is only removed on epoch basis): app4 has
        //   same setup as app2 in Epoch1: it has topic2 as returned topic in Epoch1, but is NOT
        //   classified to topic2. app4 also has topic2 as returned topic in Epoch3. Therefore, when
        //   app1 is uninstalled in Epoch4, topic1 will be removed for app4 as returned topic in
        //   Epoch1 but not in Epoch3. So if app4 calls Topics API in Epoch4, it's still able to
        //   return topic1 as a result.
        final long epochId1 = 1;
        final long epochId2 = 2;
        final long epochId3 = 3;
        final long epochId4 = 4;
        final long taxonomyVersion = 1L;
        final long modelVersion = 1L;
        final String app1 = "app1"; // app to uninstall at Epoch4
        final String app2 = "app2"; // positive case to verify the removal of the returned topic
        final String app3 = "app3"; // negative case to verify scenario of multiple contributors
        final String app4 = "app4"; // negative ase to verify the removal is on epoch basis
        final String sdk = "sdk";
        Topic topic1 = Topic.create(/* topic */ 1, taxonomyVersion, modelVersion);
        Topic topic2 = Topic.create(/* topic */ 2, taxonomyVersion, modelVersion);
        Topic topic3 = Topic.create(/* topic */ 3, taxonomyVersion, modelVersion);
        Topic topic4 = Topic.create(/* topic */ 4, taxonomyVersion, modelVersion);
        Topic topic5 = Topic.create(/* topic */ 5, taxonomyVersion, modelVersion);
        Topic topic6 = Topic.create(/* topic */ 6, taxonomyVersion, modelVersion);

        // Set the number in flag so that it doesn't depend on the actual value in PhFlags.
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(3);

        // Persist Top topics for epoch1 ~ epoch4
        mTopicsDao.persistTopTopics(
                epochId1, List.of(topic1, topic2, topic3, topic4, topic5, topic6));
        mTopicsDao.persistTopTopics(
                epochId2, List.of(topic1, topic2, topic3, topic4, topic5, topic6));
        mTopicsDao.persistTopTopics(
                epochId3, List.of(topic1, topic2, topic3, topic4, topic5, topic6));

        // Persist AppClassificationTopics Table
        mTopicsDao.persistAppClassificationTopics(
                epochId1,
                Map.of(
                        app1, List.of(topic1, topic2),
                        app2, List.of(topic1, topic3),
                        app4, List.of(topic1, topic3)));
        mTopicsDao.persistAppClassificationTopics(
                epochId2, // app1 and app3 have same setup in epoch2
                Map.of(
                        app1, List.of(topic1, topic2),
                        app3, List.of(topic1, topic2)));
        mTopicsDao.persistAppClassificationTopics(
                epochId3, // app4 has topic2 as returned topic in epoch3, which won't be removed.
                Map.of(app4, List.of(topic2)));

        // Compute and persist TopicContributors table
        mTopicsDao.persistTopicContributors(
                epochId1,
                Map.of(
                        topic1.getTopic(), Set.of(app1, app2, app4),
                        topic2.getTopic(), Set.of(app1),
                        topic3.getTopic(), Set.of(app2, app4)));
        mTopicsDao.persistTopicContributors(
                epochId2,
                Map.of(
                        topic1.getTopic(), Set.of(app1, app3),
                        topic2.getTopic(), Set.of(app1, app3)));
        mTopicsDao.persistTopicContributors(epochId3, Map.of(topic2.getTopic(), Set.of(app4)));

        // Persist Usage table to ensure each app has called Topics API in favored epoch
        mTopicsDao.recordUsageHistory(epochId1, app1, sdk);
        mTopicsDao.recordUsageHistory(epochId1, app2, sdk);
        mTopicsDao.recordUsageHistory(epochId2, app1, sdk);
        mTopicsDao.recordUsageHistory(epochId2, app3, sdk);
        mTopicsDao.recordUsageHistory(epochId3, app4, sdk);

        // Persist ReturnedTopics table, all returned topics should be topic2 based on the setup
        mTopicsDao.persistReturnedAppTopicsMap(
                epochId1,
                Map.of(
                        Pair.create(app1, sdk), topic2,
                        Pair.create(app2, sdk), topic2));
        mTopicsDao.persistReturnedAppTopicsMap(
                epochId2,
                Map.of(
                        Pair.create(app1, sdk), topic2,
                        Pair.create(app3, sdk), topic2));
        mTopicsDao.persistReturnedAppTopicsMap(epochId3, Map.of(Pair.create(app4, sdk), topic2));

        // Real Cache Manager requires loading cache before getTopics() being called.
        // The results are observed at Epoch4
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(epochId4);
        mTopicsWorker.loadCache();
        // Enable Topic Contributors check feature
        doReturn(true).when(mDbHelper).supportsTopicContributorsTable();
        when(mMockFlags.getEnableTopicContributorsCheck()).thenReturn(true);

        // Verify apps are able to get topic before uninstallation happens
        GetTopicsResult topic2GetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(List.of(taxonomyVersion))
                        .setModelVersions(List.of(modelVersion))
                        .setTopics(List.of(topic2.getTopic()))
                        .build();
        assertThat(mTopicsWorker.getTopics(app1, sdk)).isEqualTo(topic2GetTopicsResult);
        assertThat(mTopicsWorker.getTopics(app2, sdk)).isEqualTo(topic2GetTopicsResult);
        assertThat(mTopicsWorker.getTopics(app3, sdk)).isEqualTo(topic2GetTopicsResult);
        assertThat(mTopicsWorker.getTopics(app4, sdk)).isEqualTo(topic2GetTopicsResult);

        // Uninstall app1
        Uri packageUri = Uri.parse("package:" + app1);
        mTopicsWorker.handleAppUninstallation(packageUri);

        // Verify Topics API results at Epoch 4
        GetTopicsResult emptyGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();

        // app1 doesn't have any returned topics due to uninstallation
        assertThat(mTopicsWorker.getTopics(app1, sdk)).isEqualTo(emptyGetTopicsResult);
        // app2 doesn't have returned topics as it only calls Topics API at Epoch1 and its returned
        // topic topic2 is cleaned due to app1's uninstallation.
        assertThat(mTopicsWorker.getTopics(app2, sdk)).isEqualTo(emptyGetTopicsResult);
        // app3 has topic2 as returned topic. topic2 won't be cleaned at Epoch2 as both app1 and
        // app3 are contributors to topic2 in Epoch3.
        assertThat(mTopicsWorker.getTopics(app3, sdk)).isEqualTo(topic2GetTopicsResult);
        // app4 has topic2 as returned topic. topic2 is cleaned as returned topic for app4 in
        // Epoch1. However, app4 is still able to return topic2 as topic2 is a returned topic for
        // app4 at Epoch3.
        assertThat(mTopicsWorker.getTopics(app4, sdk)).isEqualTo(topic2GetTopicsResult);

        // Verify TopicContributors Map is updated: app1 should be removed after the uninstallation.
        // To make the result more readable, original TopicContributors Map before uninstallation is
        // Epoch1:  topic1 -> app1, app2, app4
        //          topic2 -> app1
        //          topic3 -> app2, app4
        // Epoch2:  topic1 -> app1, app3
        //          topic2 -> app1, app3
        // Epoch3:  topic2 -> app4
        assertThat(mTopicsDao.retrieveTopicToContributorsMap(epochId1))
                .isEqualTo(
                        Map.of(
                                topic1.getTopic(),
                                Set.of(app2, app4),
                                topic3.getTopic(),
                                Set.of(app2, app4)));
        assertThat(mTopicsDao.retrieveTopicToContributorsMap(epochId2))
                .isEqualTo(
                        Map.of(topic1.getTopic(), Set.of(app3), topic2.getTopic(), Set.of(app3)));
        assertThat(mTopicsDao.retrieveTopicToContributorsMap(epochId3))
                .isEqualTo(Map.of(topic2.getTopic(), Set.of(app4)));
    }

    @Test
    public void testHandleAppUninstallation_contributorDeletionsToSameTopic() {
        // To test the scenario a topic has two contributors, and both are deleted consecutively.
        // Both app1 and app2 are contributors to topic1 and return topic1. app3 is not the
        // contributor but also returns topic1, learnt via same SDK.
        final long epochId1 = 1;
        final long epochId2 = 2;
        final long taxonomyVersion = 1L;
        final long modelVersion = 1L;
        final String app1 = "app1";
        final String app2 = "app2";
        final String app3 = "app3";
        final String sdk = "sdk";
        Topic topic1 = Topic.create(/* topic */ 1, taxonomyVersion, modelVersion);
        Topic topic2 = Topic.create(/* topic */ 2, taxonomyVersion, modelVersion);
        Topic topic3 = Topic.create(/* topic */ 3, taxonomyVersion, modelVersion);
        Topic topic4 = Topic.create(/* topic */ 4, taxonomyVersion, modelVersion);
        Topic topic5 = Topic.create(/* topic */ 5, taxonomyVersion, modelVersion);
        Topic topic6 = Topic.create(/* topic */ 6, taxonomyVersion, modelVersion);

        // Set the number in flag so that it doesn't depend on the actual value in PhFlags.
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(1);

        // Persist Top topics for epoch1 ~ epoch4
        mTopicsDao.persistTopTopics(
                epochId1, List.of(topic1, topic2, topic3, topic4, topic5, topic6));

        // Persist AppClassificationTopics Table
        mTopicsDao.persistAppClassificationTopics(
                epochId1,
                Map.of(
                        app1, List.of(topic1),
                        app2, List.of(topic1)));

        // Compute and persist TopicContributors table
        mTopicsDao.persistTopicContributors(
                epochId1, Map.of(topic1.getTopic(), Set.of(app1, app2)));

        // Persist ReturnedTopics table. App3 is able to
        mTopicsDao.persistReturnedAppTopicsMap(
                epochId1,
                Map.of(
                        Pair.create(app1, sdk), topic1,
                        Pair.create(app2, sdk), topic1,
                        Pair.create(app3, sdk), topic1));

        // Real Cache Manager requires loading cache before getTopics() being called.
        // The results are observed at EpochId = 2
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(epochId2);
        mTopicsWorker.loadCache();
        // Enable Topic Contributors check feature
        doReturn(true).when(mDbHelper).supportsTopicContributorsTable();
        when(mMockFlags.getEnableTopicContributorsCheck()).thenReturn(true);

        // An empty getTopics() result to verify
        GetTopicsResult emptyGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();

        // Delete app1
        mTopicsWorker.handleAppUninstallation(Uri.parse(app1));
        // app1 should be deleted from TopicContributors Map
        assertThat(mTopicsDao.retrieveTopicToContributorsMap(epochId1))
                .isEqualTo(Map.of(topic1.getTopic(), Set.of(app2)));
        // app1 should have empty result
        assertThat(mTopicsWorker.getTopics(app1, sdk)).isEqualTo(emptyGetTopicsResult);

        // Delete app2
        mTopicsWorker.handleAppUninstallation(Uri.parse(app2));
        // topic1 has app2 as the only contributor, and will be removed.
        assertThat(mTopicsDao.retrieveTopicToContributorsMap(epochId1)).isEmpty();
        // app2 should have empty result
        assertThat(mTopicsWorker.getTopics(app2, sdk)).isEqualTo(emptyGetTopicsResult);

        // As topic1 is removed, app3 also has empty result
        assertThat(mTopicsWorker.getTopics(app3, sdk)).isEqualTo(emptyGetTopicsResult);
    }

    @Test
    public void testHandleAppUninstallation_disableTopicContributorsCheck() {
        final String app = "app";
        Uri packageUri = Uri.parse("package:" + app);

        AppUpdateManager appUpdateManager =
                spy(new AppUpdateManager(mDbHelper, mTopicsDao, new Random(), mMockFlags));
        TopicsWorker topicsWorker =
                new TopicsWorker(
                        mMockEpochManager,
                        mCacheManager,
                        mBlockedTopicsManager,
                        appUpdateManager,
                        mMockFlags);

        when(mMockEpochManager.getCurrentEpochId()).thenReturn(/* any value */ 1L);
        when(appUpdateManager.convertUriToAppName(packageUri)).thenReturn(app);

        // Verify when feature flag is off
        doReturn(false).when(mDbHelper).supportsTopicContributorsTable();
        topicsWorker.handleAppUninstallation(packageUri);

        verify(appUpdateManager).convertUriToAppName(packageUri);
        verify(appUpdateManager, never()).handleTopTopicsWithoutContributors(anyLong(), any());
        verify(appUpdateManager).deleteAppDataFromTableByApps(List.of(app));
    }

    @Test
    public void testHandleAppInstallation() {
        final String appName = "app";
        Uri packageUri = Uri.parse("package:" + appName);
        final long currentEpochId = 4L;
        final long taxonomyVersion = 1L;
        final long modelVersion = 1L;
        final int numOfLookBackEpochs = 3;
        final int topicsNumberOfTopTopics = 5;
        final int topicsPercentageForRandomTopic = 5;

        // As selectAssignedTopicFromTopTopics() randomly assigns a top topic, pass in a Mocked
        // Random object to make the result deterministic.
        //
        // In this test, topic 1, 2, and 6 are supposed to be returned. For each topic, it needs 2
        // random draws: the first is to determine whether to select a random topic, the second is
        // draw the actual topic index.
        MockRandom mockRandom =
                new MockRandom(
                        new long[] {
                            topicsPercentageForRandomTopic, // Will select a regular topic
                            0, // Index of first topic
                            topicsPercentageForRandomTopic, // Will select a regular topic
                            1, // Index of second topic
                            0, // Will select a random topic
                            0 // Select the first random topic
                        });
        AppUpdateManager appUpdateManager =
                new AppUpdateManager(mDbHelper, mTopicsDao, mockRandom, mMockFlags);
        // Create a local TopicsWorker in order to user above local AppUpdateManager
        TopicsWorker topicsWorker =
                new TopicsWorker(
                        mMockEpochManager,
                        mCacheManager,
                        mBlockedTopicsManager,
                        appUpdateManager,
                        mMockFlags);

        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(numOfLookBackEpochs);
        when(mMockFlags.getTopicsNumberOfTopTopics()).thenReturn(topicsNumberOfTopTopics);
        when(mMockFlags.getTopicsPercentageForRandomTopic())
                .thenReturn(topicsPercentageForRandomTopic);
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        // Enable Topic Contributors check feature
        doReturn(true).when(mDbHelper).supportsTopicContributorsTable();
        when(mMockFlags.getEnableTopicContributorsCheck()).thenReturn(true);

        Topic topic1 = Topic.create(/* topic */ 1, taxonomyVersion, modelVersion);
        Topic topic2 = Topic.create(/* topic */ 2, taxonomyVersion, modelVersion);
        Topic topic3 = Topic.create(/* topic */ 3, taxonomyVersion, modelVersion);
        Topic topic4 = Topic.create(/* topic */ 4, taxonomyVersion, modelVersion);
        Topic topic5 = Topic.create(/* topic */ 5, taxonomyVersion, modelVersion);
        Topic topic6 = Topic.create(/* topic */ 6, taxonomyVersion, modelVersion);
        List<Topic> topTopics = List.of(topic1, topic2, topic3, topic4, topic5, topic6);

        // Persist top topics into database for last 3 epochs
        for (long epochId = currentEpochId - 1;
                epochId >= currentEpochId - numOfLookBackEpochs;
                epochId--) {
            mTopicsDao.persistTopTopics(epochId, topTopics);
            // Persist topics to TopicContributors Table avoid being filtered out
            for (Topic topic : topTopics) {
                mTopicsDao.persistTopicContributors(
                        epochId, Map.of(topic.getTopic(), Set.of(appName)));
            }
        }

        // Verify getTopics() returns nothing before calling assignTopicsToNewlyInstalledApps()
        GetTopicsResult emptyGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(Collections.emptyList())
                        .setModelVersions(Collections.emptyList())
                        .setTopics(Collections.emptyList())
                        .build();
        assertThat(topicsWorker.getTopics(appName, /* sdk */ "")).isEqualTo(emptyGetTopicsResult);

        // Assign topics to past epochs
        topicsWorker.handleAppInstallation(packageUri);

        GetTopicsResult expectedGetTopicsResult =
                new GetTopicsResult.Builder()
                        .setResultCode(STATUS_SUCCESS)
                        .setTaxonomyVersions(
                                Arrays.asList(taxonomyVersion, taxonomyVersion, taxonomyVersion))
                        .setModelVersions(Arrays.asList(modelVersion, modelVersion, modelVersion))
                        .setTopics(Arrays.asList(1, 2, 6))
                        .build();
        GetTopicsResult getTopicsResult = topicsWorker.getTopics(appName, /* sdk */ "");

        // Since the returned topic list is shuffled, elements have to be verified separately
        assertThat(getTopicsResult.getResultCode())
                .isEqualTo(expectedGetTopicsResult.getResultCode());
        assertThat(getTopicsResult.getTaxonomyVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTaxonomyVersions());
        assertThat(getTopicsResult.getModelVersions())
                .containsExactlyElementsIn(expectedGetTopicsResult.getModelVersions());
        assertThat(getTopicsResult.getTopics())
                .containsExactlyElementsIn(expectedGetTopicsResult.getTopics());

        verify(mMockFlags).getTopicsNumberOfTopTopics();
        verify(mMockFlags).getTopicsPercentageForRandomTopic();
    }
}