File: host_cache_unittest.cc

package info (click to toggle)
chromium 120.0.6099.224-1~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 6,112,112 kB
  • sloc: cpp: 32,907,025; ansic: 8,148,123; javascript: 3,679,536; python: 2,031,248; asm: 959,718; java: 804,675; xml: 617,256; sh: 111,417; objc: 100,835; perl: 88,443; cs: 53,032; makefile: 29,579; fortran: 24,137; php: 21,162; tcl: 21,147; sql: 20,809; ruby: 17,735; pascal: 12,864; yacc: 8,045; lisp: 3,388; lex: 1,323; ada: 727; awk: 329; jsp: 267; csh: 117; exp: 43; sed: 37
file content (2666 lines) | stat: -rw-r--r-- 102,675 bytes parent folder | download
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/dns/host_cache.h"

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

#include "base/format_macros.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/ranges/algorithm.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "base/values.h"
#include "net/base/connection_endpoint_metadata.h"
#include "net/base/host_port_pair.h"
#include "net/base/ip_address.h"
#include "net/base/ip_endpoint.h"
#include "net/base/network_anonymization_key.h"
#include "net/base/schemeful_site.h"
#include "net/dns/host_resolver_internal_result.h"
#include "net/dns/host_resolver_results_test_util.h"
#include "net/dns/https_record_rdata.h"
#include "net/dns/public/host_resolver_results.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/scheme_host_port.h"
#include "url/url_constants.h"

using ::testing::_;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::IsEmpty;
using ::testing::Optional;
using ::testing::Pair;
using ::testing::Pointee;
using ::testing::Property;
using ::testing::UnorderedElementsAre;

namespace net {

namespace {

const int kMaxCacheEntries = 10;

// Builds a key for |hostname|, defaulting the query type to unspecified.
HostCache::Key Key(const std::string& hostname) {
  return HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, hostname, 443),
                        DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                        NetworkAnonymizationKey());
}

bool FoobarIndexIsOdd(const std::string& foobarx_com) {
  return (foobarx_com[6] - '0') % 2 == 1;
}

class MockPersistenceDelegate : public HostCache::PersistenceDelegate {
 public:
  void ScheduleWrite() override { ++num_changes_; }

  int num_changes() const { return num_changes_; }

 private:
  int num_changes_ = 0;
};

MATCHER_P(EntryContentsEqual,
          entry,
          base::StrCat({"contents ", negation ? "!=" : "==", " contents of ",
                        testing::PrintToString(entry)})) {
  return arg.ContentsEqual(entry);
}

IPAddress MakeIP(base::StringPiece literal) {
  IPAddress ret;
  CHECK(ret.AssignFromIPLiteral(literal));
  return ret;
}

std::vector<IPEndPoint> MakeEndpoints(std::vector<std::string> my_addresses) {
  std::vector<IPEndPoint> out(my_addresses.size());
  base::ranges::transform(my_addresses, out.begin(),
                          [](auto& s) { return IPEndPoint(MakeIP(s), 0); });
  return out;
}

}  // namespace

TEST(HostCacheTest, Basic) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // Start at t=0.
  base::TimeTicks now;

  HostCache::Key key1 = Key("foobar.com");
  HostCache::Key key2 = Key("foobar2.com");
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{"foobar.com"},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0U, cache.size());

  // Add an entry for "foobar.com" at t=0.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key1, now)->second.error() == entry.error());

  EXPECT_EQ(1U, cache.size());

  // Advance to t=5.
  now += base::Seconds(5);

  // Add an entry for "foobar2.com" at t=5.
  EXPECT_FALSE(cache.Lookup(key2, now));
  cache.Set(key2, entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_EQ(2U, cache.size());

  // Advance to t=9
  now += base::Seconds(4);

  // Verify that the entries we added are still retrievable, and usable.
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_NE(cache.Lookup(key1, now), cache.Lookup(key2, now));

  // Advance to t=10; key is now expired.
  now += base::Seconds(1);

  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key2, now));

  // Update key1, so it is no longer expired.
  cache.Set(key1, entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(2U, cache.size());

  // Both entries should still be retrievable and usable.
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key2, now));

  // Advance to t=20; both entries are now expired.
  now += base::Seconds(10);

  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_FALSE(cache.Lookup(key2, now));
}

TEST(HostCacheTest, GetEndpoints) {
  std::vector<IPEndPoint> ip_endpoints = {IPEndPoint(IPAddress(1, 1, 1, 1), 0),
                                          IPEndPoint(IPAddress(2, 2, 2, 2), 0)};
  HostCache::Entry entry(OK, ip_endpoints, /*aliases=*/{},
                         HostCache::Entry::SOURCE_DNS);

  EXPECT_THAT(entry.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ip_endpoints)));
}

TEST(HostCacheTest, GetEmptyEndpoints) {
  HostCache::Entry entry(ERR_NAME_NOT_RESOLVED, /*ip_endpoints=*/{},
                         /*aliases=*/{}, HostCache::Entry::SOURCE_DNS);
  EXPECT_THAT(entry.GetEndpoints(), IsEmpty());
}

TEST(HostCacheTest, GetEmptyEndpointsWithMetadata) {
  HostCache::Entry entry(ERR_NAME_NOT_RESOLVED, /*ip_endpoints=*/{},
                         /*aliases=*/{}, HostCache::Entry::SOURCE_DNS);

  // Merge in non-empty metadata.
  ConnectionEndpointMetadata metadata;
  metadata.supported_protocol_alpns = {"h3", "h2"};
  HostCache::Entry metadata_entry(
      OK,
      std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>{
          {1u, metadata}},
      HostCache::Entry::SOURCE_DNS);

  auto merged_entry = HostCache::Entry::MergeEntries(entry, metadata_entry);

  // Result should still be empty.
  EXPECT_THAT(merged_entry.GetEndpoints(), IsEmpty());
}

TEST(HostCacheTest, GetMissingEndpoints) {
  HostCache::Entry entry(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS);
  EXPECT_THAT(entry.GetEndpoints(), IsEmpty());
}

TEST(HostCacheTest, GetMissingEndpointsWithMetadata) {
  HostCache::Entry entry(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS);

  // Merge in non-empty metadata.
  ConnectionEndpointMetadata metadata;
  metadata.supported_protocol_alpns = {"h3", "h2"};
  HostCache::Entry metadata_entry(
      OK,
      std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>{
          {1u, metadata}},
      HostCache::Entry::SOURCE_DNS);

  auto merged_entry = HostCache::Entry::MergeEntries(entry, metadata_entry);

  // Result should still be empty.
  EXPECT_THAT(merged_entry.GetEndpoints(), IsEmpty());
}

// Test that Keys without scheme are allowed and treated as completely different
// from similar Keys with scheme.
TEST(HostCacheTest, HandlesKeysWithoutScheme) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // t=0.
  base::TimeTicks now;

  HostCache::Key key("host1.test", DnsQueryType::UNSPECIFIED, 0,
                     HostResolverSource::ANY, NetworkAnonymizationKey());
  HostCache::Key key_with_scheme(
      url::SchemeHostPort(url::kHttpsScheme, "host1.test", 443),
      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
      NetworkAnonymizationKey());
  ASSERT_NE(key, key_with_scheme);
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  ASSERT_EQ(0U, cache.size());
  ASSERT_FALSE(cache.Lookup(key, now));
  ASSERT_FALSE(cache.Lookup(key_with_scheme, now));

  // Add entry for `key`.
  cache.Set(key, entry, now, kTTL);
  EXPECT_EQ(1U, cache.size());
  EXPECT_TRUE(cache.Lookup(key, now));
  EXPECT_FALSE(cache.Lookup(key_with_scheme, now));

  // Add entry for `key_with_scheme`.
  cache.Set(key_with_scheme, entry, now, kTTL);
  EXPECT_EQ(2U, cache.size());
  EXPECT_TRUE(cache.Lookup(key, now));
  EXPECT_TRUE(cache.Lookup(key_with_scheme, now));

  // Clear the cache and try adding in reverse order.
  cache.clear();
  ASSERT_EQ(0U, cache.size());
  ASSERT_FALSE(cache.Lookup(key, now));
  ASSERT_FALSE(cache.Lookup(key_with_scheme, now));

  // Add entry for `key_with_scheme`.
  cache.Set(key_with_scheme, entry, now, kTTL);
  EXPECT_EQ(1U, cache.size());
  EXPECT_FALSE(cache.Lookup(key, now));
  EXPECT_TRUE(cache.Lookup(key_with_scheme, now));

  // Add entry for `key`.
  cache.Set(key, entry, now, kTTL);
  EXPECT_EQ(2U, cache.size());
  EXPECT_TRUE(cache.Lookup(key, now));
  EXPECT_TRUE(cache.Lookup(key_with_scheme, now));
}

// Make sure NetworkAnonymizationKey is respected.
TEST(HostCacheTest, NetworkAnonymizationKey) {
  const url::SchemeHostPort kHost(url::kHttpsScheme, "hostname.test", 443);
  const base::TimeDelta kTTL = base::Seconds(10);

  const SchemefulSite kSite1(GURL("https://site1.test/"));
  const auto kNetworkAnonymizationKey1 =
      NetworkAnonymizationKey::CreateSameSite(kSite1);
  const SchemefulSite kSite2(GURL("https://site2.test/"));
  const auto kNetworkAnonymizationKey2 =
      NetworkAnonymizationKey::CreateSameSite(kSite2);

  HostCache::Key key1(kHost, DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, kNetworkAnonymizationKey1);
  HostCache::Key key2(kHost, DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, kNetworkAnonymizationKey2);
  HostCache::Entry entry1 =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);
  HostCache::Entry entry2 =
      HostCache::Entry(ERR_FAILED, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  HostCache cache(kMaxCacheEntries);

  // Start at t=0.
  base::TimeTicks now;

  EXPECT_EQ(0U, cache.size());

  // Add an entry for kNetworkAnonymizationKey1.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry1, now, kTTL);

  const std::pair<const HostCache::Key, HostCache::Entry>* result =
      cache.Lookup(key1, now);
  ASSERT_TRUE(result);
  EXPECT_EQ(kNetworkAnonymizationKey1, result->first.network_anonymization_key);
  EXPECT_EQ(OK, result->second.error());
  EXPECT_FALSE(cache.Lookup(key2, now));
  EXPECT_EQ(1U, cache.size());

  // Add a different entry for kNetworkAnonymizationKey2.
  cache.Set(key2, entry2, now, 3 * kTTL);
  result = cache.Lookup(key1, now);
  ASSERT_TRUE(result);
  EXPECT_EQ(kNetworkAnonymizationKey1, result->first.network_anonymization_key);
  EXPECT_EQ(OK, result->second.error());
  result = cache.Lookup(key2, now);
  ASSERT_TRUE(result);
  EXPECT_EQ(kNetworkAnonymizationKey2, result->first.network_anonymization_key);
  EXPECT_EQ(ERR_FAILED, result->second.error());
  EXPECT_EQ(2U, cache.size());

  // Advance time so that first entry times out. Second entry should remain.
  now += 2 * kTTL;
  EXPECT_FALSE(cache.Lookup(key1, now));
  result = cache.Lookup(key2, now);
  ASSERT_TRUE(result);
  EXPECT_EQ(kNetworkAnonymizationKey2, result->first.network_anonymization_key);
  EXPECT_EQ(ERR_FAILED, result->second.error());
}

// Try caching entries for a failed resolve attempt -- since we set the TTL of
// such entries to 0 it won't store, but it will kick out the previous result.
TEST(HostCacheTest, NoCacheZeroTTL) {
  const base::TimeDelta kSuccessEntryTTL = base::Seconds(10);
  const base::TimeDelta kFailureEntryTTL = base::Seconds(0);

  HostCache cache(kMaxCacheEntries);

  // Set t=0.
  base::TimeTicks now;

  HostCache::Key key1 = Key("foobar.com");
  HostCache::Key key2 = Key("foobar2.com");
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry, now, kFailureEntryTTL);
  EXPECT_EQ(1U, cache.size());

  // We disallow use of negative entries.
  EXPECT_FALSE(cache.Lookup(key1, now));

  // Now overwrite with a valid entry, and then overwrite with negative entry
  // again -- the valid entry should be kicked out.
  cache.Set(key1, entry, now, kSuccessEntryTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  cache.Set(key1, entry, now, kFailureEntryTTL);
  EXPECT_FALSE(cache.Lookup(key1, now));
}

