File: remote_suggestions_provider_impl_unittest.cc

package info (click to toggle)
chromium 90.0.4430.212-1~deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 3,450,632 kB
  • sloc: cpp: 19,832,434; javascript: 2,948,838; ansic: 2,312,399; python: 1,464,622; xml: 584,121; java: 514,189; asm: 470,557; objc: 83,463; perl: 77,861; sh: 77,030; cs: 70,789; fortran: 24,137; tcl: 18,916; php: 18,872; makefile: 16,848; ruby: 16,721; pascal: 13,150; sql: 10,199; yacc: 7,507; lex: 1,313; lisp: 840; awk: 329; jsp: 39; sed: 19
file content (3292 lines) | stat: -rw-r--r-- 140,344 bytes parent folder | download | duplicates (6)
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
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/ntp_snippets/remote/remote_suggestions_provider_impl.h"

#include <limits>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/i18n/rtl.h"
#include "base/json/json_reader.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/test/task_environment.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/time/default_clock.h"
#include "base/time/tick_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "components/feed/core/shared_prefs/pref_names.h"
#include "components/image_fetcher/core/fake_image_decoder.h"
#include "components/image_fetcher/core/image_decoder.h"
#include "components/image_fetcher/core/image_fetcher.h"
#include "components/image_fetcher/core/mock_image_fetcher.h"
#include "components/image_fetcher/core/request_metadata.h"
#include "components/leveldb_proto/testing/fake_db.h"
#include "components/ntp_snippets/category.h"
#include "components/ntp_snippets/category_info.h"
#include "components/ntp_snippets/category_rankers/category_ranker.h"
#include "components/ntp_snippets/category_rankers/constant_category_ranker.h"
#include "components/ntp_snippets/category_rankers/mock_category_ranker.h"
#include "components/ntp_snippets/fake_content_suggestions_provider_observer.h"
#include "components/ntp_snippets/features.h"
#include "components/ntp_snippets/ntp_snippets_constants.h"
#include "components/ntp_snippets/pref_names.h"
#include "components/ntp_snippets/remote/json_to_categories.h"
#include "components/ntp_snippets/remote/persistent_scheduler.h"
#include "components/ntp_snippets/remote/proto/ntp_snippets.pb.h"
#include "components/ntp_snippets/remote/remote_suggestion.h"
#include "components/ntp_snippets/remote/remote_suggestion_builder.h"
#include "components/ntp_snippets/remote/remote_suggestions_database.h"
#include "components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h"
#include "components/ntp_snippets/remote/remote_suggestions_scheduler.h"
#include "components/ntp_snippets/remote/remote_suggestions_status_service.h"
#include "components/ntp_snippets/remote/remote_suggestions_status_service_impl.h"
#include "components/ntp_snippets/remote/test_utils.h"
#include "components/ntp_snippets/time_serialization.h"
#include "components/ntp_snippets/user_classifier.h"
#include "components/prefs/testing_pref_service.h"
#include "components/strings/grit/components_strings.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_unittest_util.h"

using base::TestMockTimeTaskRunner;
using image_fetcher::ImageFetcher;
using image_fetcher::MockImageFetcher;
using leveldb_proto::test::FakeDB;
using ntp_snippets::test::FetchedCategoryBuilder;
using ntp_snippets::test::RemoteSuggestionBuilder;
using testing::_;
using testing::AnyNumber;
using testing::AtMost;
using testing::Contains;
using testing::ElementsAre;
using testing::ElementsAreArray;
using testing::Eq;
using testing::Field;
using testing::InSequence;
using testing::Invoke;
using testing::IsEmpty;
using testing::Matcher;
using testing::Mock;
using testing::MockFunction;
using testing::NiceMock;
using testing::Not;
using testing::Property;
using testing::Return;
using testing::SaveArg;
using testing::SizeIs;
using testing::StartsWith;
using testing::StrictMock;
using testing::WithArgs;

namespace ntp_snippets {

namespace {

ACTION_P(MoveFirstArgumentPointeeTo, ptr) {
  // 0-based indexation.
  *ptr = std::move(*arg0);
}

ACTION_P(MoveSecondArgumentPointeeTo, ptr) {
  // 0-based indexation.
  *ptr = std::move(*arg1);
}

const int kMaxExcludedDismissedIds = 100;

const base::Time::Exploded kDefaultCreationTime = {2015, 11, 4, 25, 13, 46, 45};

const char kSuggestionUrl[] = "http://localhost/foobar";
const char kSuggestionTitle[] = "Title";
const char kSuggestionText[] = "Suggestion";
const char kSuggestionPublisherName[] = "Foo News";
const char kImageUrl[] = "http://image/image.png";

const char kSuggestionUrl2[] = "http://foo.com/bar";

const char kTestJsonDefaultCategoryTitle[] = "Some title";

const int kOtherCategoryId = 2;
const int kUnknownRemoteCategoryId = 1234;

const int kTimeoutForRefetchWhileDisplayingSeconds = 5;

base::Time GetDefaultCreationTime() {
  base::Time out_time;
  EXPECT_TRUE(base::Time::FromUTCExploded(kDefaultCreationTime, &out_time));
  return out_time;
}

base::Time GetDefaultExpirationTime() {
  return base::Time::Now() + base::TimeDelta::FromHours(1);
}

// TODO(vitaliii): Remove this and use RemoteSuggestionBuilder instead.
std::unique_ptr<RemoteSuggestion> CreateTestRemoteSuggestion(
    const std::string& url) {
  SnippetProto snippet_proto;
  snippet_proto.add_ids(url);
  snippet_proto.set_title("title");
  snippet_proto.set_snippet("snippet");
  snippet_proto.set_salient_image_url(url + "p.jpg");
  snippet_proto.set_publish_date(SerializeTime(GetDefaultCreationTime()));
  snippet_proto.set_expiry_date(SerializeTime(GetDefaultExpirationTime()));
  snippet_proto.set_remote_category_id(1);
  auto* source = snippet_proto.mutable_source();
  source->set_url(url);
  source->set_publisher_name("Publisher");
  source->set_amp_url(url + "amp");
  return RemoteSuggestion::CreateFromProto(snippet_proto);
}

void ServeOneByOneImage(
    image_fetcher::ImageDataFetcherCallback* image_data_callback,
    image_fetcher::ImageFetcherCallback* callback) {
  std::move(*image_data_callback)
      .Run("1-by-1-image-data", image_fetcher::RequestMetadata());
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(std::move(*callback), gfx::test::CreateImage(1, 1),
                     image_fetcher::RequestMetadata()));
}

class MockScheduler : public RemoteSuggestionsScheduler {
 public:
  MOCK_METHOD1(SetProvider, void(RemoteSuggestionsProvider* provider));
  MOCK_METHOD0(OnProviderActivated, void());
  MOCK_METHOD0(OnProviderDeactivated, void());
  MOCK_METHOD0(OnSuggestionsCleared, void());
  MOCK_METHOD0(OnHistoryCleared, void());
  MOCK_METHOD0(AcquireQuotaForInteractiveFetch, bool());
  MOCK_METHOD1(OnInteractiveFetchFinished, void(Status fetch_status));
  MOCK_METHOD0(OnBrowserForegrounded, void());
  MOCK_METHOD0(OnBrowserColdStart, void());
  MOCK_METHOD0(OnSuggestionsSurfaceOpened, void());
  MOCK_METHOD0(OnPersistentSchedulerWakeUp, void());
  MOCK_METHOD0(OnBrowserUpgraded, void());
};

class MockRemoteSuggestionsFetcher : public RemoteSuggestionsFetcher {
 public:
  // GMock does not support movable-only types (SnippetsAvailableCallback is
  // OnceCallback), therefore, the call is redirected to a mock method with a
  // pointer to the callback.
  void FetchSnippets(const RequestParams& params,
                     SnippetsAvailableCallback callback) override {
    FetchSnippets(params, &callback);
  }
  MOCK_METHOD2(FetchSnippets,
               void(const RequestParams& params,
                    SnippetsAvailableCallback* callback));
  MOCK_CONST_METHOD0(GetLastStatusForDebugging, const std::string&());
  MOCK_CONST_METHOD0(GetLastJsonForDebugging, const std::string&());
  MOCK_CONST_METHOD0(WasLastFetchAuthenticatedForDebugging, bool());
  MOCK_CONST_METHOD0(GetFetchUrlForDebugging, const GURL&());
};

class MockRemoteSuggestionsStatusService
    : public RemoteSuggestionsStatusService {
 public:
  ~MockRemoteSuggestionsStatusService() override = default;

  MOCK_METHOD1(Init, void(const StatusChangeCallback& callback));
  MOCK_METHOD1(OnSignInStateChanged, void(bool));
  MOCK_METHOD1(OnListVisibilityToggled, void(bool));
};

std::string BoolToString(bool value) {
  return value ? "true" : "false";
}

base::Time GetDummyNow() {
  base::Time out_time;
  EXPECT_TRUE(base::Time::FromUTCString("2017-01-02T00:00:01Z", &out_time));
  return out_time;
}

}  // namespace

class RemoteSuggestionsProviderImplTest : public ::testing::Test {
 public:
  RemoteSuggestionsProviderImplTest()
      : category_ranker_(std::make_unique<ConstantCategoryRanker>()),
        user_classifier_(/*pref_service=*/nullptr,
                         base::DefaultClock::GetInstance()),
        mock_suggestions_fetcher_(nullptr),
        image_fetcher_(nullptr),
        scheduler_(std::make_unique<NiceMock<MockScheduler>>()),
        database_(nullptr),
        timer_mock_task_runner_(
            (new TestMockTimeTaskRunner(GetDummyNow(),
                                        base::TimeTicks::Now()))) {
    RemoteSuggestionsProviderImpl::RegisterProfilePrefs(
        utils_.pref_service()->registry());
    feed::prefs::RegisterFeedSharedProfilePrefs(
        utils_.pref_service()->registry());
    RequestThrottler::RegisterProfilePrefs(utils_.pref_service()->registry());
  }

  RemoteSuggestionsProviderImplTest(const RemoteSuggestionsProviderImplTest&) =
      delete;
  RemoteSuggestionsProviderImplTest& operator=(
      const RemoteSuggestionsProviderImplTest&) = delete;
  ~RemoteSuggestionsProviderImplTest() override {
    provider_.reset();
    observer_.reset();
    // We need to run until idle after deleting the database, because
    // ProtoDatabase deletes the actual LevelDB asynchronously on the task
    // runner. Without this, we'd get reports of memory leaks.
    RunUntilIdle();
  }

  void MakeSuggestionsProvider(
      bool use_mock_remote_suggestions_status_service) {
    MakeSuggestionsProviderWithoutInitialization(
        use_mock_remote_suggestions_status_service);
    WaitForSuggestionsProviderInitialization();
  }

  void MakeSuggestionsProviderWithoutInitialization(
      bool use_mock_remote_suggestions_status_service) {
    auto mock_suggestions_fetcher =
        std::make_unique<StrictMock<MockRemoteSuggestionsFetcher>>();
    mock_suggestions_fetcher_ = mock_suggestions_fetcher.get();

    std::unique_ptr<RemoteSuggestionsStatusService>
        remote_suggestions_status_service;
    if (use_mock_remote_suggestions_status_service) {
      auto mock_remote_suggestions_status_service =
          std::make_unique<StrictMock<MockRemoteSuggestionsStatusService>>();
      EXPECT_CALL(*mock_remote_suggestions_status_service, Init(_))
          .WillOnce(SaveArg<0>(&status_change_callback_));
      remote_suggestions_status_service =
          std::move(mock_remote_suggestions_status_service);
    } else {
      remote_suggestions_status_service =
          std::make_unique<RemoteSuggestionsStatusServiceImpl>(
              /*has_signed_in=*/false, utils_.pref_service(), std::string());
    }
    remote_suggestions_status_service_ =
        remote_suggestions_status_service.get();

    auto image_fetcher = std::make_unique<NiceMock<MockImageFetcher>>();

    image_fetcher_ = image_fetcher.get();
    ON_CALL(*image_fetcher, GetImageDecoder())
        .WillByDefault(Return(&image_decoder_));
    EXPECT_FALSE(observer_);
    observer_ = std::make_unique<FakeContentSuggestionsProviderObserver>();

    // Setup RemoteSuggestionsDatabase with fake ProtoDBs.
    auto suggestion_db =
        std::make_unique<FakeDB<SnippetProto>>(&suggestion_db_storage_);
    auto image_db =
        std::make_unique<FakeDB<SnippetImageProto>>(&image_db_storage_);
    suggestion_db_ = suggestion_db.get();
    image_db_ = image_db.get();
    auto database = std::make_unique<RemoteSuggestionsDatabase>(
        std::move(suggestion_db), std::move(image_db));
    database_ = database.get();
    suggestion_db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);
    image_db_->InitStatusCallback(leveldb_proto::Enums::InitStatus::kOK);

