summaryrefslogtreecommitdiff
path: root/adservices/tests/unittest/service-core/src/com/android/adservices/service/topics/CacheManagerTest.java
blob: 0eda2af514414c5063bb3ac959b5b0ef4e78c726 (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
/*
 * 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 com.google.common.truth.Truth.assertThat;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.content.Context;
import android.util.Pair;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.filters.SmallTest;

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 org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** Unit tests for {@link com.android.adservices.service.topics.CacheManager} */
@SmallTest
public final class CacheManagerTest {
    @SuppressWarnings({"unused"})
    private static final String TAG = "CacheManagerTest";

    @SuppressWarnings({"unused"})
    private final Context mContext = ApplicationProvider.getApplicationContext();

    private TopicsDao mTopicsDao;

    @Mock Flags mMockFlags;
    @Mock EpochManager mMockEpochManager;

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

        // Erase all existing data.
        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);

        DbHelper dbHelper = DbTestUtil.getDbHelperForTest();
        mTopicsDao = new TopicsDao(dbHelper);

        // Erase all existing data.
        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);
    }

    @Test
    public void testGetTopics_emptyCache() {
        // The cache is empty when first created.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        List<Topic> topics = cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app", "sdk");

        assertThat(topics).isEmpty();
    }

    @Test
    public void testGetTopics() {
        // The cache is empty.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        // Assume the current epochId is 4L, we will load cache for returned topics in the last 3
        // epochs: epochId in {3, 2, 1}.
        long currentEpochId = 4L;
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        // Mock Flags to make it independent of configuration
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(3);

        Topic topic1 = Topic.create(/* topic */ 1, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic2 = Topic.create(/* topic */ 2, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic3 = Topic.create(/* topic */ 3, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic4 = Topic.create(/* topic */ 4, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic5 = Topic.create(/* topic */ 5, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);

        // EpochId 1
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap1 = new HashMap<>();
        returnedAppSdkTopicsMap1.put(Pair.create("app1", ""), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic1);

        returnedAppSdkTopicsMap1.put(Pair.create("app2", "sdk1"), topic2);
        returnedAppSdkTopicsMap1.put(Pair.create("app2", "sdk3"), topic2);
        returnedAppSdkTopicsMap1.put(Pair.create("app2", "sdk4"), topic2);

        returnedAppSdkTopicsMap1.put(Pair.create("app3", "sdk1"), topic3);

        returnedAppSdkTopicsMap1.put(Pair.create("app5", "sdk1"), topic5);
        returnedAppSdkTopicsMap1.put(Pair.create("app5", "sdk5"), topic5);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 1L, returnedAppSdkTopicsMap1);

        // EpochId 2
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap2 = new HashMap<>();

        returnedAppSdkTopicsMap2.put(Pair.create("app1", ""), topic2);
        returnedAppSdkTopicsMap2.put(Pair.create("app1", "sdk1"), topic2);
        returnedAppSdkTopicsMap2.put(Pair.create("app1", "sdk2"), topic2);

        returnedAppSdkTopicsMap2.put(Pair.create("app2", "sdk1"), topic3);
        returnedAppSdkTopicsMap2.put(Pair.create("app2", "sdk3"), topic3);
        returnedAppSdkTopicsMap2.put(Pair.create("app2", "sdk4"), topic3);

        returnedAppSdkTopicsMap2.put(Pair.create("app3", "sdk1"), topic4);

        returnedAppSdkTopicsMap2.put(Pair.create("app5", "sdk1"), topic1);
        returnedAppSdkTopicsMap2.put(Pair.create("app5", "sdk5"), topic1);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 2L, returnedAppSdkTopicsMap2);

        // EpochId 3
        // epochId == 3 does not have any topics. This could happen if the epoch computation failed
        // or the device was offline and no epoch computation was done.

        cacheManager.loadCache();

        verify(mMockEpochManager).getCurrentEpochId();
        verify(mMockFlags).getTopicsNumberOfLookBackEpochs();

        // Now look at epochId == 3 only by setting numberOfLookBackEpochs == 1.
        // Since the epochId 3 has empty cache, the results are always empty.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", "")).isEmpty();
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", "sdk1"))
                .isEmpty();
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", "sdk2"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app3", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app4", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app5", "sdk1"))
                .isEmpty();

        // Now look at epochId in {3, 2} only by setting numberOfLookBackEpochs = 2.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", ""))
                .isEqualTo(Collections.singletonList(topic2));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", "sdk1"))
                .isEqualTo(Collections.singletonList(topic2));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", "sdk2"))
                .isEqualTo(Collections.singletonList(topic2));

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app3", "sdk1"))
                .isEqualTo(Collections.singletonList(topic4));

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app4", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app5", "sdk1"))
                .isEqualTo(Collections.singletonList(topic1));

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app5", "sdk5"))
                .isEqualTo(Collections.singletonList(topic1));

        // Now look at epochId in [1,..,3] by setting numberOfLookBackEpochs = 3.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", ""))
                .containsExactlyElementsIn(Arrays.asList(topic2, topic1));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", "sdk1"))
                .containsExactlyElementsIn(Arrays.asList(topic2, topic1));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", "sdk2"))
                .containsExactlyElementsIn(Arrays.asList(topic2, topic1));

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app3", "sdk1"))
                .containsExactlyElementsIn(Arrays.asList(topic4, topic3));

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app4", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app5", "sdk1"))
                .containsExactlyElementsIn(Arrays.asList(topic1, topic5));
    }

    @Test
    public void testGetTopics_someTopicsBlocked() {
        // The cache is empty.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        // Assume the current epochId is 4L, we will load cache for returned topics in the last 3
        // epochs: epochId in {3, 2, 1}.
        long currentEpochId = 4L;
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        // Mock Flags to make it independent of configuration
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(3);

        Topic topic1 = Topic.create(/* topic */ 1, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic2 = Topic.create(/* topic */ 2, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic3 = Topic.create(/* topic */ 3, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic4 = Topic.create(/* topic */ 4, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic5 = Topic.create(/* topic */ 5, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);

        // EpochId 1
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap1 = new HashMap<>();
        returnedAppSdkTopicsMap1.put(Pair.create("app1", ""), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic1);

        returnedAppSdkTopicsMap1.put(Pair.create("app2", "sdk1"), topic2);
        returnedAppSdkTopicsMap1.put(Pair.create("app2", "sdk3"), topic2);
        returnedAppSdkTopicsMap1.put(Pair.create("app2", "sdk4"), topic2);

        returnedAppSdkTopicsMap1.put(Pair.create("app3", "sdk1"), topic3);

        returnedAppSdkTopicsMap1.put(Pair.create("app5", "sdk1"), topic5);
        returnedAppSdkTopicsMap1.put(Pair.create("app5", "sdk5"), topic5);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 1L, returnedAppSdkTopicsMap1);

        // EpochId 2
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap2 = new HashMap<>();

        returnedAppSdkTopicsMap2.put(Pair.create("app1", ""), topic2);
        returnedAppSdkTopicsMap2.put(Pair.create("app1", "sdk1"), topic2);
        returnedAppSdkTopicsMap2.put(Pair.create("app1", "sdk2"), topic2);

        returnedAppSdkTopicsMap2.put(Pair.create("app2", "sdk1"), topic3);
        returnedAppSdkTopicsMap2.put(Pair.create("app2", "sdk3"), topic3);
        returnedAppSdkTopicsMap2.put(Pair.create("app2", "sdk4"), topic3);

        returnedAppSdkTopicsMap2.put(Pair.create("app3", "sdk1"), topic4);

        returnedAppSdkTopicsMap2.put(Pair.create("app5", "sdk1"), topic1);
        returnedAppSdkTopicsMap2.put(Pair.create("app5", "sdk5"), topic1);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 2L, returnedAppSdkTopicsMap2);

        // EpochId 3
        // epochId == 3 does not have any topics. This could happen if the epoch computation failed
        // or the device was offline and no epoch computation was done.

        // block topic 2 and 4
        mTopicsDao.recordBlockedTopic(topic2);
        mTopicsDao.recordBlockedTopic(topic4);

        cacheManager.loadCache();

        verify(mMockEpochManager).getCurrentEpochId();
        verify(mMockFlags).getTopicsNumberOfLookBackEpochs();

        // Now look at epochId == 3 only by setting numberOfLookBackEpochs == 1.
        // Since the epochId 3 has empty cache, the results are always empty.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", "")).isEmpty();
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", "sdk1"))
                .isEmpty();
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", "sdk2"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app3", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app4", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app5", "sdk1"))
                .isEmpty();

        // Now look at epochId in {3, 2} only by setting numberOfLookBackEpochs = 2.
        // Should return topic2, but it's blocked - so emptyList is expected.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", "")).isEmpty();
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", "sdk1"))
                .isEmpty();
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", "sdk2"))
                .isEmpty();

        // Should return topic4, but it's blocked - so emptyList is expected.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app3", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app4", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app5", "sdk1"))
                .isEqualTo(Collections.singletonList(topic1));

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app5", "sdk5"))
                .isEqualTo(Collections.singletonList(topic1));

        // Now look at epochId in [1,..,3] by setting numberOfLookBackEpochs = 3.
        // Should return topic1 and topic2, but topic2 is blocked - so only topic1 is expected.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", ""))
                .containsExactlyElementsIn(Arrays.asList(topic1));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", "sdk1"))
                .containsExactlyElementsIn(Arrays.asList(topic1));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", "sdk2"))
                .containsExactlyElementsIn(Arrays.asList(topic1));

        // Should return topic3 and topic4, but topic4 is blocked - so only topic3 is expected.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app3", "sdk1"))
                .containsExactlyElementsIn(Arrays.asList(topic3));

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app4", "sdk1"))
                .isEmpty();

        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app5", "sdk1"))
                .containsExactlyElementsIn(Arrays.asList(topic1, topic5));
    }

    @Test
    public void testGetTopics_shuffling() {
        // In order to test the shuffling behavior, set the test case as looking back to 3 epochs
        // with 2 app/sdk pairs. Therefore, to get Topics for epoch 1 (current is 4) will return 3
        // topics for each app/sdk pair.

        // Mock the random with pre-defined values
        // The way how Collections.shuffle works is from the last element in the list, swap it with
        // a random index. Note index 0 won't be processed as it always swaps with itself
        // So for a list with size 3,
        // if (2,1) is passed into random object, the order will persist
        // if (0,1) is passed in, the order will be reversed. (swap index 2 with 0, rest remains the
        // same)

        // Since returned topics list is generated backwards from epoch 3 to epoch 1, if topics for
        // each epoch is (epoch 1 -> topic 1), (epoch 2 -> topic 2), (epoch 3 -> topic 3)
        // Without shuffling, returned topics list will be (topic3, topic2, topic1) for both app/sdk
        // pair 1
        // and app/sdk/ pair 2
        // With shuffling against above mocked random object, app/sdk pair 1 should remain the
        // order,
        // and app/sdk pair 2 should have returned topics list as (topic1, topic2, topic3)
        MockRandom mockRandom =
                new MockRandom(
                        new long[] {
                            /* first list */
                            2, 1, /* second list */ 0, 1
                        });

        // The cache is empty.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        // Assume the current epochId is 4L, we will load cache for returned topics in the last 3
        // epochs: epochId in {3, 2, 1}.
        long currentEpochId = 4L;
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        // Mock Flags to make it independent of configuration
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(3);

        Topic topic1 = Topic.create(/* topic */ 1, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic2 = Topic.create(/* topic */ 2, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic3 = Topic.create(/* topic */ 3, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        // EpochId 1
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap1 = new HashMap<>();
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic1);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 1L, returnedAppSdkTopicsMap1);

        // EpochId 2
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic2);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic2);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 2L, returnedAppSdkTopicsMap1);

        // EpochId 3
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic3);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic3);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 3L, returnedAppSdkTopicsMap1);

        cacheManager.loadCache();

        verify(mMockEpochManager).getCurrentEpochId();
        verify(mMockFlags).getTopicsNumberOfLookBackEpochs();

        // Look back to epoch 1
        // As described above, (app1, sdk1) should have returned topics in order (3, 2, 1), while
        // (app2, sdk2) should have returned topics in order (1, 2, 3).
        assertThat(
                        cacheManager.getTopics(
                                /* numberOfLookBackEpochs = */ 3, "app1", "sdk1", mockRandom))
                .isEqualTo(Arrays.asList(topic3, topic2, topic1));
        assertThat(
                        cacheManager.getTopics(
                                /* numberOfLookBackEpochs = */ 3, "app1", "sdk2", mockRandom))
                .isEqualTo(Arrays.asList(topic1, topic2, topic3));
    }

    @Test
    public void testGetTopics_duplicateTopics() {
        // The cache is empty.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        // Assume the current epochId is 4L, we will load cache for returned topics in the last 3
        // epochs: epochId in {3, 2, 1}.
        long currentEpochId = 4L;
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        // Mock Flags to make it independent of configuration
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(3);

        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);
        Topic topic3 =
                Topic.create(/* topic */ 3, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);

        // EpochId 1
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap1 = new HashMap<>();
        returnedAppSdkTopicsMap1.put(Pair.create("app1", ""), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic1);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 1L, returnedAppSdkTopicsMap1);

        // EpochId 2
        returnedAppSdkTopicsMap1.put(Pair.create("app1", ""), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic2);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic2);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 2L, returnedAppSdkTopicsMap1);

        // EpochId 3
        returnedAppSdkTopicsMap1.put(Pair.create("app1", ""), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic2);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic3);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 3L, returnedAppSdkTopicsMap1);

        cacheManager.loadCache();

        verify(mMockEpochManager).getCurrentEpochId();
        verify(mMockFlags).getTopicsNumberOfLookBackEpochs();

        // Now look at epochId == 3 only by setting numberOfLookBackEpochs == 1.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", ""))
                .isEqualTo(Collections.singletonList(topic1));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", "sdk1"))
                .isEqualTo(Collections.singletonList(topic2));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 1, "app1", "sdk2"))
                .isEqualTo(Collections.singletonList(topic3));

        // Now look at epochId == [2,3] by setting numberOfLookBackEpochs == 2.
        // Note for (app1, sdk1), both Epoch 2 and Epoch 3 have same value topic 2, which should be
        // deduplicated.
        // Same things for (app1, ""), both Epoch 2 and Epoch 3 have same value topic 1, which
        // should be deduplicated.
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", ""))
                .isEqualTo(Collections.singletonList(topic1));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", "sdk1"))
                .isEqualTo(Collections.singletonList(topic2));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 2, "app1", "sdk2"))
                .containsExactlyElementsIn(Arrays.asList(topic2, topic3));

        // Now look at epochId == [1,2,3] by setting numberOfLookBackEpochs == 3.
        // Note for (app1, ""), Epoch1, Epoch 2 and Epoch 3 have same value topic 1, which should be
        // deduplicated.
        // Note for (app1, sdk1), both Epoch 2 and Epoch 3 have same value topic 2, and Epoch 1 has
        // value topic 1, so it should return (topic1, topic2).
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", ""))
                .isEqualTo(Collections.singletonList(topic1));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", "sdk1"))
                .containsExactlyElementsIn(Arrays.asList(topic1, topic2));
        assertThat(cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app1", "sdk2"))
                .containsExactlyElementsIn(Arrays.asList(topic1, topic2, topic3));
    }

    // Currently SQLException is not thrown. This test needs to be uplifted after SQLException gets
    // handled.
    // TODO(b/230669931): Handle SQLException.
    @Test
    public void testGetTopics_failToLoadFromDb() {
        // The cache is empty when first created.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        // Fail to load from DB will have empty cache.

        List<Topic> topics = cacheManager.getTopics(/* numberOfLookBackEpochs = */ 3, "app", "sdk");

        assertThat(topics).isEmpty();
    }

    @Test
    public void testDump() {
        // Trigger the dump to verify no crash
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        PrintWriter printWriter = new PrintWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {

            }

            @Override
            public void flush() throws IOException {

            }

            @Override
            public void close() throws IOException {

            }
        });
        String[] args = new String[]{};
        cacheManager.dump(printWriter, args);
    }

    @Test
    public void testGetKnownTopicsWithConsent_noBlockedTopics() {
        // The cache is empty.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        // Assume the current epochId is 4L, we will load cache for returned topics in the last 3
        // epochs: epochId in {3, 2, 1}.
        long currentEpochId = 4L;
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        // Mock Flags to make it independent of configuration
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(3);

        Topic topic1 = Topic.create(/* topic */ 1, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic2 = Topic.create(/* topic */ 2, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);
        Topic topic4 = Topic.create(/* topic */ 4, /* taxonomyVersion */ 1L, /* modelVersion */ 1L);

        // EpochId 1
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap1 = new HashMap<>();
        returnedAppSdkTopicsMap1.put(Pair.create("app1", ""), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic1);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 1L, returnedAppSdkTopicsMap1);

        // EpochId 2
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap2 = new HashMap<>();
        returnedAppSdkTopicsMap2.put(Pair.create("app3", "sdk1"), topic2);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 2L, returnedAppSdkTopicsMap2);

        // EpochId 3
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap3 = new HashMap<>();
        returnedAppSdkTopicsMap3.put(Pair.create("app2", "sdk1"), topic4);
        returnedAppSdkTopicsMap3.put(Pair.create("app2", "sdk3"), topic4);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 3L, returnedAppSdkTopicsMap3);

        cacheManager.loadCache();

        verify(mMockEpochManager).getCurrentEpochId();
        verify(mMockFlags).getTopicsNumberOfLookBackEpochs();

        assertThat(cacheManager.getKnownTopicsWithConsent())
                .containsExactly(topic1, topic2, topic4);
    }

    @Test
    public void testGetKnownTopicsWithConsent_blockSomeTopics() {
        // The cache is empty.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        // Assume the current epochId is 4L, we will load cache for returned topics in the last 3
        // epochs: epochId in {3, 2, 1}.
        long currentEpochId = 4L;
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        // Mock Flags to make it independent of configuration
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(3);

        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);
        Topic topic4 =
                Topic.create(/* topic */ 4, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);

        // EpochId 1
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap1 = new HashMap<>();
        returnedAppSdkTopicsMap1.put(Pair.create("app1", ""), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic1);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 1L, returnedAppSdkTopicsMap1);

        // EpochId 2
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap2 = new HashMap<>();
        returnedAppSdkTopicsMap2.put(Pair.create("app3", "sdk1"), topic2);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 2L, returnedAppSdkTopicsMap2);

        // EpochId 3
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap3 = new HashMap<>();
        returnedAppSdkTopicsMap3.put(Pair.create("app2", "sdk1"), topic4);
        returnedAppSdkTopicsMap3.put(Pair.create("app2", "sdk3"), topic4);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 3L, returnedAppSdkTopicsMap3);

        // Block Topics
        mTopicsDao.recordBlockedTopic(topic2);

        cacheManager.loadCache();

        verify(mMockEpochManager).getCurrentEpochId();
        verify(mMockFlags).getTopicsNumberOfLookBackEpochs();

        assertThat(cacheManager.getKnownTopicsWithConsent()).containsExactly(topic1, topic4);
    }

    @Test
    public void testGetKnownTopicsWithConsent_blockAllTopics() {
        // The cache is empty.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

        // Assume the current epochId is 4L, we will load cache for returned topics in the last 3
        // epochs: epochId in {3, 2, 1}.
        long currentEpochId = 4L;
        when(mMockEpochManager.getCurrentEpochId()).thenReturn(currentEpochId);
        // Mock Flags to make it independent of configuration
        when(mMockFlags.getTopicsNumberOfLookBackEpochs()).thenReturn(3);

        Topic topic1 =
                Topic.create(/* topic */ 1, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);
        Topic topic2 =
                Topic.create(/* topic */ 2, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);
        Topic topic4 =
                Topic.create(/* topic */ 4, /* taxonomyVersion = */ 1L, /* modelVersion = */ 1L);

        // EpochId 1
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap1 = new HashMap<>();
        returnedAppSdkTopicsMap1.put(Pair.create("app1", ""), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk1"), topic1);
        returnedAppSdkTopicsMap1.put(Pair.create("app1", "sdk2"), topic1);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 1L, returnedAppSdkTopicsMap1);

        // EpochId 2
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap2 = new HashMap<>();
        returnedAppSdkTopicsMap2.put(Pair.create("app3", "sdk1"), topic2);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 2L, returnedAppSdkTopicsMap2);

        // EpochId 3
        Map<Pair<String, String>, Topic> returnedAppSdkTopicsMap3 = new HashMap<>();
        returnedAppSdkTopicsMap3.put(Pair.create("app2", "sdk1"), topic4);
        returnedAppSdkTopicsMap3.put(Pair.create("app2", "sdk3"), topic4);

        mTopicsDao.persistReturnedAppTopicsMap(/* epochId */ 3L, returnedAppSdkTopicsMap3);

        // Block Topics
        mTopicsDao.recordBlockedTopic(topic1);
        mTopicsDao.recordBlockedTopic(topic2);
        mTopicsDao.recordBlockedTopic(topic4);

        cacheManager.loadCache();

        verify(mMockEpochManager).getCurrentEpochId();
        verify(mMockFlags).getTopicsNumberOfLookBackEpochs();

        assertThat(cacheManager.getKnownTopicsWithConsent()).isEqualTo(Collections.emptyList());
    }

    @Test
    public void testClearAllTopicsData() {
        // The cache is empty.
        CacheManager cacheManager = new CacheManager(mMockEpochManager, mTopicsDao, mMockFlags);

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

        final String app1 = "app1";
        final String app2 = "app2";
        final String sdk1 = "sdk1";
        final String sdk2 = "sdk2";
        final long epochId1 = 1L;
        final long epochId2 = 1L;

        List<String> tableExclusionList = List.of(TopicsTables.BlockedTopicsContract.TABLE);

        // Persist data into tables
        // Below implementation may insert duplicate data into tables, but the duplicated data
        // should be handled correctly
        for (long epochId : new long[] {epochId1, epochId2}) {
            for (String app : new String[] {app1, app2}) {
                for (String sdk : new String[] {sdk1, sdk2}) {
                    mTopicsDao.recordUsageHistory(epochId, app, sdk);
                    mTopicsDao.recordAppUsageHistory(epochId, app);

                    mTopicsDao.persistReturnedAppTopicsMap(
                            epochId, Map.of(Pair.create(app, sdk), topic1));
                    mTopicsDao.persistReturnedAppTopicsMap(
                            epochId, Map.of(Pair.create(app, sdk), topic2));
                }
            }
            mTopicsDao.persistAppClassificationTopics(
                    epochId,
                    Map.of(
                            app1,
                            Arrays.asList(topic1, topic2),
                            app2,
                            Arrays.asList(topic1, topic2)));

            mTopicsDao.persistCallerCanLearnTopics(epochId, Map.of(topic1, Set.of(app1, sdk1)));
            mTopicsDao.persistCallerCanLearnTopics(epochId, Map.of(topic2, Set.of(app2, sdk2)));

            mTopicsDao.persistTopTopics(
                    epochId, List.of(topic1, topic2, topic3, topic4, topic5, topic6));
        }
        mTopicsDao.recordBlockedTopic(topic1);
        mTopicsDao.recordBlockedTopic(topic2);

        // Delete all tables except excluded ones.
        cacheManager.clearAllTopicsData(tableExclusionList);

        for (long epochId : new long[] {epochId1, epochId2}) {
            assertThat(mTopicsDao.retrieveAppUsageMap(epochId)).isEmpty();
            assertThat(mTopicsDao.retrieveAppSdksUsageMap(epochId)).isEmpty();
            assertThat(mTopicsDao.retrieveAppClassificationTopics(epochId)).isEmpty();
            assertThat(mTopicsDao.retrieveTopTopics(epochId)).isEmpty();

            // BlockedTopics Table is not cleared
            assertThat(mTopicsDao.retrieveAllBlockedTopics()).isNotEmpty();
        }
        assertThat(
                        mTopicsDao.retrieveCallerCanLearnTopicsMap(
                                /* current Epoch Id */ 3, /* look back Epochs */ 3))
                .isEmpty();
        assertThat(
                        mTopicsDao.retrieveReturnedTopics(
                                /* current Epoch Id */ 3, /* look back Epochs */ 3))
                .isEmpty();

        cacheManager.clearAllTopicsData(Collections.emptyList());
        assertThat(mTopicsDao.retrieveAllBlockedTopics()).isEmpty();

        // Also verify no topics will be returned as a second check
        cacheManager.loadCache();
        for (String app : new String[] {app1, app2}) {
            for (String sdk : new String[] {sdk1, sdk2}) {
                assertThat(cacheManager.getTopics((int) epochId2 + 1, app, sdk)).isEmpty();
            }
        }
    }
}