// Try caching entries for a failed resolves for 10 seconds.
TEST(HostCacheTest, CacheNegativeEntry) {
  const base::TimeDelta kFailureEntryTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // Start at t=0.
  base::TimeTicks now;

  HostCache::Key key1 = Key("foobar.com");
  HostCache::Key key2 = Key("foobar2.com");
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0U, cache.size());

  // Add an entry for "foobar.com" at t=0.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry, now, kFailureEntryTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(1U, cache.size());

  // Advance to t=5.
  now += base::Seconds(5);

  // Add an entry for "foobar2.com" at t=5.
  EXPECT_FALSE(cache.Lookup(key2, now));
  cache.Set(key2, entry, now, kFailureEntryTTL);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_EQ(2U, cache.size());

  // Advance to t=9
  now += base::Seconds(4);

  // Verify that the entries we added are still retrievable, and usable.
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key2, now));

  // Advance to t=10; key1 is now expired.
  now += base::Seconds(1);

  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key2, now));

  // Update key1, so it is no longer expired.
  cache.Set(key1, entry, now, kFailureEntryTTL);
  // Re-uses existing entry storage.
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(2U, cache.size());

  // Both entries should still be retrievable and usable.
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key2, now));

  // Advance to t=20; both entries are now expired.
  now += base::Seconds(10);

  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_FALSE(cache.Lookup(key2, now));
}

// Tests that the same hostname can be duplicated in the cache, so long as
// the query type differs.
TEST(HostCacheTest, DnsQueryTypeIsPartOfKey) {
  const base::TimeDelta kSuccessEntryTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // t=0.
  base::TimeTicks now;

  HostCache::Key key1(url::SchemeHostPort(url::kHttpScheme, "foobar.com", 80),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey());
  HostCache::Key key2(url::SchemeHostPort(url::kHttpScheme, "foobar.com", 80),
                      DnsQueryType::A, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey());
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0U, cache.size());

  // Add an entry for ("foobar.com", UNSPECIFIED) at t=0.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry, now, kSuccessEntryTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(1U, cache.size());

  // Add an entry for ("foobar.com", IPV4_ONLY) at t=0.
  EXPECT_FALSE(cache.Lookup(key2, now));
  cache.Set(key2, entry, now, kSuccessEntryTTL);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_EQ(2U, cache.size());

  // Even though the hostnames were the same, we should have two unique
  // entries (because the address families differ).
  EXPECT_NE(cache.Lookup(key1, now), cache.Lookup(key2, now));
}

// Tests that the same hostname can be duplicated in the cache, so long as
// the HostResolverFlags differ.
TEST(HostCacheTest, HostResolverFlagsArePartOfKey) {
  const url::SchemeHostPort kHost(url::kHttpsScheme, "foobar.test", 443);
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // t=0.
  base::TimeTicks now;

  HostCache::Key key1(kHost, DnsQueryType::A, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey());
  HostCache::Key key2(kHost, DnsQueryType::A, HOST_RESOLVER_CANONNAME,
                      HostResolverSource::ANY, NetworkAnonymizationKey());
  HostCache::Key key3(kHost, DnsQueryType::A, HOST_RESOLVER_LOOPBACK_ONLY,
                      HostResolverSource::ANY, NetworkAnonymizationKey());
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0U, cache.size());

  // Add an entry for ("foobar.com", IPV4, NONE) at t=0.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(1U, cache.size());

  // Add an entry for ("foobar.com", IPV4, CANONNAME) at t=0.
  EXPECT_FALSE(cache.Lookup(key2, now));
  cache.Set(key2, entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_EQ(2U, cache.size());

  // Add an entry for ("foobar.com", IPV4, LOOPBACK_ONLY) at t=0.
  EXPECT_FALSE(cache.Lookup(key3, now));
  cache.Set(key3, entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key3, now));
  EXPECT_EQ(3U, cache.size());

  // Even though the hostnames were the same, we should have two unique
  // entries (because the HostResolverFlags differ).
  EXPECT_NE(cache.Lookup(key1, now), cache.Lookup(key2, now));
  EXPECT_NE(cache.Lookup(key1, now), cache.Lookup(key3, now));
  EXPECT_NE(cache.Lookup(key2, now), cache.Lookup(key3, now));
}

// Tests that the same hostname can be duplicated in the cache, so long as
// the HostResolverSource differs.
TEST(HostCacheTest, HostResolverSourceIsPartOfKey) {
  const url::SchemeHostPort kHost(url::kHttpsScheme, "foobar.test", 443);
  const base::TimeDelta kSuccessEntryTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // t=0.
  base::TimeTicks now;

  HostCache::Key key1(kHost, DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, NetworkAnonymizationKey());
  HostCache::Key key2(kHost, DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::DNS, NetworkAnonymizationKey());
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0U, cache.size());

  // Add an entry for ("foobar.com", UNSPECIFIED, ANY) at t=0.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry, now, kSuccessEntryTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(1U, cache.size());

  // Add an entry for ("foobar.com", UNSPECIFIED, DNS) at t=0.
  EXPECT_FALSE(cache.Lookup(key2, now));
  cache.Set(key2, entry, now, kSuccessEntryTTL);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_EQ(2U, cache.size());

  // Even though the hostnames were the same, we should have two unique
  // entries (because the HostResolverSource differs).
  EXPECT_NE(cache.Lookup(key1, now), cache.Lookup(key2, now));
}

// Tests that the same hostname can be duplicated in the cache, so long as
// the secure field in the key differs.
TEST(HostCacheTest, SecureIsPartOfKey) {
  const url::SchemeHostPort kHost(url::kHttpsScheme, "foobar.test", 443);
  const base::TimeDelta kSuccessEntryTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // t=0.
  base::TimeTicks now;
  HostCache::EntryStaleness stale;

  HostCache::Key key1(kHost, DnsQueryType::A, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey());
  key1.secure = true;
  HostCache::Key key2(kHost, DnsQueryType::A, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey());
  key2.secure = false;
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0U, cache.size());

  // Add an entry for ("foobar.com", IPV4, true /* secure */) at t=0.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry, now, kSuccessEntryTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(1U, cache.size());

  // Lookup a key that is identical to the inserted key except for the secure
  // field.
  EXPECT_FALSE(cache.Lookup(key2, now));
  EXPECT_FALSE(cache.LookupStale(key2, now, &stale));
  const std::pair<const HostCache::Key, HostCache::Entry>* result;
  result = cache.Lookup(key2, now, true /* ignore_secure */);
  EXPECT_TRUE(result);
  EXPECT_TRUE(result->first.secure);
  result = cache.LookupStale(key2, now, &stale, true /* ignore_secure */);
  EXPECT_TRUE(result);
  EXPECT_TRUE(result->first.secure);

  // Add an entry for ("foobar.com", IPV4, false */ secure */) at t=0.
  cache.Set(key2, entry, now, kSuccessEntryTTL);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_TRUE(cache.LookupStale(key2, now, &stale));
  EXPECT_EQ(2U, cache.size());
}

TEST(HostCacheTest, PreferLessStaleMoreSecure) {
  const url::SchemeHostPort kHost(url::kHttpsScheme, "foobar.test", 443);
  const base::TimeDelta kSuccessEntryTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // t=0.
  base::TimeTicks now;
  HostCache::EntryStaleness stale;

  HostCache::Key insecure_key(kHost, DnsQueryType::A, 0,
                              HostResolverSource::ANY,
                              NetworkAnonymizationKey());
  HostCache::Key secure_key(kHost, DnsQueryType::A, 0, HostResolverSource::ANY,
                            NetworkAnonymizationKey());
  secure_key.secure = true;
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0U, cache.size());

  // Add both insecure and secure entries.
  cache.Set(insecure_key, entry, now, kSuccessEntryTTL);
  cache.Set(secure_key, entry, now, kSuccessEntryTTL);
  EXPECT_EQ(insecure_key, cache.Lookup(insecure_key, now)->first);
  EXPECT_EQ(secure_key, cache.Lookup(secure_key, now)->first);
  // Secure key is preferred when equally stale.
  EXPECT_EQ(secure_key,
            cache.Lookup(insecure_key, now, true /* ignore_secure */)->first);
  EXPECT_EQ(secure_key,
            cache.Lookup(insecure_key, now, true /* ignore_secure */)->first);

  // Simulate network change.
  cache.Invalidate();

  // Re-add insecure entry.
  cache.Set(insecure_key, entry, now, kSuccessEntryTTL);
  EXPECT_EQ(insecure_key, cache.Lookup(insecure_key, now)->first);
  EXPECT_FALSE(cache.Lookup(secure_key, now));
  EXPECT_EQ(secure_key, cache.LookupStale(secure_key, now, &stale)->first);
  // Result with fewer network changes is preferred.
  EXPECT_EQ(
      insecure_key,
      cache.LookupStale(secure_key, now, &stale, true /* ignore-secure */)
          ->first);

  // Add both insecure and secure entries to a cleared cache, still at t=0.
  cache.clear();
  cache.Set(insecure_key, entry, now, base::Seconds(20));
  cache.Set(secure_key, entry, now, kSuccessEntryTTL);

  // Advance to t=15 to expire the secure entry only.
  now += base::Seconds(15);
  EXPECT_EQ(insecure_key, cache.Lookup(insecure_key, now)->first);
  EXPECT_FALSE(cache.Lookup(secure_key, now));
  EXPECT_EQ(secure_key, cache.LookupStale(secure_key, now, &stale)->first);
  // Non-expired result is preferred.
  EXPECT_EQ(
      insecure_key,
      cache.LookupStale(secure_key, now, &stale, true /* ignore-secure */)
          ->first);
}

TEST(HostCacheTest, NoCache) {
  const base::TimeDelta kTTL = base::Seconds(10);

  // Disable caching.
  HostCache cache(0);
  EXPECT_TRUE(cache.caching_is_disabled());

  // Set t=0.
  base::TimeTicks now;

  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  // Lookup and Set should have no effect.
  EXPECT_FALSE(cache.Lookup(Key("foobar.com"), now));
  cache.Set(Key("foobar.com"), entry, now, kTTL);
  EXPECT_FALSE(cache.Lookup(Key("foobar.com"), now));

  EXPECT_EQ(0U, cache.size());
}

TEST(HostCacheTest, Clear) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // Set t=0.
  base::TimeTicks now;

  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0u, cache.size());

  // Add three entries.
  cache.Set(Key("foobar1.com"), entry, now, kTTL);
  cache.Set(Key("foobar2.com"), entry, now, kTTL);
  cache.Set(Key("foobar3.com"), entry, now, kTTL);

  EXPECT_EQ(3u, cache.size());

  cache.clear();

  EXPECT_EQ(0u, cache.size());
}

TEST(HostCacheTest, ClearForHosts) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // Set t=0.
  base::TimeTicks now;

  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0u, cache.size());

  // Add several entries.
  cache.Set(Key("foobar1.com"), entry, now, kTTL);
  cache.Set(Key("foobar2.com"), entry, now, kTTL);
  cache.Set(Key("foobar3.com"), entry, now, kTTL);
  cache.Set(Key("foobar4.com"), entry, now, kTTL);
  cache.Set(Key("foobar5.com"), entry, now, kTTL);

  EXPECT_EQ(5u, cache.size());

  // Clear the hosts matching a certain predicate, such as the number being odd.
  cache.ClearForHosts(base::BindRepeating(&FoobarIndexIsOdd));

  EXPECT_EQ(2u, cache.size());
  EXPECT_TRUE(cache.Lookup(Key("foobar2.com"), now));
  EXPECT_TRUE(cache.Lookup(Key("foobar4.com"), now));

  // Passing null callback will delete all hosts.
  cache.ClearForHosts(base::NullCallback());

  EXPECT_EQ(0u, cache.size());
}

// Try to add too many entries to cache; it should evict the one with the oldest
// expiration time.
TEST(HostCacheTest, Evict) {
  HostCache cache(2);

  base::TimeTicks now;

  HostCache::Key key1 = Key("foobar.com");
  HostCache::Key key2 = Key("foobar2.com");
  HostCache::Key key3 = Key("foobar3.com");
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0u, cache.size());
  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_FALSE(cache.Lookup(key2, now));
  EXPECT_FALSE(cache.Lookup(key3, now));

  // |key1| expires in 10 seconds, but |key2| in just 5.
  cache.Set(key1, entry, now, base::Seconds(10));
  cache.Set(key2, entry, now, base::Seconds(5));
  EXPECT_EQ(2u, cache.size());
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_FALSE(cache.Lookup(key3, now));

  // |key2| should be chosen for eviction, since it expires sooner.
  cache.Set(key3, entry, now, base::Seconds(10));
  EXPECT_EQ(2u, cache.size());
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_FALSE(cache.Lookup(key2, now));
  EXPECT_TRUE(cache.Lookup(key3, now));
}