    auto fetch_timeout_timer = std::make_unique<base::OneShotTimer>(
        timer_mock_task_runner_->GetMockTickClock());
    fetch_timeout_timer->SetTaskRunner(timer_mock_task_runner_);

    provider_ = std::make_unique<RemoteSuggestionsProviderImpl>(
        observer_.get(), utils_.pref_service(), "fr", category_ranker_.get(),
        scheduler_.get(), std::move(mock_suggestions_fetcher),
        std::move(image_fetcher), std::move(database),
        std::move(remote_suggestions_status_service),
        std::move(fetch_timeout_timer));
  }

  void MakeSuggestionsProviderWithoutInitializationWithStrictScheduler() {
    scheduler_ = std::make_unique<StrictMock<MockScheduler>>();
    MakeSuggestionsProviderWithoutInitialization(
        /*use_mock_remote_suggestions_status_service=*/false);
  }

  void WaitForSuggestionsProviderInitialization() {
    EXPECT_EQ(RemoteSuggestionsProviderImpl::State::NOT_INITED,
              provider_->state_);

    suggestion_db()->LoadCallback(true);
  }

  void ResetSuggestionsProvider(
      bool use_mock_remote_suggestions_status_service) {
    provider_.reset();
    observer_.reset();
    MakeSuggestionsProvider(use_mock_remote_suggestions_status_service);
  }

  void ResetSuggestionsProviderWithoutInitialization(
      bool use_mock_remote_suggestions_status_service) {
    provider_.reset();
    observer_.reset();
    MakeSuggestionsProviderWithoutInitialization(
        use_mock_remote_suggestions_status_service);
  }

  void RunUntilIdle() {
    timer_mock_task_runner_->RunUntilIdle();
    task_environment_.RunUntilIdle();
  }

  void SetCategoryRanker(std::unique_ptr<CategoryRanker> category_ranker) {
    category_ranker_ = std::move(category_ranker);
  }

  ContentSuggestion::ID MakeArticleID(const std::string& id_within_category) {
    return ContentSuggestion::ID(articles_category(), id_within_category);
  }

  Category articles_category() {
    return Category::FromKnownCategory(KnownCategories::ARTICLES);
  }

  ContentSuggestion::ID MakeOtherID(const std::string& id_within_category) {
    return ContentSuggestion::ID(Category::FromRemoteCategory(kOtherCategoryId),
                                 id_within_category);
  }

  FakeDB<SnippetProto>* suggestion_db() { return suggestion_db_; }
  FakeDB<SnippetImageProto>* image_db() { return image_db_; }

  RemoteSuggestionsProviderImpl* provider() { return provider_.get(); }

  MOCK_METHOD1(OnImageFetched, void(const gfx::Image&));

 protected:
  FakeContentSuggestionsProviderObserver& observer() { return *observer_; }
  StrictMock<MockRemoteSuggestionsFetcher>* mock_suggestions_fetcher() {
    return mock_suggestions_fetcher_;
  }
  // TODO(tschumann): Make this a strict-mock. We want to avoid unneccesary
  // network requests.
  NiceMock<MockImageFetcher>* image_fetcher() { return image_fetcher_; }
  image_fetcher::FakeImageDecoder* image_decoder() { return &image_decoder_; }
  PrefService* pref_service() { return utils_.pref_service(); }
  RemoteSuggestionsDatabase* database() { return database_; }
  MockScheduler* scheduler() { return scheduler_.get(); }

  void FetchTheseSuggestions(
      bool interactive_request,
      Status status,
      base::Optional<std::vector<FetchedCategory>> fetched_categories) {
    RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
    EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
        .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
        .RetiresOnSaturation();
    provider_->FetchSuggestions(
        interactive_request, RemoteSuggestionsProvider::FetchStatusCallback());
    std::move(snippets_callback).Run(status, std::move(fetched_categories));
  }

  void FetchMoreTheseSuggestions(
      const Category& category,
      const std::set<std::string>& known_suggestion_ids,
      FetchDoneCallback fetch_done_callback,
      Status status,
      base::Optional<std::vector<FetchedCategory>> fetched_categories) {
    RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
    EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
        .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
        .RetiresOnSaturation();
    EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
        .WillOnce(Return(true))
        .RetiresOnSaturation();
    provider_->Fetch(category, known_suggestion_ids,
                     std::move(fetch_done_callback));
    std::move(snippets_callback).Run(status, std::move(fetched_categories));
  }

  RemoteSuggestionsFetcher::SnippetsAvailableCallback
  FetchSuggestionsAndGetResponseCallback(
      bool interactive_request) {
    RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
    EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
        .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
        .RetiresOnSaturation();
    provider_->FetchSuggestions(
        interactive_request, RemoteSuggestionsProvider::FetchStatusCallback());
    return snippets_callback;
  }

  RemoteSuggestionsFetcher::SnippetsAvailableCallback
  RefetchWhileDisplayingAndGetResponseCallback() {
    RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
    EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
        .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
        .RetiresOnSaturation();
    provider_->RefetchWhileDisplaying(
        RemoteSuggestionsProvider::FetchStatusCallback());
    return snippets_callback;
  }

  RemoteSuggestionsFetcher::SnippetsAvailableCallback
  ReloadSuggestionsAndGetResponseCallback() {
    EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
        .WillOnce(Return(true))
        .RetiresOnSaturation();
    RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
    EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
        .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
        .RetiresOnSaturation();
    provider_->ReloadSuggestions();
    return snippets_callback;
  }

  void ChangeRemoteSuggestionsStatus(RemoteSuggestionsStatus old_status,
                                     RemoteSuggestionsStatus new_status) {
    EXPECT_FALSE(status_change_callback_.is_null());
    status_change_callback_.Run(old_status, new_status);
  }

  void SetOrderNewRemoteCategoriesBasedOnArticlesCategoryParam(bool value) {
    scoped_feature_list_.Reset();
    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        kArticleSuggestionsFeature,
        {{"order_new_remote_categories_based_on_articles_category",
          value ? "true" : "false"}});
  }

  void SetTriggeringNotificationsAndSubscriptionParams(
      bool fetched_notifications_enabled,
      bool pushed_notifications_enabled,
      bool subscribe_signed_in,
      bool subscribe_signed_out) {
    scoped_feature_list_.Reset();
    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        kNotificationsFeature,
        {
            {"enable_fetched_suggestions_notifications",
             BoolToString(fetched_notifications_enabled)},
            {"enable_pushed_suggestions_notifications",
             BoolToString(pushed_notifications_enabled)},
            {"enable_signed_in_users_subscription_for_pushed_suggestions",
             BoolToString(subscribe_signed_in)},
            {"enable_signed_out_users_subscription_for_pushed_suggestions",
             BoolToString(subscribe_signed_out)},
        });
  }

  void SetFetchedNotificationsParams(bool enable, bool force) {
    scoped_feature_list_.Reset();
    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        kNotificationsFeature,
        {
            {"enable_fetched_suggestions_notifications", BoolToString(enable)},
            {"force_fetched_suggestions_notifications", BoolToString(force)},
        });
  }

  void SetFetchMoreSuggestionsCount(int count) {
    scoped_feature_list_.Reset();
    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        kArticleSuggestionsFeature,
        {{"fetch_more_suggestions_count", base::NumberToString(count)}});
  }

  void FastForwardBy(const base::TimeDelta& delta) {
    timer_mock_task_runner_->FastForwardBy(delta);
  }

  gfx::Image FetchImage(const ContentSuggestion::ID& suggestion_id) {
    gfx::Image result;
    provider_->FetchSuggestionImage(
        suggestion_id,
        base::BindOnce([](gfx::Image* output,
                          const gfx::Image& loaded) { *output = loaded; },
                       &result));
    image_db_->GetCallback(true);
    RunUntilIdle();
    return result;
  }

 private:
  std::unique_ptr<RemoteSuggestionsProviderImpl> provider_;

  base::test::ScopedFeatureList scoped_feature_list_;
  test::RemoteSuggestionsTestUtils utils_;
  std::unique_ptr<CategoryRanker> category_ranker_;
  UserClassifier user_classifier_;
  std::unique_ptr<FakeContentSuggestionsProviderObserver> observer_;
  StrictMock<MockRemoteSuggestionsFetcher>* mock_suggestions_fetcher_;
  NiceMock<MockImageFetcher>* image_fetcher_;
  image_fetcher::FakeImageDecoder image_decoder_;
  std::unique_ptr<MockScheduler> scheduler_;
  RemoteSuggestionsStatusService* remote_suggestions_status_service_;
  base::test::TaskEnvironment task_environment_;

  RemoteSuggestionsStatusService::StatusChangeCallback status_change_callback_;

  RemoteSuggestionsDatabase* database_;
  std::map<std::string, SnippetProto> suggestion_db_storage_;
  std::map<std::string, SnippetImageProto> image_db_storage_;

  // Owned by |database_|.
  FakeDB<SnippetProto>* suggestion_db_;
  FakeDB<SnippetImageProto>* image_db_;

  scoped_refptr<TestMockTimeTaskRunner> timer_mock_task_runner_;
};

TEST_F(RemoteSuggestionsProviderImplTest, Full) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .AddId(kSuggestionUrl)
                                       .SetTitle(kSuggestionTitle)
                                       .SetSnippet(kSuggestionText)
                                       .SetImageUrl(kImageUrl)
                                       .SetPublishDate(GetDefaultCreationTime())
                                       .SetPublisher(kSuggestionPublisherName))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
  ASSERT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));

  const ContentSuggestion& suggestion =
      observer().SuggestionsForCategory(articles_category()).front();

  EXPECT_EQ(MakeArticleID(kSuggestionUrl), suggestion.id());
  EXPECT_EQ(kSuggestionTitle, base::UTF16ToUTF8(suggestion.title()));
  EXPECT_EQ(kSuggestionText, base::UTF16ToUTF8(suggestion.snippet_text()));
  EXPECT_EQ(kImageUrl, suggestion.salient_image_url());
  EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date());
  EXPECT_EQ(kSuggestionPublisherName,
            base::UTF16ToUTF8(suggestion.publisher_name()));
}

TEST_F(RemoteSuggestionsProviderImplTest, CategoryTitle) {
  const base::string16 test_default_title =
      base::UTF8ToUTF16(kTestJsonDefaultCategoryTitle);

  // Don't send an initial response -- we want to test what happens without any
  // server status.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // The articles category should be there by default, and have a title.
  CategoryInfo info_before = provider()->GetCategoryInfo(articles_category());
  ASSERT_THAT(info_before.title(), Not(IsEmpty()));
  ASSERT_THAT(info_before.title(), Not(Eq(test_default_title)));
  EXPECT_THAT(info_before.additional_action(),
              Eq(ContentSuggestionsAdditionalAction::FETCH));
  EXPECT_THAT(info_before.show_if_empty(), Eq(true));

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .SetTitle(base::UTF16ToUTF8(test_default_title))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder())
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
  ASSERT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));

  // The response contained a title, |kTestJsonDefaultCategoryTitle|.
  // Make sure we updated the title in the CategoryInfo.
  CategoryInfo info_with_title =
      provider()->GetCategoryInfo(articles_category());
  EXPECT_THAT(info_before.title(), Not(Eq(info_with_title.title())));
  EXPECT_THAT(test_default_title, Eq(info_with_title.title()));
  EXPECT_THAT(info_before.additional_action(),
              Eq(ContentSuggestionsAdditionalAction::FETCH));
  EXPECT_THAT(info_before.show_if_empty(), Eq(true));
}