// Try to retrieve stale entries from the cache. They should be returned by
// |LookupStale()| but not |Lookup()|, with correct |EntryStaleness| data.
TEST(HostCacheTest, Stale) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // Start at t=0.
  base::TimeTicks now;
  HostCache::EntryStaleness stale;

  HostCache::Key key = Key("foobar.com");
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0U, cache.size());

  // Add an entry for "foobar.com" at t=0.
  EXPECT_FALSE(cache.Lookup(key, now));
  EXPECT_FALSE(cache.LookupStale(key, now, &stale));
  cache.Set(key, entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key, now));
  EXPECT_TRUE(cache.LookupStale(key, now, &stale));
  EXPECT_FALSE(stale.is_stale());
  EXPECT_EQ(0, stale.stale_hits);

  EXPECT_EQ(1U, cache.size());

  // Advance to t=5.
  now += base::Seconds(5);

  EXPECT_TRUE(cache.Lookup(key, now));
  EXPECT_TRUE(cache.LookupStale(key, now, &stale));
  EXPECT_FALSE(stale.is_stale());
  EXPECT_EQ(0, stale.stale_hits);

  // Advance to t=15.
  now += base::Seconds(10);

  EXPECT_FALSE(cache.Lookup(key, now));
  EXPECT_TRUE(cache.LookupStale(key, now, &stale));
  EXPECT_TRUE(stale.is_stale());
  EXPECT_EQ(base::Seconds(5), stale.expired_by);
  EXPECT_EQ(0, stale.network_changes);
  EXPECT_EQ(1, stale.stale_hits);

  // Advance to t=20.
  now += base::Seconds(5);

  EXPECT_FALSE(cache.Lookup(key, now));
  EXPECT_TRUE(cache.LookupStale(key, now, &stale));
  EXPECT_TRUE(stale.is_stale());
  EXPECT_EQ(base::Seconds(10), stale.expired_by);
  EXPECT_EQ(0, stale.network_changes);
  EXPECT_EQ(2, stale.stale_hits);

  // Simulate network change.
  cache.Invalidate();

  EXPECT_FALSE(cache.Lookup(key, now));
  EXPECT_TRUE(cache.LookupStale(key, now, &stale));
  EXPECT_TRUE(stale.is_stale());
  EXPECT_EQ(base::Seconds(10), stale.expired_by);
  EXPECT_EQ(1, stale.network_changes);
  EXPECT_EQ(3, stale.stale_hits);
}

TEST(HostCacheTest, EvictStale) {
  HostCache cache(2);

  base::TimeTicks now;
  HostCache::EntryStaleness stale;

  HostCache::Key key1 = Key("foobar.com");
  HostCache::Key key2 = Key("foobar2.com");
  HostCache::Key key3 = Key("foobar3.com");
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0u, cache.size());
  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_FALSE(cache.Lookup(key2, now));
  EXPECT_FALSE(cache.Lookup(key3, now));

  // |key1| expires in 10 seconds.
  cache.Set(key1, entry, now, base::Seconds(10));
  EXPECT_EQ(1u, cache.size());
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_FALSE(cache.Lookup(key2, now));
  EXPECT_FALSE(cache.Lookup(key3, now));

  // Simulate network change, expiring the cache.
  cache.Invalidate();

  EXPECT_EQ(1u, cache.size());
  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.LookupStale(key1, now, &stale));
  EXPECT_EQ(1, stale.network_changes);

  // Advance to t=1.
  now += base::Seconds(1);

  // |key2| expires before |key1| would originally have expired.
  cache.Set(key2, entry, now, base::Seconds(5));
  EXPECT_EQ(2u, cache.size());
  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.LookupStale(key1, now, &stale));
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_FALSE(cache.Lookup(key3, now));

  // |key1| should be chosen for eviction, since it is stale.
  cache.Set(key3, entry, now, base::Seconds(1));
  EXPECT_EQ(2u, cache.size());
  EXPECT_FALSE(cache.Lookup(key1, now));
  EXPECT_FALSE(cache.LookupStale(key1, now, &stale));
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_TRUE(cache.Lookup(key3, now));

  // Advance to t=6.
  now += base::Seconds(5);

  // Insert |key1| again. |key3| should be evicted.
  cache.Set(key1, entry, now, base::Seconds(10));
  EXPECT_EQ(2u, cache.size());
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_FALSE(cache.Lookup(key2, now));
  EXPECT_TRUE(cache.LookupStale(key2, now, &stale));
  EXPECT_FALSE(cache.Lookup(key3, now));
  EXPECT_FALSE(cache.LookupStale(key3, now, &stale));
}

// Pinned entries should not be evicted, even if the cache is full and the Entry
// has expired.
TEST(HostCacheTest, NoEvictPinned) {
  HostCache cache(2);

  base::TimeTicks now;

  HostCache::Key key1 = Key("foobar.com");
  HostCache::Key key2 = Key("foobar2.com");
  HostCache::Key key3 = Key("foobar3.com");
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);
  entry.set_pinning(true);

  cache.Set(key1, entry, now, base::Seconds(5));
  now += base::Seconds(10);
  cache.Set(key2, entry, now, base::Seconds(5));
  now += base::Seconds(10);
  cache.Set(key3, entry, now, base::Seconds(5));

  // There are 3 entries in this cache whose nominal max size is 2.
  EXPECT_EQ(3u, cache.size());
  EXPECT_TRUE(cache.LookupStale(key1, now, nullptr));
  EXPECT_TRUE(cache.LookupStale(key2, now, nullptr));
  EXPECT_TRUE(cache.Lookup(key3, now));
}

// Obsolete pinned entries should be evicted normally.
TEST(HostCacheTest, EvictObsoletePinned) {
  HostCache cache(2);

  base::TimeTicks now;

  HostCache::Key key1 = Key("foobar.com");
  HostCache::Key key2 = Key("foobar2.com");
  HostCache::Key key3 = Key("foobar3.com");
  HostCache::Key key4 = Key("foobar4.com");
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);
  entry.set_pinning(true);

  // |key2| should be preserved, since it expires later.
  cache.Set(key1, entry, now, base::Seconds(5));
  cache.Set(key2, entry, now, base::Seconds(10));
  cache.Set(key3, entry, now, base::Seconds(5));
  // There are 3 entries in this cache whose nominal max size is 2.
  EXPECT_EQ(3u, cache.size());

  cache.Invalidate();
  // |Invalidate()| does not trigger eviction.
  EXPECT_EQ(3u, cache.size());

  // |Set()| triggers an eviction, leaving only |key2| in cache,
  // before adding |key4|
  cache.Set(key4, entry, now, base::Seconds(2));
  EXPECT_EQ(2u, cache.size());
  EXPECT_FALSE(cache.LookupStale(key1, now, nullptr));
  EXPECT_TRUE(cache.LookupStale(key2, now, nullptr));
  EXPECT_FALSE(cache.LookupStale(key3, now, nullptr));
  EXPECT_TRUE(cache.LookupStale(key4, now, nullptr));
}

// An active pin is preserved if the record is
// replaced due to a Set() call without the pin.
TEST(HostCacheTest, PreserveActivePin) {
  HostCache cache(2);

  base::TimeTicks now;

  // Make entry1 and entry2, identical except for IP and pinned flag.
  IPEndPoint endpoint1(IPAddress(192, 0, 2, 1), 0);
  IPEndPoint endpoint2(IPAddress(192, 0, 2, 2), 0);
  HostCache::Entry entry1 = HostCache::Entry(OK, {endpoint1}, /*aliases=*/{},
                                             HostCache::Entry::SOURCE_UNKNOWN);
  HostCache::Entry entry2 = HostCache::Entry(OK, {endpoint2}, /*aliases=*/{},
                                             HostCache::Entry::SOURCE_UNKNOWN);
  entry1.set_pinning(true);

  HostCache::Key key = Key("foobar.com");

  // Insert entry1, and verify that it can be retrieved with the
  // correct IP and |pinning()| == true.
  cache.Set(key, entry1, now, base::Seconds(10));
  const auto* pair1 = cache.Lookup(key, now);
  ASSERT_TRUE(pair1);
  const HostCache::Entry& result1 = pair1->second;
  EXPECT_THAT(result1.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ElementsAre(endpoint1))));
  EXPECT_THAT(result1.pinning(), Optional(true));

  // Insert |entry2|, and verify that it when it is retrieved, it
  // has the new IP, and the "pinned" flag copied from |entry1|.
  cache.Set(key, entry2, now, base::Seconds(10));
  const auto* pair2 = cache.Lookup(key, now);
  ASSERT_TRUE(pair2);
  const HostCache::Entry& result2 = pair2->second;
  EXPECT_THAT(result2.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ElementsAre(endpoint2))));
  EXPECT_THAT(result2.pinning(), Optional(true));
}

// An obsolete cache pin is not preserved if the record is replaced.
TEST(HostCacheTest, DontPreserveObsoletePin) {
  HostCache cache(2);

  base::TimeTicks now;

  // Make entry1 and entry2, identical except for IP and "pinned" flag.
  IPEndPoint endpoint1(IPAddress(192, 0, 2, 1), 0);
  IPEndPoint endpoint2(IPAddress(192, 0, 2, 2), 0);
  HostCache::Entry entry1 = HostCache::Entry(OK, {endpoint1}, /*aliases=*/{},
                                             HostCache::Entry::SOURCE_UNKNOWN);
  HostCache::Entry entry2 = HostCache::Entry(OK, {endpoint2}, /*aliases=*/{},
                                             HostCache::Entry::SOURCE_UNKNOWN);
  entry1.set_pinning(true);

  HostCache::Key key = Key("foobar.com");

  // Insert entry1, and verify that it can be retrieved with the
  // correct IP and |pinning()| == true.
  cache.Set(key, entry1, now, base::Seconds(10));
  const auto* pair1 = cache.Lookup(key, now);
  ASSERT_TRUE(pair1);
  const HostCache::Entry& result1 = pair1->second;
  EXPECT_THAT(result1.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ElementsAre(endpoint1))));
  EXPECT_THAT(result1.pinning(), Optional(true));

  // Make entry1 obsolete.
  cache.Invalidate();

  // Insert |entry2|, and verify that it when it is retrieved, it
  // has the new IP, and the "pinned" flag is not copied from |entry1|.
  cache.Set(key, entry2, now, base::Seconds(10));
  const auto* pair2 = cache.Lookup(key, now);
  ASSERT_TRUE(pair2);
  const HostCache::Entry& result2 = pair2->second;
  EXPECT_THAT(result2.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ElementsAre(endpoint2))));
  EXPECT_THAT(result2.pinning(), Optional(false));
}

// An active pin is removed if the record is replaced by a Set() call
// with the pin flag set to false.
TEST(HostCacheTest, Unpin) {
  HostCache cache(2);

  base::TimeTicks now;

  // Make entry1 and entry2, identical except for IP and pinned flag.
  IPEndPoint endpoint1(IPAddress(192, 0, 2, 1), 0);
  IPEndPoint endpoint2(IPAddress(192, 0, 2, 2), 0);
  HostCache::Entry entry1 = HostCache::Entry(OK, {endpoint1}, /*aliases=*/{},
                                             HostCache::Entry::SOURCE_UNKNOWN);
  HostCache::Entry entry2 = HostCache::Entry(OK, {endpoint2}, /*aliases=*/{},
                                             HostCache::Entry::SOURCE_UNKNOWN);
  entry1.set_pinning(true);
  entry2.set_pinning(false);

  HostCache::Key key = Key("foobar.com");

  // Insert entry1, and verify that it can be retrieved with the
  // correct IP and |pinning()| == true.
  cache.Set(key, entry1, now, base::Seconds(10));
  const auto* pair1 = cache.Lookup(key, now);
  ASSERT_TRUE(pair1);
  const HostCache::Entry& result1 = pair1->second;
  EXPECT_THAT(result1.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ElementsAre(endpoint1))));
  EXPECT_THAT(result1.pinning(), Optional(true));

  // Insert |entry2|, and verify that it when it is retrieved, it
  // has the new IP, and the "pinned" flag is now false.
  cache.Set(key, entry2, now, base::Seconds(10));
  const auto* pair2 = cache.Lookup(key, now);
  ASSERT_TRUE(pair2);
  const HostCache::Entry& result2 = pair2->second;
  EXPECT_THAT(result2.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ElementsAre(endpoint2))));
  EXPECT_THAT(result2.pinning(), Optional(false));
}

// Tests the less than and equal operators for HostCache::Key work.
TEST(HostCacheTest, KeyComparators) {
  struct CacheTestParameters {
    CacheTestParameters(const HostCache::Key key1,
                        const HostCache::Key key2,
                        int expected_comparison)
        : key1(key1), key2(key2), expected_comparison(expected_comparison) {}

    // Inputs.
    HostCache::Key key1;
    HostCache::Key key2;

    // Expectation.
    //   -1 means key1 is less than key2
    //    0 means key1 equals key2
    //    1 means key1 is greater than key2
    int expected_comparison;
  };
  std::vector<CacheTestParameters> tests = {
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       0},
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::A, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       1},
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::A, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       -1},
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host2", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       -1},
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::A, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host2", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       1},
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host2", 443),
                      DnsQueryType::A, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       -1},
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, HOST_RESOLVER_CANONNAME,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       -1},
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, HOST_RESOLVER_CANONNAME,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       1},
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, HOST_RESOLVER_CANONNAME,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host2", 443),
                      DnsQueryType::UNSPECIFIED, HOST_RESOLVER_CANONNAME,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       -1},
      // 9: Different host scheme.
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       1},
      // 10: Different host port.
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 1544),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       -1},
      // 11: Same host name without scheme/port.
      {HostCache::Key("host1", DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       HostCache::Key("host1", DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       0},
      // 12: Different host name without scheme/port.
      {HostCache::Key("host1", DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       HostCache::Key("host2", DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       -1},
      // 13: Only one with scheme/port.
      {HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                      DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                      NetworkAnonymizationKey()),
       HostCache::Key("host1", DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, NetworkAnonymizationKey()),
       -1},
  };
  HostCache::Key insecure_key =
      HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                     DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                     NetworkAnonymizationKey());
  HostCache::Key secure_key =
      HostCache::Key(url::SchemeHostPort(url::kHttpsScheme, "host1", 443),
                     DnsQueryType::UNSPECIFIED, 0, HostResolverSource::ANY,
                     NetworkAnonymizationKey());
  secure_key.secure = true;
  tests.emplace_back(insecure_key, secure_key, -1);

  for (size_t i = 0; i < std::size(tests); ++i) {
    SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));

    const HostCache::Key& key1 = tests[i].key1;
    const HostCache::Key& key2 = tests[i].key2;

    switch (tests[i].expected_comparison) {
      case -1:
        EXPECT_TRUE(key1 < key2);
        EXPECT_FALSE(key2 < key1);
        break;
      case 0:
        EXPECT_FALSE(key1 < key2);
        EXPECT_FALSE(key2 < key1);
        break;
      case 1:
        EXPECT_FALSE(key1 < key2);
        EXPECT_TRUE(key2 < key1);
        break;
      default:
        FAIL() << "Invalid expectation. Can be only -1, 0, 1";
    }
  }
}

TEST(HostCacheTest, SerializeAndDeserializeWithExpirations) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // Start at t=0.
  base::TimeTicks now;

  HostCache::Key expire_by_time_key = Key("expire.by.time.test");
  HostCache::Key expire_by_changes_key = Key("expire.by.changes.test");

  IPEndPoint endpoint(IPAddress(1, 2, 3, 4), 0);
  HostCache::Entry entry = HostCache::Entry(OK, {endpoint}, /*aliases=*/{},
                                            HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0u, cache.size());

  // Add an entry for `expire_by_time_key` at t=0.
  EXPECT_FALSE(cache.Lookup(expire_by_time_key, now));
  cache.Set(expire_by_time_key, entry, now, kTTL);
  EXPECT_THAT(cache.Lookup(expire_by_time_key, now),
              Pointee(Pair(expire_by_time_key, EntryContentsEqual(entry))));

  EXPECT_EQ(1u, cache.size());

  // Advance to t=5.
  now += base::Seconds(5);

  // Add entry for `expire_by_changes_key` at t=5.
  EXPECT_FALSE(cache.Lookup(expire_by_changes_key, now));
  cache.Set(expire_by_changes_key, entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(expire_by_changes_key, now));
  EXPECT_EQ(2u, cache.size());

  EXPECT_EQ(0u, cache.last_restore_size());

  // Advance to t=12, and serialize/deserialize the cache.
  now += base::Seconds(7);

  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, false /* include_staleness */,
                HostCache::SerializationType::kRestorable);
  HostCache restored_cache(kMaxCacheEntries);

  EXPECT_TRUE(restored_cache.RestoreFromListValue(serialized_cache));

  HostCache::EntryStaleness stale;

  // The `expire_by_time_key` entry is stale due to both network changes and
  // expiration time.
  EXPECT_FALSE(restored_cache.Lookup(expire_by_time_key, now));
  EXPECT_THAT(restored_cache.LookupStale(expire_by_time_key, now, &stale),
              Pointee(Pair(expire_by_time_key, EntryContentsEqual(entry))));
  EXPECT_EQ(1, stale.network_changes);
  // Time to TimeTicks conversion is fuzzy, so just check that expected and
  // actual expiration times are close.
  EXPECT_GT(base::Milliseconds(100),
            (base::Seconds(2) - stale.expired_by).magnitude());

  // The `expire_by_changes_key` entry is stale only due to network changes.
  EXPECT_FALSE(restored_cache.Lookup(expire_by_changes_key, now));
  EXPECT_THAT(restored_cache.LookupStale(expire_by_changes_key, now, &stale),
              Pointee(Pair(expire_by_changes_key, EntryContentsEqual(entry))));
  EXPECT_EQ(1, stale.network_changes);
  EXPECT_GT(base::Milliseconds(100),
            (base::Seconds(-3) - stale.expired_by).magnitude());

  EXPECT_EQ(2u, restored_cache.last_restore_size());
}

// Test that any changes between serialization and restore are preferred over
// old restored entries.
TEST(HostCacheTest, SerializeAndDeserializeWithChanges) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // Start at t=0.
  base::TimeTicks now;

  HostCache::Key to_serialize_key1 = Key("to.serialize1.test");
  HostCache::Key to_serialize_key2 = Key("to.serialize2.test");
  HostCache::Key other_key = Key("other.test");

  IPEndPoint endpoint(IPAddress(1, 1, 1, 1), 0);
  HostCache::Entry serialized_entry = HostCache::Entry(
      OK, {endpoint}, /*aliases=*/{}, HostCache::Entry::SOURCE_UNKNOWN);

  IPEndPoint replacement_endpoint(IPAddress(2, 2, 2, 2), 0);
  HostCache::Entry replacement_entry =
      HostCache::Entry(OK, {replacement_endpoint}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);

  IPEndPoint other_endpoint(IPAddress(3, 3, 3, 3), 0);
  HostCache::Entry other_entry = HostCache::Entry(
      OK, {other_endpoint}, /*aliases=*/{}, HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0u, cache.size());

  // Add `to_serialize_key1` and `to_serialize_key2`
  EXPECT_FALSE(cache.Lookup(to_serialize_key1, now));
  cache.Set(to_serialize_key1, serialized_entry, now, kTTL);
  EXPECT_THAT(
      cache.Lookup(to_serialize_key1, now),
      Pointee(Pair(to_serialize_key1, EntryContentsEqual(serialized_entry))));
  EXPECT_FALSE(cache.Lookup(to_serialize_key2, now));
  cache.Set(to_serialize_key2, serialized_entry, now, kTTL);
  EXPECT_THAT(
      cache.Lookup(to_serialize_key2, now),
      Pointee(Pair(to_serialize_key2, EntryContentsEqual(serialized_entry))));
  EXPECT_EQ(2u, cache.size());

  // Serialize the cache.
  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, false /* include_staleness */,
                HostCache::SerializationType::kRestorable);
  HostCache restored_cache(kMaxCacheEntries);

  // Add entries for `to_serialize_key1` and `other_key` to the new cache
  // before restoring the serialized one. The `to_serialize_key1` result is
  // different from the original.
  EXPECT_FALSE(restored_cache.Lookup(to_serialize_key1, now));
  restored_cache.Set(to_serialize_key1, replacement_entry, now, kTTL);
  EXPECT_THAT(
      restored_cache.Lookup(to_serialize_key1, now),
      Pointee(Pair(to_serialize_key1, EntryContentsEqual(replacement_entry))));
  EXPECT_EQ(1u, restored_cache.size());

  EXPECT_FALSE(restored_cache.Lookup(other_key, now));
  restored_cache.Set(other_key, other_entry, now, kTTL);
  EXPECT_THAT(restored_cache.Lookup(other_key, now),
              Pointee(Pair(other_key, EntryContentsEqual(other_entry))));
  EXPECT_EQ(2u, restored_cache.size());

  EXPECT_EQ(0u, restored_cache.last_restore_size());

  EXPECT_TRUE(restored_cache.RestoreFromListValue(serialized_cache));
  EXPECT_EQ(1u, restored_cache.last_restore_size());

  HostCache::EntryStaleness stale;

  // Expect `to_serialize_key1` has the replacement entry.
  EXPECT_THAT(
      restored_cache.Lookup(to_serialize_key1, now),
      Pointee(Pair(to_serialize_key1, EntryContentsEqual(replacement_entry))));

  // Expect `to_serialize_key2` has the original entry.
  EXPECT_THAT(
      restored_cache.LookupStale(to_serialize_key2, now, &stale),
      Pointee(Pair(to_serialize_key2, EntryContentsEqual(serialized_entry))));

  // Expect no change for `other_key`.
  EXPECT_THAT(restored_cache.Lookup(other_key, now),
              Pointee(Pair(other_key, EntryContentsEqual(other_entry))));
}

TEST(HostCacheTest, SerializeAndDeserializeAddresses) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache cache(kMaxCacheEntries);

  // Start at t=0.
  base::TimeTicks now;

  HostCache::Key key1 = Key("foobar.com");
  key1.secure = true;
  HostCache::Key key2 = Key("foobar2.com");
  HostCache::Key key3 = Key("foobar3.com");
  HostCache::Key key4 = Key("foobar4.com");

  IPAddress address_ipv4(1, 2, 3, 4);
  IPAddress address_ipv6(0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  IPEndPoint endpoint_ipv4(address_ipv4, 0);
  IPEndPoint endpoint_ipv6(address_ipv6, 0);

  HostCache::Entry entry1 = HostCache::Entry(
      OK, {endpoint_ipv4}, /*aliases=*/{}, HostCache::Entry::SOURCE_UNKNOWN);
  HostCache::Entry entry2 =
      HostCache::Entry(OK, {endpoint_ipv6, endpoint_ipv4}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);
  HostCache::Entry entry3 = HostCache::Entry(
      OK, {endpoint_ipv6}, /*aliases=*/{}, HostCache::Entry::SOURCE_UNKNOWN);
  HostCache::Entry entry4 = HostCache::Entry(
      OK, {endpoint_ipv4}, /*aliases=*/{}, HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(0u, cache.size());

  // Add an entry for "foobar.com" at t=0.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, entry1, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_TRUE(cache.Lookup(key1, now)->second.error() == entry1.error());

  EXPECT_EQ(1u, cache.size());

  // Advance to t=5.
  now += base::Seconds(5);

  // Add entries for "foobar2.com" and "foobar3.com" at t=5.
  EXPECT_FALSE(cache.Lookup(key2, now));
  cache.Set(key2, entry2, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_EQ(2u, cache.size());

  EXPECT_FALSE(cache.Lookup(key3, now));
  cache.Set(key3, entry3, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key3, now));
  EXPECT_EQ(3u, cache.size());

  EXPECT_EQ(0u, cache.last_restore_size());

  // Advance to t=12, ansd serialize the cache.
  now += base::Seconds(7);

  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, false /* include_staleness */,
                HostCache::SerializationType::kRestorable);
  HostCache restored_cache(kMaxCacheEntries);

  // Add entries for "foobar3.com" and "foobar4.com" to the cache before
  // restoring it. The "foobar3.com" result is different from the original.
  EXPECT_FALSE(restored_cache.Lookup(key3, now));
  restored_cache.Set(key3, entry1, now, kTTL);
  EXPECT_TRUE(restored_cache.Lookup(key3, now));
  EXPECT_EQ(1u, restored_cache.size());

  EXPECT_FALSE(restored_cache.Lookup(key4, now));
  restored_cache.Set(key4, entry4, now, kTTL);
  EXPECT_TRUE(restored_cache.Lookup(key4, now));
  EXPECT_EQ(2u, restored_cache.size());

  EXPECT_EQ(0u, restored_cache.last_restore_size());

  EXPECT_TRUE(restored_cache.RestoreFromListValue(serialized_cache));

  HostCache::EntryStaleness stale;

  // The "foobar.com" entry is stale due to both network changes and expiration
  // time.
  EXPECT_FALSE(restored_cache.Lookup(key1, now));
  const std::pair<const HostCache::Key, HostCache::Entry>* result1 =
      restored_cache.LookupStale(key1, now, &stale);
  EXPECT_TRUE(result1);
  EXPECT_TRUE(result1->first.secure);
  EXPECT_THAT(result1->second.text_records(), IsEmpty());
  EXPECT_THAT(result1->second.hostnames(), IsEmpty());
  EXPECT_EQ(1u, result1->second.ip_endpoints().size());
  EXPECT_EQ(endpoint_ipv4, result1->second.ip_endpoints().front());
  EXPECT_EQ(1, stale.network_changes);
  // Time to TimeTicks conversion is fuzzy, so just check that expected and
  // actual expiration times are close.
  EXPECT_GT(base::Milliseconds(100),
            (base::Seconds(2) - stale.expired_by).magnitude());

  // The "foobar2.com" entry is stale only due to network changes.
  EXPECT_FALSE(restored_cache.Lookup(key2, now));
  const std::pair<const HostCache::Key, HostCache::Entry>* result2 =
      restored_cache.LookupStale(key2, now, &stale);
  EXPECT_TRUE(result2);
  EXPECT_FALSE(result2->first.secure);
  EXPECT_EQ(2u, result2->second.ip_endpoints().size());
  EXPECT_EQ(endpoint_ipv6, result2->second.ip_endpoints().front());
  EXPECT_EQ(endpoint_ipv4, result2->second.ip_endpoints().back());
  EXPECT_EQ(1, stale.network_changes);
  EXPECT_GT(base::Milliseconds(100),
            (base::Seconds(-3) - stale.expired_by).magnitude());

  // The "foobar3.com" entry is the new one, not the restored one.
  const std::pair<const HostCache::Key, HostCache::Entry>* result3 =
      restored_cache.Lookup(key3, now);
  EXPECT_TRUE(result3);
  EXPECT_EQ(1u, result3->second.ip_endpoints().size());
  EXPECT_EQ(endpoint_ipv4, result3->second.ip_endpoints().front());

  // The "foobar4.com" entry is still present and usable.
  const std::pair<const HostCache::Key, HostCache::Entry>* result4 =
      restored_cache.Lookup(key4, now);
  EXPECT_TRUE(result4);
  EXPECT_EQ(1u, result4->second.ip_endpoints().size());
  EXPECT_EQ(endpoint_ipv4, result4->second.ip_endpoints().front());

  EXPECT_EQ(2u, restored_cache.last_restore_size());
}