TEST_F(RemoteSuggestionsProviderImplTest, MultipleCategories) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(1))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder()
                  .AddId(base::StringPrintf("%s/%d", kSuggestionUrl, 0))
                  .SetTitle(kSuggestionTitle)
                  .SetSnippet(kSuggestionText)
                  .SetPublishDate(GetDefaultCreationTime())
                  .SetPublisher(kSuggestionPublisherName))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(2))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder()
                  .AddId(base::StringPrintf("%s/%d", kSuggestionUrl, 1))
                  .SetTitle(kSuggestionTitle)
                  .SetSnippet(kSuggestionText)
                  .SetPublishDate(GetDefaultCreationTime())
                  .SetPublisher(kSuggestionPublisherName))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(observer().statuses(),
              Eq(std::map<Category, CategoryStatus, Category::CompareByID>{
                  {articles_category(), CategoryStatus::AVAILABLE},
                  {Category::FromRemoteCategory(kOtherCategoryId),
                   CategoryStatus::AVAILABLE},
              }));

  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(
                  Category::FromRemoteCategory(kOtherCategoryId)),
              SizeIs(1));

  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));

  ASSERT_THAT(observer().SuggestionsForCategory(
                  Category::FromRemoteCategory(kOtherCategoryId)),
              SizeIs(1));

  {
    const ContentSuggestion& suggestion =
        observer().SuggestionsForCategory(articles_category()).front();
    EXPECT_EQ(MakeArticleID(std::string(kSuggestionUrl) + "/0"),
              suggestion.id());
    EXPECT_EQ(kSuggestionTitle, base::UTF16ToUTF8(suggestion.title()));
    EXPECT_EQ(kSuggestionText, base::UTF16ToUTF8(suggestion.snippet_text()));
    EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date());
    EXPECT_EQ(kSuggestionPublisherName,
              base::UTF16ToUTF8(suggestion.publisher_name()));
  }

  {
    const ContentSuggestion& suggestion =
        observer()
            .SuggestionsForCategory(
                Category::FromRemoteCategory(kOtherCategoryId))
            .front();
    EXPECT_EQ(MakeOtherID(std::string(kSuggestionUrl) + "/1"), suggestion.id());
    EXPECT_EQ(kSuggestionTitle, base::UTF16ToUTF8(suggestion.title()));
    EXPECT_EQ(kSuggestionText, base::UTF16ToUTF8(suggestion.snippet_text()));
    EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date());
    EXPECT_EQ(kSuggestionPublisherName,
              base::UTF16ToUTF8(suggestion.publisher_name()));
  }
}

TEST_F(RemoteSuggestionsProviderImplTest, ArticleCategoryInfo) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  CategoryInfo article_info = provider()->GetCategoryInfo(articles_category());
  EXPECT_THAT(article_info.additional_action(),
              Eq(ContentSuggestionsAdditionalAction::FETCH));
  EXPECT_THAT(article_info.show_if_empty(), Eq(true));
}

TEST_F(RemoteSuggestionsProviderImplTest, ExperimentalCategoryInfo) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(1))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("1"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(kUnknownRemoteCategoryId))
          .SetAdditionalAction(ContentSuggestionsAdditionalAction::NONE)
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("2"))
          .Build());
  // Load data with multiple categories so that a new experimental category gets
  // registered.
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  CategoryInfo info = provider()->GetCategoryInfo(
      Category::FromRemoteCategory(kUnknownRemoteCategoryId));
  EXPECT_THAT(info.additional_action(),
              Eq(ContentSuggestionsAdditionalAction::NONE));
  EXPECT_THAT(info.show_if_empty(), Eq(false));
}

TEST_F(RemoteSuggestionsProviderImplTest, AddRemoteCategoriesToCategoryRanker) {
  auto mock_ranker = std::make_unique<MockCategoryRanker>();
  MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
  SetCategoryRanker(std::move(mock_ranker));
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(11))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("11"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(13))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("13"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(12))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("12"))
          .Build());
  {
    // The order of categories is determined by the order in which they are
    // added. Thus, the latter is tested here.
    InSequence s;
    EXPECT_CALL(*raw_mock_ranker,
                AppendCategoryIfNecessary(Category::FromRemoteCategory(11)));
    EXPECT_CALL(*raw_mock_ranker,
                AppendCategoryIfNecessary(Category::FromRemoteCategory(13)));
    EXPECT_CALL(*raw_mock_ranker,
                AppendCategoryIfNecessary(Category::FromRemoteCategory(12)));
  }
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       AddRemoteCategoriesToCategoryRankerRelativeToArticles) {
  SetOrderNewRemoteCategoriesBasedOnArticlesCategoryParam(true);
  auto mock_ranker = std::make_unique<MockCategoryRanker>();
  MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
  SetCategoryRanker(std::move(mock_ranker));
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(14))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("14"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(13))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("13"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(1))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("1"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(12))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("12"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(11))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("11"))
          .Build());
  {
    InSequence s;
    EXPECT_CALL(*raw_mock_ranker,
                InsertCategoryBeforeIfNecessary(
                    Category::FromRemoteCategory(14), articles_category()));
    EXPECT_CALL(*raw_mock_ranker,
                InsertCategoryBeforeIfNecessary(
                    Category::FromRemoteCategory(13), articles_category()));
    EXPECT_CALL(*raw_mock_ranker,
                InsertCategoryAfterIfNecessary(Category::FromRemoteCategory(11),
                                               articles_category()));
    EXPECT_CALL(*raw_mock_ranker,
                InsertCategoryAfterIfNecessary(Category::FromRemoteCategory(12),
                                               articles_category()));
  }
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
}

TEST_F(
    RemoteSuggestionsProviderImplTest,
    AddRemoteCategoriesToCategoryRankerRelativeToArticlesWithArticlesAbsent) {
  SetOrderNewRemoteCategoriesBasedOnArticlesCategoryParam(true);
  auto mock_ranker = std::make_unique<MockCategoryRanker>();
  MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
  SetCategoryRanker(std::move(mock_ranker));
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(11))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("11"))
          .Build());

  EXPECT_CALL(*raw_mock_ranker, InsertCategoryBeforeIfNecessary(_, _)).Times(0);
  EXPECT_CALL(*raw_mock_ranker,
              AppendCategoryIfNecessary(Category::FromRemoteCategory(11)));
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
}

TEST_F(RemoteSuggestionsProviderImplTest, PersistCategoryInfos) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("1"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(kUnknownRemoteCategoryId))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("2"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_EQ(observer().StatusForCategory(articles_category()),
            CategoryStatus::AVAILABLE);
  ASSERT_EQ(observer().StatusForCategory(
                Category::FromRemoteCategory(kUnknownRemoteCategoryId)),
            CategoryStatus::AVAILABLE);

  CategoryInfo info_articles_before =
      provider()->GetCategoryInfo(articles_category());
  CategoryInfo info_unknown_before = provider()->GetCategoryInfo(
      Category::FromRemoteCategory(kUnknownRemoteCategoryId));

  base::i18n::SetICUDefaultLocale("de");
  // Recreate the provider to simulate a Chrome restart.
  ResetSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // The categories should have been restored.
  ASSERT_NE(observer().StatusForCategory(articles_category()),
            CategoryStatus::NOT_PROVIDED);
  ASSERT_NE(observer().StatusForCategory(
                Category::FromRemoteCategory(kUnknownRemoteCategoryId)),
            CategoryStatus::NOT_PROVIDED);

  EXPECT_EQ(observer().StatusForCategory(articles_category()),
            CategoryStatus::AVAILABLE);
  EXPECT_EQ(observer().StatusForCategory(
                Category::FromRemoteCategory(kUnknownRemoteCategoryId)),
            CategoryStatus::AVAILABLE);

  CategoryInfo info_articles_after =
      provider()->GetCategoryInfo(articles_category());
  CategoryInfo info_unknown_after = provider()->GetCategoryInfo(
      Category::FromRemoteCategory(kUnknownRemoteCategoryId));

  // The new articles section title should reflect the current locale, not what
  // we persisted earlier.
  EXPECT_NE(info_articles_before.title(), info_articles_after.title());
  EXPECT_EQ(
      info_articles_after.title(),
      l10n_util::GetStringUTF16(IDS_NTP_ARTICLE_SUGGESTIONS_SECTION_HEADER));
  EXPECT_EQ(info_unknown_before.title(), info_unknown_after.title());
}

TEST_F(RemoteSuggestionsProviderImplTest, PersistRemoteCategoryOrder) {
  // We create a provider with a normal ranker to store the order.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(11))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("11"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(13))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("13"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(12))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("12"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // We manually recreate the provider to simulate Chrome restart and enforce a
  // mock ranker.
  auto mock_ranker = std::make_unique<MockCategoryRanker>();
  MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
  SetCategoryRanker(std::move(mock_ranker));
  // Ensure that the order is not fetched.
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)).Times(0);
  {
    // The order of categories is determined by the order in which they are
    // added. Thus, the latter is tested here.
    InSequence s;
    // Article category always exists and, therefore, it is stored in prefs too.
    EXPECT_CALL(*raw_mock_ranker,
                AppendCategoryIfNecessary(articles_category()));

    EXPECT_CALL(*raw_mock_ranker,
                AppendCategoryIfNecessary(Category::FromRemoteCategory(11)));
    EXPECT_CALL(*raw_mock_ranker,
                AppendCategoryIfNecessary(Category::FromRemoteCategory(13)));
    EXPECT_CALL(*raw_mock_ranker,
                AppendCategoryIfNecessary(Category::FromRemoteCategory(12)));
  }
  ResetSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
}

TEST_F(RemoteSuggestionsProviderImplTest, PersistSuggestions) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(1))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("1").SetRemoteCategoryId(1))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(2))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("2").SetRemoteCategoryId(2))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
  ASSERT_THAT(observer().SuggestionsForCategory(
                  Category::FromRemoteCategory(kOtherCategoryId)),
              SizeIs(1));

  // Recreate the provider to simulate a Chrome restart.
  ResetSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // The suggestions in both categories should have been restored.
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
  EXPECT_THAT(observer().SuggestionsForCategory(
                  Category::FromRemoteCategory(kOtherCategoryId)),
              SizeIs(1));
}

TEST_F(RemoteSuggestionsProviderImplTest, ClearSuggestionsOnInit) {
  // Add suggestions.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(1))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("1").SetRemoteCategoryId(1))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(2))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("2").SetRemoteCategoryId(2))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
  ASSERT_THAT(observer().SuggestionsForCategory(
                  Category::FromRemoteCategory(kOtherCategoryId)),
              SizeIs(1));

  // Reset the provider and clear the suggestions before it is inited.
  ResetSuggestionsProviderWithoutInitialization(
      /*use_mock_remote_suggestions_status_service=*/false);
  provider()->ClearCachedSuggestions();

  // The suggestions in both categories should have been cleared after the init.
  WaitForSuggestionsProviderInitialization();
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(0));
  EXPECT_THAT(observer().SuggestionsForCategory(
                  Category::FromRemoteCategory(kOtherCategoryId)),
              SizeIs(0));
}

TEST_F(RemoteSuggestionsProviderImplTest, DontNotifyIfNotAvailable) {
  // Get some suggestions into the database.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(1))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("1"))
          .Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(2))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("2"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
  ASSERT_THAT(observer().SuggestionsForCategory(
                  Category::FromRemoteCategory(kOtherCategoryId)),
              SizeIs(1));

  // Set the pref that disables remote suggestions.
  pref_service()->SetBoolean(feed::prefs::kEnableSnippets, false);

  // Recreate the provider to simulate a Chrome start.
  ResetSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  ASSERT_THAT(RemoteSuggestionsProviderImpl::State::DISABLED,
              Eq(provider()->state_));

  // Now the observer should not have received any suggestions.
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              IsEmpty());
  EXPECT_THAT(observer().SuggestionsForCategory(
                  Category::FromRemoteCategory(kOtherCategoryId)),
              IsEmpty());
}

TEST_F(RemoteSuggestionsProviderImplTest, Clear) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("1"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));

  provider()->ClearCachedSuggestions();
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());
}

TEST_F(RemoteSuggestionsProviderImplTest, ReplaceSuggestions) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::string first("http://first");
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId(first))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              ElementsAre(Pointee(Property(&RemoteSuggestion::id, first))));

  std::string second("http://second");
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId(second))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  // The suggestions loaded last replace all that was loaded previously.
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              ElementsAre(Pointee(Property(&RemoteSuggestion::id, second))));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldResolveFetchedSuggestionThumbnail) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("id"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  ASSERT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              ElementsAre(Pointee(Property(&RemoteSuggestion::id, "id"))));

  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
  EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _))
      .WillOnce(WithArgs<1, 2>(Invoke(&ServeOneByOneImage)));

  gfx::Image image = FetchImage(MakeArticleID("id"));

  ASSERT_FALSE(image.IsEmpty());
  EXPECT_EQ(1, image.Width());
}

TEST_F(RemoteSuggestionsProviderImplTest, ShouldFetchMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("first"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  ASSERT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              ElementsAre(Pointee(Property(&RemoteSuggestion::id, "first"))));

  auto expect_only_second_suggestion_received = base::BindOnce(
      [](Status status, std::vector<ContentSuggestion> suggestions) {
        EXPECT_THAT(suggestions, SizeIs(1));
        EXPECT_THAT(suggestions[0].id().id_within_category(), Eq("second"));
      });
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("second"))
          .Build());
  FetchMoreTheseSuggestions(
      articles_category(),
      /*known_suggestion_ids=*/std::set<std::string>(),
      /*fetch_done_callback=*/std::move(expect_only_second_suggestion_received),
      Status::Success(), std::move(fetched_categories));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldResolveFetchedMoreSuggestionThumbnail) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId("id"))
          .Build());

  auto assert_only_first_suggestion_received = base::BindOnce(
      [](Status status, std::vector<ContentSuggestion> suggestions) {
        ASSERT_THAT(suggestions, SizeIs(1));
        ASSERT_THAT(suggestions[0].id().id_within_category(), Eq("id"));
      });
  FetchMoreTheseSuggestions(
      articles_category(),
      /*known_suggestion_ids=*/std::set<std::string>(),
      /*fetch_done_callback=*/std::move(assert_only_first_suggestion_received),
      Status::Success(), std::move(fetched_categories));

  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
  EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _))
      .WillOnce(WithArgs<1, 2>(Invoke(&ServeOneByOneImage)));

  gfx::Image image = FetchImage(MakeArticleID("id"));
  ASSERT_FALSE(image.IsEmpty());
  EXPECT_EQ(1, image.Width());
}

// Imagine that we have surfaces A and B. The user fetches more in A, this
// should not add any suggestions to B.
TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldNotChangeSuggestionsInOtherSurfacesWhenFetchingMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Fetch a suggestion.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://old.com/"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              ElementsAre(Property(&ContentSuggestion::id,
                                   MakeArticleID("http://old.com/"))));

  // Now fetch more, but first prepare a response.
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://fetched-more.com/"))
          .Build());

  // The surface issuing the fetch more gets response via callback.
  auto assert_receiving_one_new_suggestion = base::BindOnce(
      [](Status status, std::vector<ContentSuggestion> suggestions) {
        ASSERT_THAT(suggestions, SizeIs(1));
        ASSERT_THAT(suggestions[0].id().id_within_category(),
                    Eq("http://fetched-more.com/"));
      });
  FetchMoreTheseSuggestions(
      articles_category(),
      /*known_suggestion_ids=*/{"http://old.com/"},
      /*fetch_done_callback=*/std::move(assert_receiving_one_new_suggestion),
      Status::Success(), std::move(fetched_categories));

  // Other surfaces should remain the same.
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              ElementsAre(Property(&ContentSuggestion::id,
                                   MakeArticleID("http://old.com/"))));
}

// Imagine that we have surfaces A and B. The user fetches more in A. This
// should not affect the next fetch more in B, i.e. assuming the same server
// response the same suggestions must be fetched in B if the user fetches more
// there as well.
TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldNotAffectFetchMoreInOtherSurfacesWhenFetchingMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Fetch more on the surface A.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(FetchedCategory(
      articles_category(),
      BuildRemoteCategoryInfo(base::UTF8ToUTF16("title"),
                              /*allow_fetching_more_results=*/true)));
  fetched_categories[0].suggestions.push_back(
      CreateTestRemoteSuggestion("http://fetched-more.com/"));

  auto assert_receiving_one_new_suggestion = base::BindOnce(
      [](Status status, std::vector<ContentSuggestion> suggestions) {
        ASSERT_THAT(suggestions, SizeIs(1));
        ASSERT_THAT(suggestions[0].id().id_within_category(),
                    Eq("http://fetched-more.com/"));
      });
  RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
      .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
      .RetiresOnSaturation();
  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  provider()->Fetch(articles_category(),
                    /*known_suggestion_ids=*/std::set<std::string>(),
                    std::move(assert_receiving_one_new_suggestion));
  std::move(snippets_callback)
      .Run(Status::Success(), std::move(fetched_categories));

  // Now fetch more on the surface B. The response is the same as before.
  fetched_categories.clear();
  fetched_categories.push_back(FetchedCategory(
      articles_category(),
      BuildRemoteCategoryInfo(base::UTF8ToUTF16("title"),
                              /*allow_fetching_more_results=*/true)));
  fetched_categories[0].suggestions.push_back(
      CreateTestRemoteSuggestion("http://fetched-more.com/"));

  // B should receive the same suggestion as was fetched more on A.
  auto expect_receiving_same_suggestion = base::BindOnce(
      [](Status status, std::vector<ContentSuggestion> suggestions) {
        ASSERT_THAT(suggestions, SizeIs(1));
        EXPECT_THAT(suggestions[0].id().id_within_category(),
                    Eq("http://fetched-more.com/"));
      });
  // The provider should not ask the fetcher to exclude the suggestion fetched
  // more on A.
  EXPECT_CALL(*mock_suggestions_fetcher(),
              FetchSnippets(Field(&RequestParams::excluded_ids,
                                  Not(Contains("http://fetched-more.com/"))),
                            _))
      .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
      .RetiresOnSaturation();
  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  provider()->Fetch(articles_category(),
                    /*known_suggestion_ids=*/std::set<std::string>(),
                    std::move(expect_receiving_same_suggestion));
  std::move(snippets_callback)
      .Run(Status::Success(), std::move(fetched_categories));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ClearHistoryShouldDeleteArchivedSuggestions) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  // First get suggestions into the archived state which happens through
  // subsequent fetches. Then we verify the entries are gone from the 'archived'
  // state by trying to load their images (and we shouldn't even know the URLs
  // anymore).
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://id-1"))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://id-2"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://new-id-1"))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://new-id-2"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  // Make sure images of both batches are available. This is to sanity check our
  // assumptions for the test are right.
  EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _))
      .Times(2)
      .WillRepeatedly(WithArgs<1, 2>(Invoke(&ServeOneByOneImage)));
  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
  gfx::Image image = FetchImage(MakeArticleID("http://id-1"));
  ASSERT_FALSE(image.IsEmpty());
  ASSERT_EQ(1, image.Width());
  image = FetchImage(MakeArticleID("http://new-id-1"));
  ASSERT_FALSE(image.IsEmpty());
  ASSERT_EQ(1, image.Width());

  provider()->ClearHistory(base::Time::UnixEpoch(), base::Time::Max(),
                           base::RepeatingCallback<bool(const GURL& url)>());

  // Make sure images of both batches are gone.
  // Verify we cannot resolve the image of the new suggestions.
  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));

  EXPECT_CALL(*this, OnImageFetched(Property(&gfx::Image::IsEmpty, Eq(true))))
      .Times(2);
  provider()->FetchSuggestionImage(
      MakeArticleID("http://id-1"),
      base::BindOnce(&RemoteSuggestionsProviderImplTest::OnImageFetched,
                     base::Unretained(this)));
  provider()->FetchSuggestionImage(
      MakeArticleID("http://new-id-1"),
      base::BindOnce(&RemoteSuggestionsProviderImplTest::OnImageFetched,
                     base::Unretained(this)));
}

namespace {

// Workaround for gMock's lack of support for movable types.
void SuggestionsLoaded(
    MockFunction<void(Status, const std::vector<ContentSuggestion>&)>* loaded,
    Status status,
    std::vector<ContentSuggestion> suggestions) {
  loaded->Call(status, suggestions);
}

}  // namespace

TEST_F(RemoteSuggestionsProviderImplTest, ReturnFetchRequestEmptyBeforeInit) {
  MakeSuggestionsProviderWithoutInitialization(
      /*use_mock_remote_suggestions_status_service=*/false);
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)).Times(0);
  MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
  EXPECT_CALL(loaded, Call(Field(&Status::code, StatusCode::TEMPORARY_ERROR),
                           IsEmpty()));
  provider()->Fetch(articles_category(), std::set<std::string>(),
                    base::BindOnce(&SuggestionsLoaded, &loaded));
  RunUntilIdle();
}

TEST_F(RemoteSuggestionsProviderImplTest, ReturnRefetchRequestEmptyBeforeInit) {
  MakeSuggestionsProviderWithoutInitialization(
      /*use_mock_remote_suggestions_status_service=*/false);
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)).Times(0);
  MockFunction<void(Status)> loaded;
  EXPECT_CALL(loaded, Call(Field(&Status::code, StatusCode::TEMPORARY_ERROR)));
  provider()->RefetchInTheBackground(base::BindOnce(
      &MockFunction<void(Status)>::Call, base::Unretained(&loaded)));
  RunUntilIdle();
}

TEST_F(RemoteSuggestionsProviderImplTest, IgnoreRefetchRequestEmptyBeforeInit) {
  MakeSuggestionsProviderWithoutInitialization(
      /*use_mock_remote_suggestions_status_service=*/false);
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)).Times(0);
  provider()->RefetchInTheBackground(
      RemoteSuggestionsProvider::FetchStatusCallback());
  RunUntilIdle();
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldForwardTemporaryErrorFromFetcher) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
  MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
      .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback));
  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  provider()->Fetch(articles_category(),
                    /*known_ids=*/std::set<std::string>(),
                    base::BindOnce(&SuggestionsLoaded, &loaded));

  EXPECT_CALL(loaded, Call(Field(&Status::code, StatusCode::TEMPORARY_ERROR),
                           IsEmpty()));
  ASSERT_FALSE(snippets_callback.is_null());
  std::move(snippets_callback)
      .Run(Status(StatusCode::TEMPORARY_ERROR, "Received invalid JSON"),
           base::nullopt);
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldNotAddNewSuggestionsAfterFetchError) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  FetchTheseSuggestions(
      /*interactive_request=*/false,
      Status(StatusCode::TEMPORARY_ERROR, "Received invalid JSON"),
      base::nullopt);
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldNotClearOldSuggestionsAfterFetchError) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(FetchedCategory(
      articles_category(),
      BuildRemoteCategoryInfo(base::UTF8ToUTF16("title"),
                              /*allow_fetching_more_results=*/true)));
  fetched_categories[0].suggestions.push_back(
      CreateTestRemoteSuggestion(base::StringPrintf("http://abc.com/")));
  FetchTheseSuggestions(/*interactive_request=*/false, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(
      provider()->GetSuggestionsForTesting(articles_category()),
      ElementsAre(Pointee(Property(&RemoteSuggestion::id, "http://abc.com/"))));

  FetchTheseSuggestions(
      /*interactive_request=*/false,
      Status(StatusCode::TEMPORARY_ERROR, "Received invalid JSON"),
      base::nullopt);
  // This should not have changed the existing suggestions.
  EXPECT_THAT(
      provider()->GetSuggestionsForTesting(articles_category()),
      ElementsAre(Pointee(Property(&RemoteSuggestion::id, "http://abc.com/"))));
}