TEST(HostCacheTest, SerializeAndDeserializeEntryWithoutScheme) {
  const base::TimeDelta kTTL = base::Seconds(10);

  HostCache::Key key("host.test", DnsQueryType::UNSPECIFIED, 0,
                     HostResolverSource::ANY, NetworkAnonymizationKey());
  HostCache::Entry entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{},
                       /*aliases=*/{}, HostCache::Entry::SOURCE_UNKNOWN);

  base::TimeTicks now;
  HostCache cache(kMaxCacheEntries);

  cache.Set(key, entry, now, kTTL);
  ASSERT_TRUE(cache.Lookup(key, now));
  ASSERT_EQ(cache.size(), 1u);

  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, /*include_staleness=*/false,
                HostCache::SerializationType::kRestorable);
  HostCache restored_cache(kMaxCacheEntries);
  EXPECT_TRUE(restored_cache.RestoreFromListValue(serialized_cache));
  EXPECT_EQ(restored_cache.size(), 1u);

  HostCache::EntryStaleness staleness;
  EXPECT_THAT(restored_cache.LookupStale(key, now, &staleness),
              Pointee(Pair(key, EntryContentsEqual(entry))));
}

TEST(HostCacheTest, SerializeAndDeserializeWithNetworkAnonymizationKey) {
  const url::SchemeHostPort kHost =
      url::SchemeHostPort(url::kHttpsScheme, "hostname.test", 443);
  const base::TimeDelta kTTL = base::Seconds(10);
  const SchemefulSite kSite(GURL("https://site.test/"));
  const auto kNetworkAnonymizationKey =
      NetworkAnonymizationKey::CreateSameSite(kSite);
  const SchemefulSite kOpaqueSite;
  const auto kOpaqueNetworkAnonymizationKey =
      NetworkAnonymizationKey::CreateSameSite(kOpaqueSite);

  HostCache::Key key1(kHost, DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, kNetworkAnonymizationKey);
  HostCache::Key key2(kHost, DnsQueryType::UNSPECIFIED, 0,
                      HostResolverSource::ANY, kOpaqueNetworkAnonymizationKey);

  IPEndPoint endpoint(IPAddress(1, 2, 3, 4), 0);
  HostCache::Entry entry = HostCache::Entry(OK, {endpoint}, /*aliases=*/{},
                                            HostCache::Entry::SOURCE_UNKNOWN);

  base::TimeTicks now;
  HostCache cache(kMaxCacheEntries);

  cache.Set(key1, entry, now, kTTL);
  cache.Set(key2, entry, now, kTTL);

  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(kNetworkAnonymizationKey,
            cache.Lookup(key1, now)->first.network_anonymization_key);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_EQ(kOpaqueNetworkAnonymizationKey,
            cache.Lookup(key2, now)->first.network_anonymization_key);
  EXPECT_EQ(2u, cache.size());

  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, false /* include_staleness */,
                HostCache::SerializationType::kRestorable);
  HostCache restored_cache(kMaxCacheEntries);
  EXPECT_TRUE(restored_cache.RestoreFromListValue(serialized_cache));
  EXPECT_EQ(1u, restored_cache.size());

  HostCache::EntryStaleness stale;
  EXPECT_THAT(restored_cache.LookupStale(key1, now, &stale),
              Pointee(Pair(key1, EntryContentsEqual(entry))));
  EXPECT_FALSE(restored_cache.Lookup(key2, now));
}

TEST(HostCacheTest, SerializeForDebugging) {
  const url::SchemeHostPort kHost(url::kHttpsScheme, "hostname.test", 443);
  const base::TimeDelta kTTL = base::Seconds(10);
  const NetworkAnonymizationKey kNetworkAnonymizationKey =
      NetworkAnonymizationKey::CreateTransient();

  HostCache::Key key(kHost, DnsQueryType::UNSPECIFIED, 0,
                     HostResolverSource::ANY, kNetworkAnonymizationKey);

  IPEndPoint endpoint(IPAddress(1, 2, 3, 4), 0);
  HostCache::Entry entry = HostCache::Entry(OK, {endpoint}, /*aliases=*/{},
                                            HostCache::Entry::SOURCE_UNKNOWN);

  base::TimeTicks now;
  HostCache cache(kMaxCacheEntries);

  cache.Set(key, entry, now, kTTL);

  EXPECT_TRUE(cache.Lookup(key, now));
  EXPECT_EQ(kNetworkAnonymizationKey,
            cache.Lookup(key, now)->first.network_anonymization_key);
  EXPECT_EQ(1u, cache.size());

  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, false /* include_staleness */,
                HostCache::SerializationType::kDebug);
  HostCache restored_cache(kMaxCacheEntries);
  EXPECT_FALSE(restored_cache.RestoreFromListValue(serialized_cache));

  ASSERT_EQ(1u, serialized_cache.size());
  ASSERT_TRUE(serialized_cache[0].is_dict());
  const std::string* nik_string =
      serialized_cache[0].GetDict().FindString("network_anonymization_key");
  ASSERT_TRUE(nik_string);
  ASSERT_EQ(kNetworkAnonymizationKey.ToDebugString(), *nik_string);
}

TEST(HostCacheTest, SerializeAndDeserialize_Text) {
  base::TimeTicks now;

  base::TimeDelta ttl = base::Seconds(99);
  std::vector<std::string> text_records({"foo", "bar"});
  HostCache::Key key(url::SchemeHostPort(url::kHttpsScheme, "example.com", 443),
                     DnsQueryType::A, 0, HostResolverSource::DNS,
                     NetworkAnonymizationKey());
  key.secure = true;
  HostCache::Entry entry(OK, text_records, HostCache::Entry::SOURCE_DNS, ttl);
  EXPECT_THAT(entry.text_records(), Not(IsEmpty()));

  HostCache cache(kMaxCacheEntries);
  cache.Set(key, entry, now, ttl);
  EXPECT_EQ(1u, cache.size());

  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, false /* include_staleness */,
                HostCache::SerializationType::kRestorable);
  HostCache restored_cache(kMaxCacheEntries);
  EXPECT_TRUE(restored_cache.RestoreFromListValue(serialized_cache));

  ASSERT_EQ(1u, serialized_cache.size());
  ASSERT_EQ(1u, restored_cache.size());
  HostCache::EntryStaleness stale;
  const std::pair<const HostCache::Key, HostCache::Entry>* result =
      restored_cache.LookupStale(key, now, &stale);
  EXPECT_THAT(result, Pointee(Pair(key, EntryContentsEqual(entry))));
  EXPECT_THAT(result->second.text_records(), text_records);
}

TEST(HostCacheTest, SerializeAndDeserialize_Hostname) {
  base::TimeTicks now;

  base::TimeDelta ttl = base::Seconds(99);
  std::vector<HostPortPair> hostnames(
      {HostPortPair("example.com", 95), HostPortPair("chromium.org", 122)});
  HostCache::Key key(url::SchemeHostPort(url::kHttpsScheme, "example.com", 443),
                     DnsQueryType::A, 0, HostResolverSource::DNS,
                     NetworkAnonymizationKey());
  HostCache::Entry entry(OK, hostnames, HostCache::Entry::SOURCE_DNS, ttl);
  EXPECT_THAT(entry.hostnames(), Not(IsEmpty()));

  HostCache cache(kMaxCacheEntries);
  cache.Set(key, entry, now, ttl);
  EXPECT_EQ(1u, cache.size());

  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, false /* include_staleness */,
                HostCache::SerializationType::kRestorable);
  HostCache restored_cache(kMaxCacheEntries);
  EXPECT_TRUE(restored_cache.RestoreFromListValue(serialized_cache));

  ASSERT_EQ(1u, restored_cache.size());
  HostCache::EntryStaleness stale;
  const std::pair<const HostCache::Key, HostCache::Entry>* result =
      restored_cache.LookupStale(key, now, &stale);
  EXPECT_THAT(result, Pointee(Pair(key, EntryContentsEqual(entry))));
  EXPECT_THAT(result->second.hostnames(), hostnames);
}

TEST(HostCacheTest, SerializeAndDeserializeEndpointResult) {
  base::TimeTicks now;

  base::TimeDelta ttl = base::Seconds(99);
  HostCache::Key key(url::SchemeHostPort(url::kHttpsScheme, "example.com", 443),
                     DnsQueryType::A, 0, HostResolverSource::DNS,
                     NetworkAnonymizationKey());
  IPEndPoint ipv6_endpoint(
      IPAddress(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4), 110);
  IPEndPoint ipv4_endpoint1(IPAddress(1, 1, 1, 1), 80);
  IPEndPoint ipv4_endpoint2(IPAddress(2, 2, 2, 2), 90);
  IPEndPoint other_ipv4_endpoint(IPAddress(3, 3, 3, 3), 100);
  std::string ipv6_alias = "ipv6_alias.test";
  std::string ipv4_alias = "ipv4_alias.test";
  std::string other_alias = "other_alias.test";
  std::vector<IPEndPoint> ip_endpoints = {ipv6_endpoint, ipv4_endpoint1,
                                          ipv4_endpoint2, other_ipv4_endpoint};
  std::set<std::string> aliases = {ipv6_alias, ipv4_alias, other_alias};
  HostCache::Entry entry(OK, ip_endpoints, aliases,
                         HostCache::Entry::SOURCE_DNS, ttl);

  std::set<std::string> canonical_names = {ipv6_alias, ipv4_alias};
  entry.set_canonical_names(canonical_names);

  EXPECT_THAT(entry.GetEndpoints(), Not(IsEmpty()));

  ConnectionEndpointMetadata metadata1;
  metadata1.supported_protocol_alpns = {"h3", "h2"};
  metadata1.ech_config_list = {'f', 'o', 'o'};
  metadata1.target_name = ipv6_alias;
  ConnectionEndpointMetadata metadata2;
  metadata2.supported_protocol_alpns = {"h2", "h4"};
  metadata2.target_name = ipv4_alias;
  HostCache::Entry metadata_entry(
      OK,
      std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>{
          {1u, metadata1}, {2u, metadata2}},
      HostCache::Entry::SOURCE_DNS);

  auto merged_entry = HostCache::Entry::MergeEntries(entry, metadata_entry);

  EXPECT_THAT(merged_entry.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ip_endpoints)));
  EXPECT_THAT(
      merged_entry.GetMetadatas(),
      testing::ElementsAre(
          ExpectConnectionEndpointMetadata(testing::ElementsAre("h3", "h2"),
                                           testing::ElementsAre('f', 'o', 'o'),
                                           ipv6_alias),
          ExpectConnectionEndpointMetadata(testing::ElementsAre("h2", "h4"),
                                           IsEmpty(), ipv4_alias)));
  EXPECT_THAT(merged_entry.canonical_names(),
              UnorderedElementsAre(ipv4_alias, ipv6_alias));

  HostCache cache(kMaxCacheEntries);
  cache.Set(key, merged_entry, now, ttl);
  EXPECT_EQ(1u, cache.size());

  base::Value::List serialized_cache;
  cache.GetList(serialized_cache, false /* include_staleness */,
                HostCache::SerializationType::kRestorable);
  HostCache restored_cache(kMaxCacheEntries);
  EXPECT_TRUE(restored_cache.RestoreFromListValue(serialized_cache));

  // Check `serialized_cache` can be encoded as JSON. This ensures it has no
  // binary values.
  std::string json;
  EXPECT_TRUE(base::JSONWriter::Write(serialized_cache, &json));

  ASSERT_EQ(1u, restored_cache.size());
  HostCache::EntryStaleness stale;
  const std::pair<const HostCache::Key, HostCache::Entry>* result =
      restored_cache.LookupStale(key, now, &stale);

  ASSERT_TRUE(result);
  EXPECT_THAT(result, Pointee(Pair(key, EntryContentsEqual(merged_entry))));
  EXPECT_THAT(result->second.GetEndpoints(),
              ElementsAre(ExpectEndpointResult(ip_endpoints)));
  EXPECT_THAT(
      result->second.GetMetadatas(),
      testing::ElementsAre(
          ExpectConnectionEndpointMetadata(testing::ElementsAre("h3", "h2"),
                                           testing::ElementsAre('f', 'o', 'o'),
                                           ipv6_alias),
          ExpectConnectionEndpointMetadata(testing::ElementsAre("h2", "h4"),
                                           IsEmpty(), ipv4_alias)));
  EXPECT_THAT(result->second.canonical_names(),
              UnorderedElementsAre(ipv4_alias, ipv6_alias));

  EXPECT_EQ(result->second.aliases(), aliases);
}