TEST_F(RemoteSuggestionsProviderImplTest, Dismiss) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  const FetchedCategoryBuilder category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://site.com"));
  fetched_categories.push_back(category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));
  // Load the image to store it in the database.
  EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _))
      .WillOnce(WithArgs<1, 2>(Invoke(&ServeOneByOneImage)));
  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
  gfx::Image image = FetchImage(MakeArticleID("http://site.com"));
  EXPECT_FALSE(image.IsEmpty());
  EXPECT_EQ(1, image.Width());

  // Dismissing a non-existent suggestion shouldn't do anything.
  provider()->DismissSuggestion(MakeArticleID("http://othersite.com"));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));

  // Dismiss the suggestion.
  provider()->DismissSuggestion(MakeArticleID("http://site.com"));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());

  // Verify we can still load the image of the discarded suggestion (other NTPs
  // might still reference it). This should come from the database -- no network
  // fetch necessary.
  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
  image = FetchImage(MakeArticleID("http://site.com"));
  EXPECT_FALSE(image.IsEmpty());
  EXPECT_EQ(1, image.Width());

  // Make sure that fetching the same suggestion again does not re-add it.
  fetched_categories.clear();
  fetched_categories.push_back(category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());

  // The suggestion should stay dismissed even after re-creating the provider.
  ResetSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  fetched_categories.clear();
  fetched_categories.push_back(category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());

  // The suggestion can be added again after clearing dismissed suggestions.
  provider()->ClearDismissedSuggestionsForDebugging(articles_category());
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());
  fetched_categories.clear();
  fetched_categories.push_back(category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));
}

TEST_F(RemoteSuggestionsProviderImplTest, GetDismissed) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://site.com"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  provider()->DismissSuggestion(MakeArticleID("http://site.com"));

  provider()->GetDismissedSuggestionsForDebugging(
      articles_category(),
      base::BindOnce(
          [](RemoteSuggestionsProviderImpl* provider,
             RemoteSuggestionsProviderImplTest* test,
             std::vector<ContentSuggestion> dismissed_suggestions) {
            EXPECT_EQ(1u, dismissed_suggestions.size());
            for (auto& suggestion : dismissed_suggestions) {
              EXPECT_EQ(test->MakeArticleID("http://site.com"),
                        suggestion.id());
            }
          },
          provider(), this));
  RunUntilIdle();

  // There should be no dismissed suggestion after clearing the list.
  provider()->ClearDismissedSuggestionsForDebugging(articles_category());
  provider()->GetDismissedSuggestionsForDebugging(
      articles_category(),
      base::BindOnce(
          [](RemoteSuggestionsProviderImpl* provider,
             RemoteSuggestionsProviderImplTest* test,
             std::vector<ContentSuggestion> dismissed_suggestions) {
            EXPECT_EQ(0u, dismissed_suggestions.size());
          },
          provider(), this));
  RunUntilIdle();
}

TEST_F(RemoteSuggestionsProviderImplTest, RemoveExpiredDismissedContent) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .AddId("http://first/")
                                       .SetExpiryDate(base::Time::Now()))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  // Load the image to store it in the database.
  // TODO(tschumann): Introduce some abstraction to nicely work with image
  // fetching expectations.
  EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _))
      .WillOnce(WithArgs<1, 2>(Invoke(&ServeOneByOneImage)));
  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
  gfx::Image image = FetchImage(MakeArticleID("http://first/"));
  EXPECT_FALSE(image.IsEmpty());
  EXPECT_EQ(1, image.Width());

  // Dismiss the suggestion
  provider()->DismissSuggestion(
      ContentSuggestion::ID(articles_category(), "http://first/"));

  // Load a different suggestion - this will clear the expired dismissed ones.
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://second/"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  EXPECT_THAT(
      provider()->GetDismissedSuggestionsForTesting(articles_category()),
      IsEmpty());

  // Verify the image got removed, too.
  EXPECT_CALL(*this, OnImageFetched(Property(&gfx::Image::IsEmpty, Eq(true))));
  provider()->FetchSuggestionImage(
      MakeArticleID("http://first/"),
      base::BindOnce(&RemoteSuggestionsProviderImplTest::OnImageFetched,
                     base::Unretained(this)));
}

TEST_F(RemoteSuggestionsProviderImplTest, ExpiredContentNotRemoved) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetExpiryDate(base::Time::Now()))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));
}

TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSource) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .AddId("http://source1.com")
                                       .SetUrl("http://source1.com")
                                       .SetPublisher("Source 1")
                                       .SetAmpUrl("http://source1.amp.com"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));
  const RemoteSuggestion& suggestion =
      *provider()->GetSuggestionsForTesting(articles_category()).front();
  EXPECT_EQ(suggestion.id(), "http://source1.com");
  EXPECT_EQ(suggestion.url(), GURL("http://source1.com"));
  EXPECT_EQ(suggestion.publisher_name(), std::string("Source 1"));
  EXPECT_EQ(suggestion.amp_url(), GURL("http://source1.amp.com"));
}

TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSourceWithMissingData) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetPublisher("").SetAmpUrl(""))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());
}

TEST_F(RemoteSuggestionsProviderImplTest, LogNumArticlesHistogram) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  base::HistogramTester tester;

  FetchTheseSuggestions(/*interactive_request=*/true,
                        Status(StatusCode::TEMPORARY_ERROR, "message"),
                        base::nullopt);
  // Error responses don't update the list of suggestions and shouldn't
  // influence these metrics.
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"),
              IsEmpty());
  // Fetch error shouldn't contribute to NumArticlesFetched.
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"),
              IsEmpty());

  // TODO(tschumann): The expectations in these tests have high dependencies on
  // the sequence of unrelated events. This test should be split up into
  // multiple tests.

  // Empty categories list.
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::vector<FetchedCategory>());
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"),
              IsEmpty());

  // Empty articles category.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder().SetCategory(articles_category()).Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/2)));
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));

  // Suggestion list should be populated with size 1.
  const FetchedCategoryBuilder category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://site.com/"));
  fetched_categories.clear();
  fetched_categories.push_back(category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/2),
                          base::Bucket(/*min=*/1, /*count=*/1)));
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/1),
                          base::Bucket(/*min=*/1, /*count=*/1)));

  // Duplicate suggestion shouldn't increase the list size.
  fetched_categories.clear();
  fetched_categories.push_back(category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/2),
                          base::Bucket(/*min=*/1, /*count=*/2)));
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/1),
                          base::Bucket(/*min=*/1, /*count=*/2)));
  EXPECT_THAT(
      tester.GetAllSamples("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded"),
      IsEmpty());

  // Dismissing a suggestion should decrease the list size. This will only be
  // logged after the next fetch.
  provider()->DismissSuggestion(MakeArticleID("http://site.com/"));
  fetched_categories.clear();
  fetched_categories.push_back(category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/3),
                          base::Bucket(/*min=*/1, /*count=*/2)));
  // Dismissed suggestions shouldn't influence NumArticlesFetched.
  EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"),
              ElementsAre(base::Bucket(/*min=*/0, /*count=*/1),
                          base::Bucket(/*min=*/1, /*count=*/3)));
  EXPECT_THAT(
      tester.GetAllSamples("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded"),
      ElementsAre(base::Bucket(/*min=*/1, /*count=*/1)));
}

TEST_F(RemoteSuggestionsProviderImplTest, DismissShouldRespectAllKnownUrls) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  const std::vector<std::string> source_urls = {
      "http://mashable.com/2016/05/11/stolen",
      "http://www.aol.com/article/2016/05/stolen-doggie"};
  const std::vector<std::string> publishers = {"Mashable", "AOL"};
  const std::vector<std::string> amp_urls = {
      "http://mashable-amphtml.googleusercontent.com/1",
      "http://t2.gstatic.com/images?q=tbn:3"};

  // Add the suggestion from the mashable domain.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .AddId(source_urls[0])
                                       .AddId(source_urls[1])
                                       .SetUrl(source_urls[0])
                                       .SetAmpUrl(amp_urls[0])
                                       .SetPublisher(publishers[0]))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  ASSERT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(1));
  // Dismiss the suggestion via the mashable source corpus ID.
  provider()->DismissSuggestion(MakeArticleID(source_urls[0]));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());

  // The same article from the AOL domain should now be detected as dismissed.
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .AddId(source_urls[0])
                                       .AddId(source_urls[1])
                                       .SetUrl(source_urls[1])
                                       .SetAmpUrl(amp_urls[1])
                                       .SetPublisher(publishers[1]))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  EXPECT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              IsEmpty());
}

TEST_F(RemoteSuggestionsProviderImplTest, ImageReturnedWithTheSameId) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId(kSuggestionUrl))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _))
      .WillOnce(WithArgs<1, 2>(Invoke(&ServeOneByOneImage)));

  gfx::Image image = FetchImage(MakeArticleID(kSuggestionUrl));

  // Check that the image by ServeOneByOneImage is really served.
  EXPECT_EQ(1, image.Width());
}

TEST_F(RemoteSuggestionsProviderImplTest, EmptyImageReturnedForNonExistentId) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Create a non-empty image so that we can test the image gets updated.
  gfx::Image image = gfx::test::CreateImage(1, 1);
  MockFunction<void(const gfx::Image&)> image_fetched;
  EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image));

  provider()->FetchSuggestionImage(
      MakeArticleID("nonexistent"),
      base::BindOnce(&MockFunction<void(const gfx::Image&)>::Call,
                     base::Unretained(&image_fetched)));

  RunUntilIdle();
  EXPECT_TRUE(image.IsEmpty());
}

TEST_F(RemoteSuggestionsProviderImplTest,
       FetchingUnknownImageIdShouldNotHitDatabase) {
  // Testing that the provider is not accessing the database is tricky.
  // Therefore, we simply put in some data making sure that if the provider asks
  // the database, it will get a wrong answer.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  ContentSuggestion::ID unknown_id = MakeArticleID(kSuggestionUrl2);
  database()->SaveImage(unknown_id.id_within_category(), "some image blob");
  // Set up the image decoder to always return the 1x1 test image.
  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));

  // Create a non-empty image so that we can test the image gets updated.
  gfx::Image image = gfx::test::CreateImage(2, 2);
  MockFunction<void(const gfx::Image&)> image_fetched;
  EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image));

  provider()->FetchSuggestionImage(
      MakeArticleID(kSuggestionUrl2),
      base::BindOnce(&MockFunction<void(const gfx::Image&)>::Call,
                     base::Unretained(&image_fetched)));

  RunUntilIdle();
  EXPECT_TRUE(image.IsEmpty()) << "got image with width: " << image.Width();
}

TEST_F(RemoteSuggestionsProviderImplTest, ClearHistoryRemovesAllSuggestions) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://first/"))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://second/"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  ASSERT_THAT(provider()->GetSuggestionsForTesting(articles_category()),
              SizeIs(2));

  provider()->DismissSuggestion(MakeArticleID("http://first/"));
  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              Not(IsEmpty()));
  ASSERT_THAT(
      provider()->GetDismissedSuggestionsForTesting(articles_category()),
      SizeIs(1));

  base::Time begin = base::Time::FromTimeT(123),
             end = base::Time::FromTimeT(456);
  base::RepeatingCallback<bool(const GURL& url)> filter;
  provider()->ClearHistory(begin, end, filter);

  // Verify that the observer received the update with the empty data as well.
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              IsEmpty());
  EXPECT_THAT(
      provider()->GetDismissedSuggestionsForTesting(articles_category()),
      IsEmpty());
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldKeepArticlesCategoryAvailableAfterClearHistory) {
  // If the provider marks that category as NOT_PROVIDED, then it won't be shown
  // at all in the UI and the user cannot load new data :-/.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  ASSERT_THAT(observer().StatusForCategory(articles_category()),
              Eq(CategoryStatus::AVAILABLE));
  provider()->ClearHistory(base::Time::UnixEpoch(), base::Time::Max(),
                           base::RepeatingCallback<bool(const GURL& url)>());

  EXPECT_THAT(observer().StatusForCategory(articles_category()),
              Eq(CategoryStatus::AVAILABLE));
}