TEST(HostCacheTest, DeserializeNoEndpointNoAliase) {
  base::TimeDelta ttl = base::Seconds(99);
  std::string expiration_time_str = base::NumberToString(
      (base::Time::Now() + ttl).since_origin().InMicroseconds());

  auto dict = base::JSONReader::Read(base::StringPrintf(
      R"(
 [ {
   "dns_query_type": 1,
   "expiration": "%s",
   "flags": 0,
   "host_resolver_source": 2,
   "hostname": "example.com",
   "network_anonymization_key": [  ],
   "port": 443,
   "scheme": "https",
   "secure": false
} ]
)",
      expiration_time_str.c_str()));
  ASSERT_TRUE(dict);

  HostCache restored_cache(kMaxCacheEntries);
  ASSERT_TRUE(dict->is_list());
  EXPECT_TRUE(restored_cache.RestoreFromListValue(dict->GetList()));

  ASSERT_EQ(1u, restored_cache.size());

  HostCache::Key key(url::SchemeHostPort(url::kHttpsScheme, "example.com", 443),
                     DnsQueryType::A, 0, HostResolverSource::DNS,
                     NetworkAnonymizationKey());

  HostCache::EntryStaleness stale;
  const std::pair<const HostCache::Key, HostCache::Entry>* result =
      restored_cache.LookupStale(key, base::TimeTicks::Now(), &stale);

  ASSERT_TRUE(result);
  EXPECT_THAT(result->second.aliases(), ElementsAre());
  EXPECT_THAT(result->second.ip_endpoints(), ElementsAre());
}

TEST(HostCacheTest, DeserializeLegacyAddresses) {
  base::TimeDelta ttl = base::Seconds(99);
  std::string expiration_time_str = base::NumberToString(
      (base::Time::Now() + ttl).since_origin().InMicroseconds());

  auto dict = base::JSONReader::Read(base::StringPrintf(
      R"(
 [ {
   "addresses": [ "2000::", "1.2.3.4" ],
   "dns_query_type": 1,
   "expiration": "%s",
   "flags": 0,
   "host_resolver_source": 2,
   "hostname": "example.com",
   "network_anonymization_key": [  ],
   "port": 443,
   "scheme": "https",
   "secure": false
} ]
)",
      expiration_time_str.c_str()));
  ASSERT_TRUE(dict);

  HostCache restored_cache(kMaxCacheEntries);
  ASSERT_TRUE(dict->is_list());
  EXPECT_TRUE(restored_cache.RestoreFromListValue(dict->GetList()));

  ASSERT_EQ(1u, restored_cache.size());

  HostCache::Key key(url::SchemeHostPort(url::kHttpsScheme, "example.com", 443),
                     DnsQueryType::A, 0, HostResolverSource::DNS,
                     NetworkAnonymizationKey());

  HostCache::EntryStaleness stale;
  const std::pair<const HostCache::Key, HostCache::Entry>* result =
      restored_cache.LookupStale(key, base::TimeTicks::Now(), &stale);

  ASSERT_TRUE(result);
  EXPECT_THAT(result->second.ip_endpoints(),
              ElementsAreArray(MakeEndpoints({"2000::", "1.2.3.4"})));
  EXPECT_THAT(result->second.aliases(), ElementsAre());
}

TEST(HostCacheTest, DeserializeInvalidQueryTypeIntegrity) {
  base::TimeDelta ttl = base::Seconds(99);
  std::string expiration_time_str = base::NumberToString(
      (base::Time::Now() + ttl).since_origin().InMicroseconds());

  // RestoreFromListValue doesn't support dns_query_type=6 (INTEGRITY).
  auto dict = base::JSONReader::Read(base::StringPrintf(
      R"(
 [ {
   "addresses": [ "2000::", "1.2.3.4" ],
   "dns_query_type": 6,
   "expiration": "%s",
   "flags": 0,
   "host_resolver_source": 2,
   "hostname": "example.com",
   "network_anonymization_key": [  ],
   "port": 443,
   "scheme": "https",
   "secure": false
} ]
)",
      expiration_time_str.c_str()));
  ASSERT_TRUE(dict);

  HostCache restored_cache(kMaxCacheEntries);
  ASSERT_TRUE(dict->is_list());
  EXPECT_FALSE(restored_cache.RestoreFromListValue(dict->GetList()));

  ASSERT_EQ(0u, restored_cache.size());
}

TEST(HostCacheTest, DeserializeInvalidQueryTypeHttpsExperimental) {
  base::TimeDelta ttl = base::Seconds(99);
  std::string expiration_time_str = base::NumberToString(
      (base::Time::Now() + ttl).since_origin().InMicroseconds());

  // RestoreFromListValue doesn't support dns_query_type=8 (HTTPS_EXPERIMENTAL).
  auto dict = base::JSONReader::Read(base::StringPrintf(
      R"(
 [ {
   "addresses": [ "2000::", "1.2.3.4" ],
   "dns_query_type": 8,
   "expiration": "%s",
   "flags": 0,
   "host_resolver_source": 2,
   "hostname": "example.com",
   "network_anonymization_key": [  ],
   "port": 443,
   "scheme": "https",
   "secure": false
} ]
)",
      expiration_time_str.c_str()));
  ASSERT_TRUE(dict);

  HostCache restored_cache(kMaxCacheEntries);
  ASSERT_TRUE(dict->is_list());
  EXPECT_FALSE(restored_cache.RestoreFromListValue(dict->GetList()));

  ASSERT_EQ(0u, restored_cache.size());
}