TEST_F(RemoteSuggestionsProviderImplTest, ShouldClearOrphanedImagesOnRestart) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId(kSuggestionUrl))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  EXPECT_CALL(*image_fetcher(), FetchImageAndData_(_, _, _, _))
      .WillOnce(WithArgs<1, 2>(Invoke(&ServeOneByOneImage)));
  image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));

  gfx::Image image = FetchImage(MakeArticleID(kSuggestionUrl));
  EXPECT_EQ(1, image.Width());
  EXPECT_FALSE(image.IsEmpty());

  // Send new suggestion which don't include the suggestion referencing the
  // image.
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId(
              "http://something.com/pletely/unrelated"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // The image should still be available until a restart happens.
  EXPECT_FALSE(FetchImage(MakeArticleID(kSuggestionUrl)).IsEmpty());
  ResetSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  // After the restart, the image should be garbage collected.
  EXPECT_CALL(*this, OnImageFetched(Property(&gfx::Image::IsEmpty, Eq(true))));
  provider()->FetchSuggestionImage(
      MakeArticleID(kSuggestionUrl),
      base::BindOnce(&RemoteSuggestionsProviderImplTest::OnImageFetched,
                     base::Unretained(this)));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldHandleMoreThanMaxSuggestionsInResponse) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  FetchedCategoryBuilder category_builder;
  category_builder.SetCategory(articles_category());
  for (int i = 0;
       i < provider()->GetMaxNormalFetchSuggestionCountForTesting() + 1; ++i) {
    category_builder.AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId(
        base::StringPrintf("http://localhost/suggestion-id-%d", i)));
  }
  fetched_categories.push_back(category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  // TODO(tschumann): We should probably trim out any additional results and
  // only serve the MaxSuggestionCount items.
  EXPECT_THAT(
      provider()->GetSuggestionsForTesting(articles_category()),
      SizeIs(provider()->GetMaxNormalFetchSuggestionCountForTesting() + 1));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       StoreLastSuccessfullBackgroundFetchTime) {
  // On initialization of the RemoteSuggestionsProviderImpl a background fetch
  // is triggered since the suggestions DB is empty. Therefore the provider must
  // not be initialized until the test clock is set.
  MakeSuggestionsProviderWithoutInitialization(
      /*use_mock_remote_suggestions_status_service=*/false);

  base::SimpleTestClock simple_test_clock;
  provider()->SetClockForTesting(&simple_test_clock);

  // Test that the preference is correctly initialized with the default value 0.
  EXPECT_EQ(
      0, pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));

  WaitForSuggestionsProviderInitialization();
  EXPECT_EQ(
      SerializeTime(simple_test_clock.Now()),
      pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));

  // Advance the time and check whether the time was updated correctly after the
  // background fetch.
  simple_test_clock.Advance(base::TimeDelta::FromHours(1));

  RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
      .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
      .RetiresOnSaturation();
  provider()->RefetchInTheBackground(
      RemoteSuggestionsProvider::FetchStatusCallback());
  RunUntilIdle();
  std::move(snippets_callback).Run(Status::Success(), base::nullopt);
  // TODO(jkrcal): Move together with the pref storage into the scheduler.
  EXPECT_EQ(
      SerializeTime(simple_test_clock.Now()),
      pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
  // TODO(markusheintz): Add a test that simulates a browser restart once the
  // scheduler refactoring is done (crbug.com/672434).
}

TEST_F(RemoteSuggestionsProviderImplTest, CallsSchedulerWhenReady) {
  MakeSuggestionsProviderWithoutInitializationWithStrictScheduler();

  // Should be called when becoming ready.
  EXPECT_CALL(*scheduler(), OnProviderActivated());
  WaitForSuggestionsProviderInitialization();
}

TEST_F(RemoteSuggestionsProviderImplTest, CallsSchedulerOnError) {
  MakeSuggestionsProviderWithoutInitializationWithStrictScheduler();

  // Should be called on error.
  EXPECT_CALL(*scheduler(), OnProviderDeactivated());
  provider()->EnterState(RemoteSuggestionsProviderImpl::State::ERROR_OCCURRED);
}

TEST_F(RemoteSuggestionsProviderImplTest, CallsSchedulerWhenDisabled) {
      MakeSuggestionsProviderWithoutInitializationWithStrictScheduler();

  // Should be called when becoming disabled. First deactivate and only after
  // that clear the suggestions so that they are not fetched again.
  {
    InSequence s;
    EXPECT_CALL(*scheduler(), OnProviderDeactivated());
    ASSERT_THAT(provider()->ready(), Eq(false));
    EXPECT_CALL(*scheduler(), OnSuggestionsCleared());
  }
  provider()->EnterState(RemoteSuggestionsProviderImpl::State::DISABLED);
}

TEST_F(RemoteSuggestionsProviderImplTest, CallsSchedulerWhenHistoryCleared) {
      MakeSuggestionsProviderWithoutInitializationWithStrictScheduler();
  // Initiate the provider so that it is already READY.
  EXPECT_CALL(*scheduler(), OnProviderActivated());
  WaitForSuggestionsProviderInitialization();

  // The scheduler should be notified of clearing the history.
  EXPECT_CALL(*scheduler(), OnHistoryCleared());
  provider()->ClearHistory(GetDefaultCreationTime(), GetDefaultExpirationTime(),
                           base::RepeatingCallback<bool(const GURL& url)>());
}

TEST_F(RemoteSuggestionsProviderImplTest, CallsSchedulerWhenSignedIn) {
      MakeSuggestionsProviderWithoutInitializationWithStrictScheduler();
  // Initiate the provider so that it is already READY.
  EXPECT_CALL(*scheduler(), OnProviderActivated());
  WaitForSuggestionsProviderInitialization();

  // The scheduler should be notified of clearing the history.
  EXPECT_CALL(*scheduler(), OnSuggestionsCleared());
  provider()->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN,
                              RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT);
}

TEST_F(RemoteSuggestionsProviderImplTest, CallsSchedulerWhenSignedOut) {
      MakeSuggestionsProviderWithoutInitializationWithStrictScheduler();
  // Initiate the provider so that it is already READY.
  EXPECT_CALL(*scheduler(), OnProviderActivated());
  WaitForSuggestionsProviderInitialization();

  // The scheduler should be notified of clearing the history.
  EXPECT_CALL(*scheduler(), OnSuggestionsCleared());
  provider()->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT,
                              RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN);
}

TEST_F(RemoteSuggestionsProviderImplTest,
       RestartsFetchWhenSignedInWhileFetching) {
      MakeSuggestionsProviderWithoutInitializationWithStrictScheduler();
  // Initiate the provider so that it is already READY.
  EXPECT_CALL(*scheduler(), OnProviderActivated());
  WaitForSuggestionsProviderInitialization();

  // Initiate the fetch.
  RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
      .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback))
      .RetiresOnSaturation();
  provider()->FetchSuggestions(
      /*interactive_request=*/false,
      RemoteSuggestionsProvider::FetchStatusCallback());

  // The scheduler should be notified of clearing the suggestions.
  EXPECT_CALL(*scheduler(), OnSuggestionsCleared());
  provider()->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT,
                              RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN);

  // Once we signal the first fetch to be finished (calling snippets_callback
  // below), a new fetch should get triggered.
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)).Times(1);
  std::move(snippets_callback)
      .Run(Status::Success(), std::vector<FetchedCategory>());
}

TEST_F(RemoteSuggestionsProviderImplTest,
       IgnoresResultsWhenHistoryClearedWhileFetching) {
      MakeSuggestionsProviderWithoutInitializationWithStrictScheduler();
  // Initiate the provider so that it is already READY.
  EXPECT_CALL(*scheduler(), OnProviderActivated());
  WaitForSuggestionsProviderInitialization();

  // Initiate the fetch.
  RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback =
      FetchSuggestionsAndGetResponseCallback(/*interactive_request=*/false);

  // The scheduler should be notified of clearing the history.
  EXPECT_CALL(*scheduler(), OnHistoryCleared());
  provider()->ClearHistory(GetDefaultCreationTime(), GetDefaultExpirationTime(),
                           base::RepeatingCallback<bool(const GURL& url)>());

  // Once the fetch finishes, the returned suggestions are ignored.
  FetchedCategoryBuilder category_builder;
  category_builder.SetCategory(articles_category());
  category_builder.AddSuggestionViaBuilder(
      RemoteSuggestionBuilder().AddId(base::StringPrintf("http://abc.com")));
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(category_builder.Build());
  std::move(snippets_callback)
      .Run(Status::Success(), std::move(fetched_categories));
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(0));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldExcludeKnownSuggestionsWithoutTruncatingWhenFetchingMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::set<std::string> known_ids;
  for (int i = 0; i < 200; ++i) {
    known_ids.insert(base::NumberToString(i));
  }

  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_suggestions_fetcher(),
              FetchSnippets(Field(&RequestParams::excluded_ids, known_ids), _));
  provider()->Fetch(
      articles_category(), known_ids,
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldExcludeDismissedSuggestionsWhenFetchingMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().AddId("http://abc.com/"))
          .Build());
  ASSERT_TRUE(fetched_categories[0].suggestions[0]->is_complete());

  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  provider()->DismissSuggestion(MakeArticleID("http://abc.com/"));

  std::set<std::string> expected_excluded_ids({"http://abc.com/"});
  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  EXPECT_CALL(
      *mock_suggestions_fetcher(),
      FetchSnippets(Field(&RequestParams::excluded_ids, expected_excluded_ids),
                    _));
  provider()->Fetch(
      articles_category(), std::set<std::string>(),
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldTruncateExcludedDismissedSuggestionsWhenFetchingMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  FetchedCategoryBuilder category_builder;
  category_builder.SetCategory(articles_category());
  const int kSuggestionsCount = kMaxExcludedDismissedIds + 1;
  for (int i = 0; i < kSuggestionsCount; ++i) {
    category_builder.AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId(
        base::StringPrintf("http://abc.com/%d/", i)));
  }
  fetched_categories.push_back(category_builder.Build());

  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  // Dismiss them.
  for (int i = 0; i < kSuggestionsCount; ++i) {
    provider()->DismissSuggestion(
        MakeArticleID(base::StringPrintf("http://abc.com/%d/", i)));
  }

  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_suggestions_fetcher(),
              FetchSnippets(Field(&RequestParams::excluded_ids,
                                  SizeIs(kMaxExcludedDismissedIds)),
                            _));
  provider()->Fetch(
      articles_category(), std::set<std::string>(),
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldPreferLatestExcludedDismissedSuggestionsWhenFetchingMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  FetchedCategoryBuilder category_builder;
  category_builder.SetCategory(articles_category());
  const int kSuggestionsCount = kMaxExcludedDismissedIds + 1;
  for (int i = 0; i < kSuggestionsCount; ++i) {
    category_builder.AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId(
        base::StringPrintf("http://abc.com/%d/", i)));
  }
  fetched_categories.push_back(category_builder.Build());

  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // Dismiss them in reverse order.
  std::string first_dismissed_suggestion_id;
  for (int i = kSuggestionsCount - 1; i >= 0; --i) {
    const std::string id = base::StringPrintf("http://abc.com/%d/", i);
    provider()->DismissSuggestion(MakeArticleID(id));
    if (first_dismissed_suggestion_id.empty()) {
      first_dismissed_suggestion_id = id;
    }
  }

  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  // The oldest dismissed suggestion should be absent, because there are
  // |kMaxExcludedDismissedIds| newer dismissed suggestions.
  EXPECT_CALL(*mock_suggestions_fetcher(),
              FetchSnippets(Field(&RequestParams::excluded_ids,
                                  Not(Contains(first_dismissed_suggestion_id))),
                            _));
  provider()->Fetch(
      articles_category(), std::set<std::string>(),
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldExcludeDismissedFetchedMoreSuggestions) {
  // This tests verifies that dismissing an article seen in the fetch-more state
  // (i.e., an article that has been fetched via fetch-more) will be excluded in
  // future fetches.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  FetchedCategoryBuilder category_builder;
  category_builder.SetCategory(articles_category());
  const int kSuggestionsCount = 5;
  for (int i = 0; i < kSuggestionsCount; ++i) {
    category_builder.AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId(
        base::StringPrintf("http://abc.com/%d", i)));
  }
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(category_builder.Build());

  FetchMoreTheseSuggestions(
      articles_category(),
      /*known_suggestion_ids=*/std::set<std::string>(),
      /*fetch_done_callback=*/
      base::BindOnce(
          [](Status status, std::vector<ContentSuggestion> suggestions) {
            ASSERT_THAT(suggestions, SizeIs(5));
          }),
      Status::Success(), std::move(fetched_categories));

  // Dismiss them.
  for (int i = 0; i < kSuggestionsCount; ++i) {
    provider()->DismissSuggestion(
        MakeArticleID(base::StringPrintf("http://abc.com/%d", i)));
  }

  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  EXPECT_CALL(
      *mock_suggestions_fetcher(),
      FetchSnippets(Field(&RequestParams::excluded_ids,
                          ElementsAre("http://abc.com/0", "http://abc.com/1",
                                      "http://abc.com/2", "http://abc.com/3",
                                      "http://abc.com/4")),
                    _));
  provider()->Fetch(
      articles_category(), std::set<std::string>(),
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));
}