TEST(HostCacheTest, PersistenceDelegate) {
  const base::TimeDelta kTTL = base::Seconds(10);
  HostCache cache(kMaxCacheEntries);
  MockPersistenceDelegate delegate;
  cache.set_persistence_delegate(&delegate);

  HostCache::Key key1 = Key("foobar.com");
  HostCache::Key key2 = Key("foobar2.com");

  HostCache::Entry ok_entry =
      HostCache::Entry(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                       HostCache::Entry::SOURCE_UNKNOWN);
  std::vector<IPEndPoint> other_endpoints = {
      IPEndPoint(IPAddress(1, 1, 1, 1), 300)};
  HostCache::Entry other_entry(OK, std::move(other_endpoints), /*aliases=*/{},
                               HostCache::Entry::SOURCE_UNKNOWN);
  HostCache::Entry error_entry =
      HostCache::Entry(ERR_NAME_NOT_RESOLVED, /*ip_endpoints=*/{},
                       /*aliases=*/{}, HostCache::Entry::SOURCE_UNKNOWN);

  // Start at t=0.
  base::TimeTicks now;
  EXPECT_EQ(0u, cache.size());

  // Add two entries at t=0.
  EXPECT_FALSE(cache.Lookup(key1, now));
  cache.Set(key1, ok_entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(1u, cache.size());
  EXPECT_EQ(1, delegate.num_changes());

  EXPECT_FALSE(cache.Lookup(key2, now));
  cache.Set(key2, error_entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key2, now));
  EXPECT_EQ(2u, cache.size());
  EXPECT_EQ(2, delegate.num_changes());

  // Advance to t=5.
  now += base::Seconds(5);

  // Changes that shouldn't trigger a write:
  // Add an entry for "foobar.com" with different expiration time.
  EXPECT_TRUE(cache.Lookup(key1, now));
  cache.Set(key1, ok_entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(2u, cache.size());
  EXPECT_EQ(2, delegate.num_changes());

  // Add an entry for "foobar.com" with different TTL.
  EXPECT_TRUE(cache.Lookup(key1, now));
  cache.Set(key1, ok_entry, now, kTTL - base::Seconds(5));
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(2u, cache.size());
  EXPECT_EQ(2, delegate.num_changes());

  // Changes that should trigger a write:
  // Add an entry for "foobar.com" with different address list.
  EXPECT_TRUE(cache.Lookup(key1, now));
  cache.Set(key1, other_entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(2u, cache.size());
  EXPECT_EQ(3, delegate.num_changes());

  // Add an entry for "foobar2.com" with different error.
  EXPECT_TRUE(cache.Lookup(key1, now));
  cache.Set(key2, ok_entry, now, kTTL);
  EXPECT_TRUE(cache.Lookup(key1, now));
  EXPECT_EQ(2u, cache.size());
  EXPECT_EQ(4, delegate.num_changes());
}

TEST(HostCacheTest, MergeEndpointsWithAliases) {
  const IPAddress kAddressFront(1, 2, 3, 4);
  const IPEndPoint kEndpointFront(kAddressFront, 0);
  HostCache::Entry front(OK, {kEndpointFront}, {"alias1", "alias2", "alias3"},
                         HostCache::Entry::SOURCE_DNS);
  front.set_text_records(std::vector<std::string>{"text1"});
  const HostPortPair kHostnameFront("host", 1);
  front.set_hostnames(std::vector<HostPortPair>{kHostnameFront});

  const IPAddress kAddressBack(0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               0);
  const IPEndPoint kEndpointBack(kAddressBack, 0);
  HostCache::Entry back(OK, {kEndpointBack}, {"alias2", "alias4", "alias5"},
                        HostCache::Entry::SOURCE_DNS);
  back.set_text_records(std::vector<std::string>{"text2"});
  const HostPortPair kHostnameBack("host", 2);
  back.set_hostnames(std::vector<HostPortPair>{kHostnameBack});

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(OK, result.error());
  EXPECT_EQ(HostCache::Entry::SOURCE_DNS, result.source());

  EXPECT_THAT(result.ip_endpoints(),
              ElementsAre(kEndpointFront, kEndpointBack));
  EXPECT_THAT(result.text_records(), ElementsAre("text1", "text2"));

  EXPECT_THAT(result.hostnames(), ElementsAre(kHostnameFront, kHostnameBack));

  EXPECT_THAT(
      result.aliases(),
      UnorderedElementsAre("alias1", "alias2", "alias3", "alias4", "alias5"));
}

TEST(HostCacheTest, MergeEndpointsKeepEndpointsOrder) {
  std::vector<IPEndPoint> front_addresses =
      MakeEndpoints({"::1", "0.0.0.2", "0.0.0.4"});
  std::vector<IPEndPoint> back_addresses =
      MakeEndpoints({"0.0.0.2", "0.0.0.2", "::3", "::3", "0.0.0.4"});

  HostCache::Entry front(OK, front_addresses, /*aliases=*/{"front"},
                         HostCache::Entry::SOURCE_DNS);
  HostCache::Entry back(OK, back_addresses, /*aliases=*/{"back"},
                        HostCache::Entry::SOURCE_DNS);

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_THAT(
      result.ip_endpoints(),
      ElementsAreArray(MakeEndpoints({"::1", "0.0.0.2", "0.0.0.4", "0.0.0.2",
                                      "0.0.0.2", "::3", "::3", "0.0.0.4"})));
  EXPECT_THAT(result.aliases(), UnorderedElementsAre("front", "back"));
}

TEST(HostCacheTest, MergeMetadatas) {
  ConnectionEndpointMetadata front_metadata;
  front_metadata.supported_protocol_alpns = {"h5", "h6", "monster truck rally"};
  front_metadata.ech_config_list = {'h', 'i'};
  std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>
      front_metadata_map{{4u, front_metadata}};
  HostCache::Entry front(OK, front_metadata_map, HostCache::Entry::SOURCE_DNS);

  ConnectionEndpointMetadata back_metadata;
  back_metadata.supported_protocol_alpns = {"h5"};
  std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>
      back_metadata_map{{2u, back_metadata}};
  HostCache::Entry back(OK, back_metadata_map, HostCache::Entry::SOURCE_DNS);

  HostCache::Entry result = HostCache::Entry::MergeEntries(front, back);

  // Expect `GetEndpoints()` to ignore metadatas if no `IPEndPoint`s.
  EXPECT_THAT(result.GetEndpoints(), IsEmpty());

  // Expect order irrelevant for endpoint metadata merging.
  result = HostCache::Entry::MergeEntries(back, front);
  EXPECT_THAT(result.GetEndpoints(), IsEmpty());
}

TEST(HostCacheTest, MergeMetadatasWithIpEndpointsDifferentCanonicalName) {
  std::string target_name = "example.com";
  std::string other_target_name = "other.example.com";
  ConnectionEndpointMetadata metadata;
  metadata.supported_protocol_alpns = {"h5", "h6", "monster truck rally"};
  metadata.ech_config_list = {'h', 'i'};
  metadata.target_name = target_name;

  std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata> metadata_map{
      {4u, metadata}};
  HostCache::Entry metadata_entry(OK, metadata_map,
                                  HostCache::Entry::SOURCE_DNS);

  // Expect `GetEndpoints()` to always ignore metadatas with no `IPEndPoint`s.
  EXPECT_THAT(metadata_entry.GetEndpoints(), IsEmpty());

  // Merge in an `IPEndPoint` with different canonical name.
  IPEndPoint ip_endpoint(IPAddress(1, 1, 1, 1), 0);
  HostCache::Entry with_ip_endpoint(OK, {ip_endpoint}, /*aliases=*/{},
                                    HostCache::Entry::SOURCE_DNS);
  with_ip_endpoint.set_canonical_names(
      std::set<std::string>{other_target_name});
  HostCache::Entry result =
      HostCache::Entry::MergeEntries(metadata_entry, with_ip_endpoint);

  // Expect `GetEndpoints()` not to return the metadata.
  EXPECT_THAT(
      result.GetEndpoints(),
      ElementsAre(ExpectEndpointResult(std::vector<IPEndPoint>{ip_endpoint})));

  // Expect merge order irrelevant.
  EXPECT_EQ(result,
            HostCache::Entry::MergeEntries(with_ip_endpoint, metadata_entry));
}

TEST(HostCacheTest, MergeMetadatasWithIpEndpointsMatchingCanonicalName) {
  std::string target_name = "example.com";
  ConnectionEndpointMetadata metadata;
  metadata.supported_protocol_alpns = {"h5", "h6", "monster truck rally"};
  metadata.ech_config_list = {'h', 'i'};
  metadata.target_name = target_name;

  std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata> metadata_map{
      {4u, metadata}};
  HostCache::Entry metadata_entry(OK, metadata_map,
                                  HostCache::Entry::SOURCE_DNS);

  // Expect `GetEndpoints()` to always ignore metadatas with no `IPEndPoint`s.
  EXPECT_THAT(metadata_entry.GetEndpoints(), IsEmpty());

  // Merge in an `IPEndPoint` with different canonical name.
  IPEndPoint ip_endpoint(IPAddress(1, 1, 1, 1), 0);
  HostCache::Entry with_ip_endpoint(OK, {ip_endpoint}, /*aliases=*/{},
                                    HostCache::Entry::SOURCE_DNS);
  with_ip_endpoint.set_canonical_names(std::set<std::string>{target_name});
  HostCache::Entry result =
      HostCache::Entry::MergeEntries(metadata_entry, with_ip_endpoint);

  // Expect `GetEndpoints()` to return the metadata.
  EXPECT_THAT(
      result.GetEndpoints(),
      ElementsAre(ExpectEndpointResult(ElementsAre(ip_endpoint), metadata),
                  ExpectEndpointResult(ElementsAre(ip_endpoint))));

  // Expect merge order irrelevant.
  EXPECT_EQ(result,
            HostCache::Entry::MergeEntries(with_ip_endpoint, metadata_entry));
}

TEST(HostCacheTest, MergeMultipleMetadatasWithIpEndpoints) {
  std::string target_name = "example.com";
  ConnectionEndpointMetadata front_metadata;
  front_metadata.supported_protocol_alpns = {"h5", "h6", "monster truck rally"};
  front_metadata.ech_config_list = {'h', 'i'};
  front_metadata.target_name = target_name;

  std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>
      front_metadata_map{{4u, front_metadata}};
  HostCache::Entry front(OK, front_metadata_map, HostCache::Entry::SOURCE_DNS);

  ConnectionEndpointMetadata back_metadata;
  back_metadata.supported_protocol_alpns = {"h5"};
  back_metadata.target_name = target_name;
  std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>
      back_metadata_map{{2u, back_metadata}};
  HostCache::Entry back(OK, back_metadata_map, HostCache::Entry::SOURCE_DNS);

  HostCache::Entry merged_metadatas =
      HostCache::Entry::MergeEntries(front, back);
  HostCache::Entry reversed_merged_metadatas =
      HostCache::Entry::MergeEntries(back, front);

  // Expect `GetEndpoints()` to always ignore metadatas with no `IPEndPoint`s.
  EXPECT_THAT(merged_metadatas.GetEndpoints(), IsEmpty());
  EXPECT_THAT(reversed_merged_metadatas.GetEndpoints(), IsEmpty());

  // Merge in an `IPEndPoint`.
  IPEndPoint ip_endpoint(IPAddress(1, 1, 1, 1), 0);
  HostCache::Entry with_ip_endpoint(OK, {ip_endpoint}, /*aliases=*/{},
                                    HostCache::Entry::SOURCE_DNS);
  with_ip_endpoint.set_canonical_names(std::set<std::string>{target_name});

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(merged_metadatas, with_ip_endpoint);

  // Expect `back_metadata` before `front_metadata` because it has lower
  // priority number.
  EXPECT_THAT(
      result.GetEndpoints(),
      ElementsAre(
          ExpectEndpointResult(ElementsAre(ip_endpoint), back_metadata),
          ExpectEndpointResult(ElementsAre(ip_endpoint), front_metadata),
          ExpectEndpointResult(ElementsAre(ip_endpoint))));

  // Expect merge order irrelevant.
  EXPECT_EQ(result, HostCache::Entry::MergeEntries(reversed_merged_metadatas,
                                                   with_ip_endpoint));
  EXPECT_EQ(result,
            HostCache::Entry::MergeEntries(with_ip_endpoint, merged_metadatas));
  EXPECT_EQ(result, HostCache::Entry::MergeEntries(with_ip_endpoint,
                                                   reversed_merged_metadatas));
}

TEST(HostCacheTest, MergeAliases) {
  HostCache::Entry front(OK, /*ip_endpoints=*/{},
                         /*aliases=*/{"foo1.test", "foo2.test", "foo3.test"},
                         HostCache::Entry::SOURCE_DNS);

  HostCache::Entry back(OK, /*ip_endpoints=*/{},
                        /*aliases=*/{"foo2.test", "foo4.test"},
                        HostCache::Entry::SOURCE_DNS);

  HostCache::Entry expected(
      OK, /*ip_endpoints=*/{},
      /*aliases=*/{"foo1.test", "foo2.test", "foo3.test", "foo4.test"},
      HostCache::Entry::SOURCE_DNS);

  HostCache::Entry result = HostCache::Entry::MergeEntries(front, back);
  EXPECT_EQ(result, expected);

  // Expect order irrelevant for alias merging.
  result = HostCache::Entry::MergeEntries(back, front);
  EXPECT_EQ(result, expected);
}

TEST(HostCacheTest, MergeEntries_frontEmpty) {
  HostCache::Entry front(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS);

  const IPAddress kAddressBack(0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               0);
  const IPEndPoint kEndpointBack(kAddressBack, 0);
  HostCache::Entry back(OK, {kEndpointBack}, {"alias1", "alias2", "alias3"},
                        HostCache::Entry::SOURCE_DNS, base::Hours(4));
  back.set_text_records(std::vector<std::string>{"text2"});
  const HostPortPair kHostnameBack("host", 2);
  back.set_hostnames(std::vector<HostPortPair>{kHostnameBack});

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(OK, result.error());
  EXPECT_EQ(HostCache::Entry::SOURCE_DNS, result.source());

  EXPECT_THAT(result.ip_endpoints(), ElementsAre(kEndpointBack));
  EXPECT_THAT(result.text_records(), ElementsAre("text2"));
  EXPECT_THAT(result.hostnames(), ElementsAre(kHostnameBack));

  EXPECT_EQ(base::Hours(4), result.ttl());

  EXPECT_THAT(result.aliases(),
              UnorderedElementsAre("alias1", "alias2", "alias3"));
}

TEST(HostCacheTest, MergeEntries_backEmpty) {
  const IPAddress kAddressFront(1, 2, 3, 4);
  const IPEndPoint kEndpointFront(kAddressFront, 0);
  HostCache::Entry front(OK, {kEndpointFront}, {"alias1", "alias2", "alias3"},
                         HostCache::Entry::SOURCE_DNS, base::Minutes(5));
  front.set_text_records(std::vector<std::string>{"text1"});
  const HostPortPair kHostnameFront("host", 1);
  front.set_hostnames(std::vector<HostPortPair>{kHostnameFront});

  HostCache::Entry back(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS);

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(OK, result.error());
  EXPECT_EQ(HostCache::Entry::SOURCE_DNS, result.source());

  EXPECT_THAT(result.ip_endpoints(), ElementsAre(kEndpointFront));
  EXPECT_THAT(result.text_records(), ElementsAre("text1"));
  EXPECT_THAT(result.hostnames(), ElementsAre(kHostnameFront));

  EXPECT_EQ(base::Minutes(5), result.ttl());

  EXPECT_THAT(result.aliases(),
              UnorderedElementsAre("alias1", "alias2", "alias3"));
}

TEST(HostCacheTest, MergeEntries_bothEmpty) {
  HostCache::Entry front(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS);
  HostCache::Entry back(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS);

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(ERR_NAME_NOT_RESOLVED, result.error());
  EXPECT_EQ(HostCache::Entry::SOURCE_DNS, result.source());

  EXPECT_THAT(result.ip_endpoints(), IsEmpty());
  EXPECT_THAT(result.text_records(), IsEmpty());
  EXPECT_THAT(result.hostnames(), IsEmpty());
  EXPECT_FALSE(result.has_ttl());
}

TEST(HostCacheTest, MergeEntries_frontWithAliasesNoAddressesBackWithBoth) {
  HostCache::Entry front(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS);
  std::set<std::string> aliases_front({"alias0", "alias1", "alias2"});
  front.set_aliases(aliases_front);

  const IPAddress kAddressBack(0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               0);
  const IPEndPoint kEndpointBack(kAddressBack, 0);
  HostCache::Entry back(OK, {kEndpointBack}, {"alias1", "alias2", "alias3"},
                        HostCache::Entry::SOURCE_DNS, base::Hours(4));

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(OK, result.error());
  EXPECT_EQ(HostCache::Entry::SOURCE_DNS, result.source());

  EXPECT_THAT(result.ip_endpoints(), ElementsAre(kEndpointBack));

  EXPECT_EQ(base::Hours(4), result.ttl());

  EXPECT_THAT(result.aliases(),
              UnorderedElementsAre("alias0", "alias1", "alias2", "alias3"));
}

TEST(HostCacheTest, MergeEntries_backWithAliasesNoAddressesFrontWithBoth) {
  HostCache::Entry back(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS);
  std::set<std::string> aliases_back({"alias1", "alias2", "alias3"});
  back.set_aliases(aliases_back);

  const IPAddress kAddressFront(0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                0);
  const IPEndPoint kEndpointFront(kAddressFront, 0);
  HostCache::Entry front(OK, {kEndpointFront}, {"alias0", "alias1", "alias2"},
                         HostCache::Entry::SOURCE_DNS, base::Hours(4));

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(OK, result.error());
  EXPECT_EQ(HostCache::Entry::SOURCE_DNS, result.source());

  EXPECT_THAT(result.ip_endpoints(), ElementsAre(kEndpointFront));

  EXPECT_EQ(base::Hours(4), result.ttl());

  EXPECT_THAT(result.aliases(),
              UnorderedElementsAre("alias0", "alias1", "alias2", "alias3"));
}

TEST(HostCacheTest, MergeEntries_frontWithAddressesNoAliasesBackWithBoth) {
  const IPAddress kAddressFront(1, 2, 3, 4);
  const IPEndPoint kEndpointFront(kAddressFront, 0);
  HostCache::Entry front(OK, {kEndpointFront}, /*aliases=*/{},
                         HostCache::Entry::SOURCE_DNS, base::Hours(4));

  const IPAddress kAddressBack(0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               0);
  const IPEndPoint kEndpointBack(kAddressBack, 0);
  HostCache::Entry back(OK, {kEndpointBack}, {"alias1", "alias2", "alias3"},
                        HostCache::Entry::SOURCE_DNS, base::Hours(4));
  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(OK, result.error());
  EXPECT_EQ(HostCache::Entry::SOURCE_DNS, result.source());

  EXPECT_THAT(result.ip_endpoints(),
              ElementsAre(kEndpointFront, kEndpointBack));

  EXPECT_EQ(base::Hours(4), result.ttl());

  EXPECT_THAT(result.aliases(),
              UnorderedElementsAre("alias1", "alias2", "alias3"));
}

TEST(HostCacheTest, MergeEntries_backWithAddressesNoAliasesFrontWithBoth) {
  const IPAddress kAddressFront(1, 2, 3, 4);
  const IPEndPoint kEndpointFront(kAddressFront, 0);
  HostCache::Entry front(OK, {kEndpointFront}, {"alias1", "alias2", "alias3"},
                         HostCache::Entry::SOURCE_DNS, base::Hours(4));
  const IPAddress kAddressBack(0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               0);
  const IPEndPoint kEndpointBack(kAddressBack, 0);
  HostCache::Entry back(OK, {kEndpointBack}, /*aliases=*/{},
                        HostCache::Entry::SOURCE_DNS, base::Hours(4));

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(OK, result.error());
  EXPECT_EQ(HostCache::Entry::SOURCE_DNS, result.source());

  EXPECT_THAT(result.ip_endpoints(),
              ElementsAre(kEndpointFront, kEndpointBack));

  EXPECT_EQ(base::Hours(4), result.ttl());

  EXPECT_THAT(result.aliases(),
              UnorderedElementsAre("alias1", "alias2", "alias3"));
}

TEST(HostCacheTest, MergeEntries_differentTtl) {
  HostCache::Entry front(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS,
                         base::Days(12));
  HostCache::Entry back(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS,
                        base::Seconds(42));

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_EQ(base::Seconds(42), result.ttl());
}

TEST(HostCacheTest, MergeEntries_FrontCannonnamePreserved) {
  HostCache::Entry front(OK, /*ip_endpoints=*/{}, /*aliases=*/{"name1"},
                         HostCache::Entry::SOURCE_DNS);

  HostCache::Entry back(OK, /*ip_endpoints=*/{}, /*aliases=*/{"name2"},
                        HostCache::Entry::SOURCE_DNS);

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_THAT(result.aliases(), UnorderedElementsAre("name1", "name2"));
}

// Test that the back canonname can be used if there is no front cannonname.
TEST(HostCacheTest, MergeEntries_BackCannonnameUsable) {
  HostCache::Entry front(OK, /*ip_endpoints=*/{}, /*aliases=*/{},
                         HostCache::Entry::SOURCE_DNS);

  HostCache::Entry back(OK, /*ip_endpoints=*/{}, /*aliases=*/{"name2"},
                        HostCache::Entry::SOURCE_DNS);

  HostCache::Entry result =
      HostCache::Entry::MergeEntries(std::move(front), std::move(back));

  EXPECT_THAT(result.aliases(), UnorderedElementsAre("name2"));
}

TEST(HostCacheTest, ConvertFromInternalAddressResult) {
  const std::vector<IPEndPoint> kEndpoints{
      IPEndPoint(IPAddress(2, 2, 2, 2), 46)};
  constexpr base::TimeDelta kTtl1 = base::Minutes(45);
  constexpr base::TimeDelta kTtl2 = base::Minutes(40);
  constexpr base::TimeDelta kTtl3 = base::Minutes(55);

  std::set<std::unique_ptr<HostResolverInternalResult>> results;
  results.insert(std::make_unique<HostResolverInternalDataResult>(
      "endpoint.test", DnsQueryType::AAAA, base::TimeTicks() + kTtl1,
      base::Time() + kTtl1, HostResolverInternalResult::Source::kDns,
      kEndpoints, std::vector<std::string>{}, std::vector<HostPortPair>{}));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain1.test", DnsQueryType::AAAA, base::TimeTicks() + kTtl2,
      base::Time() + kTtl2, HostResolverInternalResult::Source::kDns,
      "domain2.test"));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain2.test", DnsQueryType::AAAA, base::TimeTicks() + kTtl3,
      base::Time() + kTtl3, HostResolverInternalResult::Source::kDns,
      "endpoint.test"));

  HostCache::Entry converted(std::move(results), base::Time(),
                             base::TimeTicks());

  // Expect kTtl2 because it is the min TTL.
  HostCache::Entry expected(
      OK, kEndpoints,
      /*aliases=*/{"domain1.test", "domain2.test", "endpoint.test"},
      HostCache::Entry::SOURCE_DNS, kTtl2);
  expected.set_canonical_names(std::set<std::string>{"endpoint.test"});

  // Entries converted from HostResolverInternalDataResults do not differentiate
  // between empty and no-data for the various data types, so need to set empty
  // strings and hostname entries into `expected`.
  expected.set_text_records(std::vector<std::string>());
  expected.set_hostnames(std::vector<HostPortPair>());

  EXPECT_EQ(converted, expected);
}