TEST_F(RemoteSuggestionsProviderImplTest, ClearDismissedAfterFetchMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  FetchedCategoryBuilder category_builder;
  category_builder.SetCategory(articles_category());
  category_builder.AddSuggestionViaBuilder(
      RemoteSuggestionBuilder().AddId(base::StringPrintf("http://abc.com")));
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(category_builder.Build());

  FetchMoreTheseSuggestions(
      articles_category(),
      /*known_suggestion_ids=*/std::set<std::string>(),
      /*fetch_done_callback=*/
      base::BindOnce(
          [](Status status, std::vector<ContentSuggestion> suggestions) {}),
      Status::Success(), std::move(fetched_categories));

  provider()->DismissSuggestion(MakeArticleID("http://abc.com"));

  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillRepeatedly(Return(true));

  // Make sure the article got marked as dismissed.
  InSequence s;
  EXPECT_CALL(*mock_suggestions_fetcher(),
              FetchSnippets(Field(&RequestParams::excluded_ids,
                                  ElementsAre("http://abc.com")),
                            _));
  provider()->Fetch(
      articles_category(), std::set<std::string>(),
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));

  // Clear dismissals.
  provider()->ClearDismissedSuggestionsForDebugging(articles_category());

  // Fetch and verify the article is not marked as dismissed anymore.
  EXPECT_CALL(*mock_suggestions_fetcher(),
              FetchSnippets(Field(&RequestParams::excluded_ids, IsEmpty()), _));
  provider()->Fetch(
      articles_category(), std::set<std::string>(),
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldExcludeDismissedSuggestionsFromAllCategoriesWhenFetchingMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Add article suggestions.
  std::vector<FetchedCategory> fetched_categories;
  FetchedCategoryBuilder first_category_builder;
  first_category_builder.SetCategory(articles_category());
  const int kSuggestionsPerCategory = 2;
  for (int i = 0; i < kSuggestionsPerCategory; ++i) {
    first_category_builder.AddSuggestionViaBuilder(
        RemoteSuggestionBuilder().AddId(
            base::StringPrintf("http://abc.com/%d/", i)));
  }
  fetched_categories.push_back(first_category_builder.Build());
  // Add other category suggestions.
  FetchedCategoryBuilder second_category_builder;
  second_category_builder.SetCategory(
      Category::FromRemoteCategory(kOtherCategoryId));
  for (int i = 0; i < kSuggestionsPerCategory; ++i) {
    second_category_builder.AddSuggestionViaBuilder(
        RemoteSuggestionBuilder().AddId(
            base::StringPrintf("http://other.com/%d/", i)));
  }
  fetched_categories.push_back(second_category_builder.Build());

  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // Dismiss all suggestions.
  std::set<std::string> expected_excluded_ids;
  for (int i = 0; i < kSuggestionsPerCategory; ++i) {
    const std::string article_id = base::StringPrintf("http://abc.com/%d/", i);
    provider()->DismissSuggestion(MakeArticleID(article_id));
    expected_excluded_ids.insert(article_id);
    const std::string other_id = base::StringPrintf("http://other.com/%d/", i);
    provider()->DismissSuggestion(MakeOtherID(other_id));
    expected_excluded_ids.insert(other_id);
  }

  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  // Dismissed suggestions from all categories must be excluded (but not only
  // target category).
  EXPECT_CALL(
      *mock_suggestions_fetcher(),
      FetchSnippets(Field(&RequestParams::excluded_ids, expected_excluded_ids),
                    _));
  provider()->Fetch(
      articles_category(), std::set<std::string>(),
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldPreferTargetCategoryExcludedDismissedSuggestionsWhenFetchingMore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Add article suggestions.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(FetchedCategory(
      articles_category(),
      BuildRemoteCategoryInfo(base::UTF8ToUTF16("title"),
                              /*allow_fetching_more_results=*/true)));

  for (int i = 0; i < kMaxExcludedDismissedIds; ++i) {
    fetched_categories[0].suggestions.push_back(CreateTestRemoteSuggestion(
        base::StringPrintf("http://abc.com/%d/", i)));
  }
  // Add other category suggestion.
  fetched_categories.push_back(FetchedCategory(
      Category::FromRemoteCategory(kOtherCategoryId),
      BuildRemoteCategoryInfo(base::UTF8ToUTF16("title"),
                              /*allow_fetching_more_results=*/true)));
  fetched_categories[1].suggestions.push_back(
      CreateTestRemoteSuggestion("http://other.com/"));

  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // Dismiss article suggestions first.
  for (int i = 0; i < kMaxExcludedDismissedIds; ++i) {
    provider()->DismissSuggestion(
        MakeArticleID(base::StringPrintf("http://abc.com/%d/", i)));
  }

  // Then dismiss other category suggestion.
  provider()->DismissSuggestion(MakeOtherID("http://other.com/"));

  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  // The other category dismissed suggestion should be absent, because the fetch
  // is for articles and there are |kMaxExcludedDismissedIds| dismissed
  // suggestions there.
  EXPECT_CALL(*mock_suggestions_fetcher(),
              FetchSnippets(Field(&RequestParams::excluded_ids,
                                  Not(Contains("http://other.com/"))),
                            _));
  provider()->Fetch(
      articles_category(), std::set<std::string>(),
      base::BindOnce([](Status status_code,
                        std::vector<ContentSuggestion> suggestions) {}));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldRestoreSuggestionsFromDatabaseInSameOrderAsFetched) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .AddId("http://1.com")
                                       .SetUrl("http://1.com")
                                       .SetScore(1))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .AddId("http://3.com")
                                       .SetUrl("http://3.com")
                                       .SetScore(3))
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .AddId("http://2.com")
                                       .SetUrl("http://2.com")
                                       .SetScore(2))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  ASSERT_THAT(
      observer().SuggestionsForCategory(articles_category()),
      ElementsAre(
          Property(&ContentSuggestion::id, MakeArticleID("http://1.com")),
          Property(&ContentSuggestion::id, MakeArticleID("http://3.com")),
          Property(&ContentSuggestion::id, MakeArticleID("http://2.com"))));

  ResetSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  EXPECT_THAT(
      observer().SuggestionsForCategory(articles_category()),
      ElementsAre(
          Property(&ContentSuggestion::id, MakeArticleID("http://1.com")),
          Property(&ContentSuggestion::id, MakeArticleID("http://3.com")),
          Property(&ContentSuggestion::id, MakeArticleID("http://2.com"))));
}

// TODO(vitaliii): Remove this test (as well as the score fallback) in M64.
TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldSortSuggestionsWithoutRanksByScore) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Write suggestions without ranks (i.e. with default values) directly to
  // database to simulate behaviour of M61.
  std::vector<std::unique_ptr<RemoteSuggestion>> suggestions;
  suggestions.push_back(RemoteSuggestionBuilder()
                            .AddId("http://1.com")
                            .SetUrl("http://1.com")
                            .SetScore(1)
                            .SetRank(std::numeric_limits<int>::max())
                            .Build());
  suggestions.push_back(RemoteSuggestionBuilder()
                            .AddId("http://3.com")
                            .SetUrl("http://3.com")
                            .SetScore(3)
                            .SetRank(std::numeric_limits<int>::max())
                            .Build());
  suggestions.push_back(RemoteSuggestionBuilder()
                            .AddId("http://2.com")
                            .SetUrl("http://2.com")
                            .SetScore(2)
                            .SetRank(std::numeric_limits<int>::max())
                            .Build());

  database()->SaveSnippets(suggestions);

  ResetSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  EXPECT_THAT(
      observer().SuggestionsForCategory(articles_category()),
      ElementsAre(
          Property(&ContentSuggestion::id, MakeArticleID("http://3.com")),
          Property(&ContentSuggestion::id, MakeArticleID("http://2.com")),
          Property(&ContentSuggestion::id, MakeArticleID("http://1.com"))));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       FetchingShouldNotTriggerNotificationWhenDisabled) {
  SetTriggeringNotificationsAndSubscriptionParams(
      /*fetched_notifications_enabled=*/false,
      /*pushed_notifications_enabled=*/true,
      /*subscribe_signed_in=*/true,
      /*subscribe_signed_out=*/true);

  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Fetch a suggestion triggering a notification.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder()
                  .AddId("http://fetched.com/")
                  .SetUrl("http://fetched.com/")
                  .SetShouldNotify(true)
                  .SetNotificationDeadline(GetDefaultExpirationTime()))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // The fetched suggestion should not trigger a notification because such
  // notifications are disabled.
  EXPECT_THAT(
      observer().SuggestionsForCategory(articles_category()),
      ElementsAre(Property(&ContentSuggestion::notification_extra, nullptr)));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       FetchingShouldTriggerNotificationEvenIfPrependedNotificationsDisabled) {
  SetTriggeringNotificationsAndSubscriptionParams(
      /*fetched_notifications_enabled=*/true,
      /*pushed_notifications_enabled=*/false,
      /*subscribe_signed_in=*/true,
      /*subscribe_signed_out=*/true);

  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Fetch a suggestion triggering a notification.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder()
                  .AddId("http://fetched.com/")
                  .SetUrl("http://fetched.com/")
                  .SetShouldNotify(true)
                  .SetNotificationDeadline(GetDefaultExpirationTime()))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // The fetched suggestion should trigger a notification even though prepended
  // notifications are disabled.
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              ElementsAre(Property(&ContentSuggestion::notification_extra,
                                   Not(nullptr))));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldForceFetchedSuggestionsNotificationsWhenEnabled) {
  SetFetchedNotificationsParams(
      /*enabled=*/true, /*force=*/true);

  // Initialize the provider with two article suggestions - one with a
  // notification and one - without.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder()
                  .SetUrl("http://article_with_notification.com")
                  .SetShouldNotify(true)
                  .SetNotificationDeadline(GetDefaultExpirationTime()))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder()
                  .SetUrl("http://article_without_notification.com")
                  .SetShouldNotify(false))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // For the observer, both suggestions must have notifications, because they
  // are forced via a feature param.
  EXPECT_THAT(
      observer().SuggestionsForCategory(articles_category()),
      ElementsAre(
          Property(&ContentSuggestion::notification_extra, Not(nullptr)),
          Property(&ContentSuggestion::notification_extra, Not(nullptr))));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldNotForceFetchedSuggestionsNotificationsWhenExplicitlyDisabled) {
  SetFetchedNotificationsParams(
      /*enabled=*/false, /*force=*/true);

  // Initialize the provider with an article suggestions without a notification.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder()
                  .SetUrl("http://article_without_notification.com")
                  .SetShouldNotify(false))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // For the observer, the suggestion still must not have a notification (even
  // though they are forced via a feature param), because the fetched
  // notifications are explicitly disabled via another feature param.
  EXPECT_THAT(
      observer().SuggestionsForCategory(articles_category()),
      ElementsAre(Property(&ContentSuggestion::notification_extra, nullptr)));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldDeleteNotFetchedCategoryWhenDeletionEnabled) {
  // Initialize the provider with two categories.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  const FetchedCategoryBuilder articles_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://articles.com"));
  fetched_categories.push_back(articles_category_builder.Build());
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(kOtherCategoryId))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://not_articles.com"))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(
                Category::FromRemoteCategory(kOtherCategoryId)));

  // Fetch only one category - articles.
  fetched_categories.push_back(articles_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  // The other category must be gone, because it was not included in the last
  // fetch and the deletion is enabled via feature params.
  EXPECT_EQ(CategoryStatus::NOT_PROVIDED,
            observer().StatusForCategory(
                Category::FromRemoteCategory(kOtherCategoryId)));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldKeepFetchedCategoryWhenDeletionEnabled) {
  // Initialize the provider with two categories.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  const FetchedCategoryBuilder articles_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://articles.com"));
  fetched_categories.push_back(articles_category_builder.Build());
  const FetchedCategoryBuilder other_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(kOtherCategoryId))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://not_articles.com"));
  fetched_categories.push_back(other_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(
                Category::FromRemoteCategory(kOtherCategoryId)));

  // Fetch the same two categories again.
  fetched_categories.push_back(articles_category_builder.Build());
  fetched_categories.push_back(other_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  // The other category must remain, because it was included in the last fetch.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(
                Category::FromRemoteCategory(kOtherCategoryId)));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldKeepArticleCategoryEvenWhenNotFetchedAndDeletionEnabled) {
  // Initialize the provider with two categories.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://articles.com"))
          .Build());
  const FetchedCategoryBuilder other_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(Category::FromRemoteCategory(kOtherCategoryId))
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://not_articles.com"));
  fetched_categories.push_back(other_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));

  // Fetch only one other category.
  fetched_categories.push_back(other_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  // Articles category still must be provided (it is an exception) even though
  // it was not included in the last fetch and the deletion is enabled via
  // feature params.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       EmptySectionResponseShouldClearSection) {
  // Initialize the provider with two categories.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Set up state with present suggestions.
  // Unfortunately, we cannot create the fetched_categories inline, as some part
  // requires a copy of FetchedCategory which is not supported :-/.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .SetUrl("http://articles.com")
                                       .SetAmpUrl(""))
          .Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));

  // Next fetch returns an empty article section.
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder().SetCategory(articles_category()).Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  // Articles category still must be provided, but empty.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              IsEmpty());
}

TEST_F(RemoteSuggestionsProviderImplTest,
       FetchErrorShouldLeaveSuggestionsUnchangedEmptySection) {
  // Tests that we don't interpret the response value in error cases.
  // Note, that the contract of the callback guarantees that we always send
  // a null value in error cases. However, such a contract is brittle and the
  // code is not too clear on the receiving side.
  // TODO(tschumann): Establish and enforce a clear and robust error handling
  // contract.

  // Initialize the provider with two categories.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Set up state with present suggestions.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .SetUrl("http://articles.com")
                                       .SetAmpUrl(""))
          .Build());

  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));

  // Next fetch returns an error (with an empty section).
  fetched_categories.clear();
  fetched_categories.push_back(
      FetchedCategoryBuilder().SetCategory(articles_category()).Build());
  FetchTheseSuggestions(/*interactive_request=*/true,
                        Status(StatusCode::TEMPORARY_ERROR, "some error"),
                        std::move(fetched_categories));

  // Articles category should stay unchanged.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category())[0].url(),
              GURL("http://articles.com"));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       FetchErrorShouldLeaveSuggestionsUnchangedNullResponse) {
  // Initialize the provider with two categories.
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  // Set up state with present suggestions.
  std::vector<FetchedCategory> fetched_categories;
  fetched_categories.push_back(
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(RemoteSuggestionBuilder()
                                       .SetUrl("http://articles.com")
                                       .SetAmpUrl(""))
          .Build());

  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));

  // Next fetch returns an error (with an empty section).
  FetchTheseSuggestions(/*interactive_request=*/true,
                        Status(StatusCode::TEMPORARY_ERROR, "some error"),
                        base::nullopt);

  // Articles category should stay unchanged.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category())[0].url(),
              GURL("http://articles.com"));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldNotSetExclusiveCategoryWhenFetchingSuggestions) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  RequestParams params;
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
      .WillOnce(SaveArg<0>(&params));
  provider()->FetchSuggestions(
      /*interactive_request=*/true,
      RemoteSuggestionsProvider::FetchStatusCallback());

  EXPECT_FALSE(params.exclusive_category.has_value());
  EXPECT_EQ(params.count_to_fetch, 10);
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldSetExclusiveCategoryAndCountToFetchWhenFetchingMoreSuggestions) {
  SetFetchMoreSuggestionsCount(35);

  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  RequestParams params;
  EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
      .WillOnce(SaveArg<0>(&params));
  EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch())
      .WillOnce(Return(true))
      .RetiresOnSaturation();
  provider()->Fetch(
      articles_category(), /*known_suggestion_ids=*/std::set<std::string>(),
      /*fetch_done_callback=*/
      base::BindOnce(
          [](Status status_code,
             std::vector<ContentSuggestion> suggestions) -> void {}));

  ASSERT_TRUE(params.exclusive_category.has_value());
  EXPECT_EQ(*params.exclusive_category, articles_category());
  EXPECT_EQ(params.count_to_fetch, 35);
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldToggleStatusIfRefetchWhileDisplayingSucceeds) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  const FetchedCategoryBuilder articles_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://articles.com"));
  fetched_categories.push_back(articles_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));

  auto response_callback = RefetchWhileDisplayingAndGetResponseCallback();

  // The timeout does not fire earlier than it should.
  FastForwardBy(
      base::TimeDelta::FromSeconds(kTimeoutForRefetchWhileDisplayingSeconds) -
      base::TimeDelta::FromMilliseconds(1));

  // Before the results come, the status is AVAILABLE_LOADING.
  ASSERT_EQ(CategoryStatus::AVAILABLE_LOADING,
            observer().StatusForCategory(articles_category()));

  fetched_categories.push_back(articles_category_builder.Build());
  std::move(response_callback)
      .Run(Status::Success(), std::move(fetched_categories));
  fetched_categories.clear();
  // After the results come, the status is flipped back to AVAILABLE.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldToggleStatusIfRefetchWhileDisplayingFails) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  const FetchedCategoryBuilder articles_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://articles.com"));
  fetched_categories.push_back(articles_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));

  auto response_callback = RefetchWhileDisplayingAndGetResponseCallback();

  // Before the results come, the status is flipped to AVAILABLE_LOADING.
  ASSERT_EQ(CategoryStatus::AVAILABLE_LOADING,
            observer().StatusForCategory(articles_category()));

  // After the results come, the status is flipped back to AVAILABLE.
  std::move(response_callback)
      .Run(Status(StatusCode::TEMPORARY_ERROR, "some error"), base::nullopt);
  // The category is available with the previous suggestion.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldToggleStatusIfRefetchWhileDisplayingTimeouts) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  const FetchedCategoryBuilder articles_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://articles.com"));
  fetched_categories.push_back(articles_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));

  // No need to finish the fetch, we ignore the response callback.
  RefetchWhileDisplayingAndGetResponseCallback();

  FastForwardBy(
      base::TimeDelta::FromSeconds(kTimeoutForRefetchWhileDisplayingSeconds) -
      base::TimeDelta::FromMilliseconds(1));

  // Before the timeout, the status is flipped to AVAILABLE_LOADING.
  ASSERT_EQ(CategoryStatus::AVAILABLE_LOADING,
            observer().StatusForCategory(articles_category()));

  FastForwardBy(base::TimeDelta::FromMilliseconds(2));

  // After the timeout, the status is flipped back to AVAILABLE, with the
  // previous suggestion.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldHandleCategoryDisabledBeforeTimeout) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  const FetchedCategoryBuilder articles_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://articles.com"));
  fetched_categories.push_back(articles_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));

  // No need to finish the fetch, we ignore the response callback.
  RefetchWhileDisplayingAndGetResponseCallback();

  FastForwardBy(
      base::TimeDelta::FromSeconds(kTimeoutForRefetchWhileDisplayingSeconds) -
      base::TimeDelta::FromMilliseconds(1));

  // Before the timeout, the status is flipped to AVAILABLE_LOADING.
  ASSERT_EQ(CategoryStatus::AVAILABLE_LOADING,
            observer().StatusForCategory(articles_category()));

  // Disable the provider; this will put the category into the
  // CATEGORY_EXPLICITLY_DISABLED status.
  provider()->EnterState(RemoteSuggestionsProviderImpl::State::DISABLED);
  ASSERT_EQ(CategoryStatus::CATEGORY_EXPLICITLY_DISABLED,
            observer().StatusForCategory(articles_category()));

  // Trigger the timeout. The provider should gracefully handle(i.e. not crash
  // because of) the category being disabled in the interim.
  FastForwardBy(base::TimeDelta::FromMilliseconds(2));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldNotUpdateTimeoutIfRefetchWhileDisplayingCalledAgain) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);
  std::vector<FetchedCategory> fetched_categories;
  const FetchedCategoryBuilder articles_category_builder =
      FetchedCategoryBuilder()
          .SetCategory(articles_category())
          .AddSuggestionViaBuilder(
              RemoteSuggestionBuilder().SetUrl("http://articles.com"));
  fetched_categories.push_back(articles_category_builder.Build());
  FetchTheseSuggestions(/*interactive_request=*/true, Status::Success(),
                        std::move(fetched_categories));
  fetched_categories.clear();

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));

  // No need to finish the fetch, we ignore the response callback.
  RefetchWhileDisplayingAndGetResponseCallback();

  FastForwardBy(
      base::TimeDelta::FromSeconds(kTimeoutForRefetchWhileDisplayingSeconds) -
      base::TimeDelta::FromMilliseconds(1));

  // Another fetch does nothing to the deadline.
  RefetchWhileDisplayingAndGetResponseCallback();

  FastForwardBy(base::TimeDelta::FromMilliseconds(2));

  // After the timeout, the status is flipped back to AVAILABLE, with the
  // previous suggestion.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              SizeIs(1));
}

TEST_F(RemoteSuggestionsProviderImplTest,
       ShouldToggleStatusIfReloadSuggestionsFails) {
  MakeSuggestionsProvider(
      /*use_mock_remote_suggestions_status_service=*/false);

  ASSERT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));

  auto response_callback = ReloadSuggestionsAndGetResponseCallback();

  // Before the results come, the status is flipped to AVAILABLE_LOADING.
  ASSERT_EQ(CategoryStatus::AVAILABLE_LOADING,
            observer().StatusForCategory(articles_category()));

  // After the results come, the status is flipped back to AVAILABLE.
  std::move(response_callback)
      .Run(Status(StatusCode::TEMPORARY_ERROR, "some error"), base::nullopt);
  // The category is available, with no suggestions.
  EXPECT_EQ(CategoryStatus::AVAILABLE,
            observer().StatusForCategory(articles_category()));
  EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
              IsEmpty());
}

}  // namespace ntp_snippets