TEST(HostCacheTest, ConvertFromInternalMetadataResult) {
  const std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>
      kMetadatas{{1, ConnectionEndpointMetadata({"h2", "h3"},
                                                /*ech_config_list=*/{},
                                                "target.test")}};
  constexpr base::TimeDelta kTtl1 = base::Minutes(45);
  constexpr base::TimeDelta kTtl2 = base::Minutes(40);
  constexpr base::TimeDelta kTtl3 = base::Minutes(55);

  std::set<std::unique_ptr<HostResolverInternalResult>> results;
  results.insert(std::make_unique<HostResolverInternalMetadataResult>(
      "endpoint.test", DnsQueryType::HTTPS, base::TimeTicks() + kTtl1,
      base::Time() + kTtl1, HostResolverInternalResult::Source::kDns,
      kMetadatas));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain1.test", DnsQueryType::HTTPS, base::TimeTicks() + kTtl2,
      base::Time() + kTtl2, HostResolverInternalResult::Source::kDns,
      "domain2.test"));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain2.test", DnsQueryType::HTTPS, base::TimeTicks() + kTtl3,
      base::Time() + kTtl3, HostResolverInternalResult::Source::kDns,
      "endpoint.test"));

  HostCache::Entry converted(std::move(results), base::Time(),
                             base::TimeTicks());

  // Expect kTtl2 because it is the min TTL.
  HostCache::Entry expected(OK, kMetadatas, HostCache::Entry::SOURCE_DNS,
                            kTtl2);
  expected.set_https_record_compatibility(std::vector<bool>{true});

  EXPECT_EQ(converted, expected);
}

// Test the case of compatible HTTPS records but no metadata of use to Chrome.
// Represented in internal result type as an empty metadata result. Represented
// in HostCache::Entry as empty metadata with at least one true in
// `https_record_compatibility_`.
TEST(HostCacheTest, ConvertFromCompatibleOnlyInternalMetadataResult) {
  const std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata>
      kMetadatas;
  constexpr base::TimeDelta kTtl1 = base::Minutes(45);
  constexpr base::TimeDelta kTtl2 = base::Minutes(40);
  constexpr base::TimeDelta kTtl3 = base::Minutes(55);

  std::set<std::unique_ptr<HostResolverInternalResult>> results;
  results.insert(std::make_unique<HostResolverInternalMetadataResult>(
      "endpoint.test", DnsQueryType::HTTPS, base::TimeTicks() + kTtl1,
      base::Time() + kTtl1, HostResolverInternalResult::Source::kDns,
      kMetadatas));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain1.test", DnsQueryType::HTTPS, base::TimeTicks() + kTtl2,
      base::Time() + kTtl2, HostResolverInternalResult::Source::kDns,
      "domain2.test"));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain2.test", DnsQueryType::HTTPS, base::TimeTicks() + kTtl3,
      base::Time() + kTtl3, HostResolverInternalResult::Source::kDns,
      "endpoint.test"));

  HostCache::Entry converted(std::move(results), base::Time(),
                             base::TimeTicks());

  // Expect kTtl2 because it is the min TTL.
  HostCache::Entry expected(ERR_NAME_NOT_RESOLVED, kMetadatas,
                            HostCache::Entry::SOURCE_DNS, kTtl2);
  expected.set_https_record_compatibility(std::vector<bool>{true});

  EXPECT_EQ(converted, expected);
}

TEST(HostCacheTest, ConvertFromInternalErrorResult) {
  constexpr base::TimeDelta kTtl1 = base::Minutes(45);
  constexpr base::TimeDelta kTtl2 = base::Minutes(40);
  constexpr base::TimeDelta kTtl3 = base::Minutes(55);

  std::set<std::unique_ptr<HostResolverInternalResult>> results;
  results.insert(std::make_unique<HostResolverInternalErrorResult>(
      "endpoint.test", DnsQueryType::A, base::TimeTicks() + kTtl1,
      base::Time() + kTtl1, HostResolverInternalResult::Source::kDns,
      ERR_NAME_NOT_RESOLVED));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain1.test", DnsQueryType::A, base::TimeTicks() + kTtl2,
      base::Time() + kTtl2, HostResolverInternalResult::Source::kDns,
      "domain2.test"));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain2.test", DnsQueryType::A, base::TimeTicks() + kTtl3,
      base::Time() + kTtl3, HostResolverInternalResult::Source::kDns,
      "endpoint.test"));

  HostCache::Entry converted(std::move(results), base::Time(),
                             base::TimeTicks());

  // Expect kTtl2 because it is the min TTL.
  HostCache::Entry expected(ERR_NAME_NOT_RESOLVED, HostCache::Entry::SOURCE_DNS,
                            kTtl2);

  EXPECT_EQ(converted, expected);
}

TEST(HostCacheTest, ConvertFromNonCachableInternalErrorResult) {
  constexpr base::TimeDelta kTtl1 = base::Minutes(45);
  constexpr base::TimeDelta kTtl2 = base::Minutes(40);

  std::set<std::unique_ptr<HostResolverInternalResult>> results;
  results.insert(std::make_unique<HostResolverInternalErrorResult>(
      "endpoint.test", DnsQueryType::AAAA, /*expiration=*/absl::nullopt,
      /*timed_expiration=*/absl::nullopt,
      HostResolverInternalResult::Source::kDns, ERR_NAME_NOT_RESOLVED));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain1.test", DnsQueryType::AAAA, base::TimeTicks() + kTtl1,
      base::Time() + kTtl1, HostResolverInternalResult::Source::kDns,
      "domain2.test"));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain2.test", DnsQueryType::AAAA, base::TimeTicks() + kTtl2,
      base::Time() + kTtl2, HostResolverInternalResult::Source::kDns,
      "endpoint.test"));

  HostCache::Entry converted(std::move(results), base::Time(),
                             base::TimeTicks());

  // Expect no TTL because error is non-cachable (has no TTL itself).
  HostCache::Entry expected(ERR_NAME_NOT_RESOLVED,
                            HostCache::Entry::SOURCE_DNS);

  EXPECT_EQ(converted, expected);
}

TEST(HostCacheTest, ConvertFromInternalAliasOnlyResult) {
  constexpr base::TimeDelta kTtl1 = base::Minutes(45);
  constexpr base::TimeDelta kTtl2 = base::Minutes(40);

  std::set<std::unique_ptr<HostResolverInternalResult>> results;
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain1.test", DnsQueryType::A, base::TimeTicks() + kTtl1,
      base::Time() + kTtl1, HostResolverInternalResult::Source::kDns,
      "domain2.test"));
  results.insert(std::make_unique<HostResolverInternalAliasResult>(
      "domain2.test", DnsQueryType::A, base::TimeTicks() + kTtl2,
      base::Time() + kTtl2, HostResolverInternalResult::Source::kDns,
      "endpoint.test"));

  HostCache::Entry converted(std::move(results), base::Time(),
                             base::TimeTicks());

  // Expect no TTL because alias-only results are not cacheable.
  HostCache::Entry expected(ERR_NAME_NOT_RESOLVED,
                            HostCache::Entry::SOURCE_DNS);

  EXPECT_EQ(converted, expected);
}

TEST(HostCacheTest, ConvertFromEmptyInternalResult) {
  HostCache::Entry converted({}, base::Time(), base::TimeTicks());
  HostCache::Entry expected(ERR_NAME_NOT_RESOLVED,
                            HostCache::Entry::SOURCE_UNKNOWN);

  EXPECT_EQ(converted, expected);
}

}  // namespace net