1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
// Copyright (C) 2012-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <asiolink/asio_wrapper.h>
#include <asiolink/interval_timer.h>
#include <asiolink/io_address.h>
#include <dhcp/duid.h>
#include <dhcp/iface_mgr.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/csv_lease_file4.h>
#include <dhcpsrv/csv_lease_file6.h>
#include <dhcpsrv/lease_mgr.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcpsrv/memfile_lease_mgr.h>
#include <dhcpsrv/timer_mgr.h>
#include <dhcpsrv/testutils/lease_file_io.h>
#include <dhcpsrv/testutils/test_utils.h>
#include <dhcpsrv/testutils/generic_lease_mgr_unittest.h>
#include <testutils/gtest_utils.h>
#include <util/multi_threading_mgr.h>
#include <util/pid_file.h>
#include <util/range_utilities.h>
#include <util/stopwatch.h>

#include <gtest/gtest.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

#include <cstdlib><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <iostream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <fstream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <queue><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sstream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

#include <unistd.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

using namespace std;
using namespace isc;
using namespace isc::asiolink;
using namespace isc::data;
using namespace isc::db;
using namespace isc::dhcp;
using namespace isc::dhcp::test;
using namespace isc::util;

namespace {

/// @brief Class derived from @c Memfile_LeaseMgr to test LFC timer.
///
/// This class provides a custom callback function which is invoked
/// when the timer for Lease File Cleanup goes off. It is used to
/// test that the timer is correctly installed.
class LFCMemfileLeaseMgr : public Memfile_LeaseMgr {
public:

    /// @brief Constructor.
    ///
    /// Sets the counter for callbacks to 0.
    LFCMemfileLeaseMgr(const DatabaseConnection::ParameterMap& parameters)
        : Memfile_LeaseMgr(parameters), lfc_cnt_(0) {
    }

    /// @brief Returns the number of callback executions.
    int getLFCCount() {
        return (lfc_cnt_);
    }

protected:

    /// @brief Custom callback.
    ///
    /// This callback function increases the counter of callback executions.
    /// By examining the counter value a test may verify that the callback
    /// was triggered an expected number of times.
    virtual void lfcCallback() {
        ++lfc_cnt_;
    }

private:

    /// @brief Counter of callback function executions.
    int lfc_cnt_;
};

/// @brief A derivation of the lease manager exposing protected methods.
class NakedMemfileLeaseMgr : public Memfile_LeaseMgr {
public:

    /// @brief Constructor.
    ///
    /// Creates instance of the lease manager.
    NakedMemfileLeaseMgr(const DatabaseConnection::ParameterMap& parameters)
        : Memfile_LeaseMgr(parameters) {
    }

    using Memfile_LeaseMgr::lfcCallback;
    using Memfile_LeaseMgr::relay_id6_;
    using Memfile_LeaseMgr::remote_id6_;
    using Memfile_LeaseMgr::buildExtendedInfoTables6;
};

/// @brief Test fixture class for @c Memfile_LeaseMgr
class MemfileLeaseMgrTest : public GenericLeaseMgrTest {
public:

    /// @brief memfile lease mgr test constructor
    ///
    /// Creates memfile and stores it in lmptr_ pointer
    MemfileLeaseMgrTest() :
        io4_(getLeaseFilePath("leasefile4_0.csv")),
        io6_(getLeaseFilePath("leasefile6_0.csv")),
        io_service_(getIOService()),
        timer_mgr_(TimerMgr::instance()),
        extra_files_() {

        timer_mgr_->setIOService(io_service_);
        DatabaseConnection::setIOService(io_service_);
        ProcessSpawn::setIOService(io_service_);

        std::ostringstream s;
        s << KEA_LFC_BUILD_DIR << "/kea-lfc";
        setenv("KEA_LFC_EXECUTABLE", s.str().c_str(), 1);

        // Remove lease files and products of Lease File Cleanup.
        removeFiles(getLeaseFilePath("leasefile4_0.csv"));
        removeFiles(getLeaseFilePath("leasefile6_0.csv"));

        // Reset staging extended info sanitizer to its default.
        CfgMgr::instance().getStagingCfg()->getConsistency()->
            setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_FIX);

        MultiThreadingMgr::instance().setMode(false);
    }

    /// @brief Reopens the connection to the backend.
    ///
    /// This function is called by unit tests to force reconnection of the
    /// backend to check that the leases are stored and can be retrieved
    /// from the storage.
    ///
    /// @param u Universe (V4 or V6)
    virtual void reopen(Universe u) {
        LeaseMgrFactory::destroy();
        startBackend(u);
    }

    /// @brief destructor
    ///
    /// destroys lease manager backend.
    virtual ~MemfileLeaseMgrTest() {
        // Stop TimerMgr worker thread if it is running.
        // Make sure there are no timers registered.
        timer_mgr_->unregisterTimers();
        LeaseMgrFactory::destroy();
        // Remove lease files and products of Lease File Cleanup.
        removeFiles(getLeaseFilePath("leasefile4_0.csv"));
        removeFiles(getLeaseFilePath("leasefile6_0.csv"));
        // Remove other files.
        removeOtherFiles();
        // Reset staging extended info sanitizer to its default.
        CfgMgr::instance().getStagingCfg()->getConsistency()->
            setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_FIX);
        // Disable multi-threading.
        MultiThreadingMgr::instance().setMode(false);

        getIOService()->stopAndPoll();
    }

    /// @brief Remove files being products of Lease File Cleanup.
    ///
    /// @param base_name Path to the lease file name. This file is removed
    /// and all files which names are created from this name (having specific
    /// suffixes used by Lease File Cleanup mechanism).
    void removeFiles(const std::string& base_name) const {
        // Generate suffixes and append them to the base name. The
        // resulting file names are the ones that may exist as a
        // result of LFC.
        for (int i = static_cast<int>(Memfile_LeaseMgr::FILE_CURRENT);
             i <= static_cast<int>(Memfile_LeaseMgr::FILE_FINISH);
             ++i) {
            Memfile_LeaseMgr::LFCFileType type = static_cast<
                Memfile_LeaseMgr::LFCFileType>(i);
            LeaseFileIO io(Memfile_LeaseMgr::appendSuffix(base_name, type));
            io.removeFile();
        }
    }

    /// @brief Remove other files.
    void removeOtherFiles() const {
        for (auto const& file : extra_files_) {
            LeaseFileIO io(file);
            io.removeFile();
        }
    }

    /// @brief Return path to the lease file used by unit tests.
    ///
    /// @param filename Name of the lease file appended to the path to the
    /// directory where test data is held.
    ///
    /// @return Full path to the lease file.
    static std::string getLeaseFilePath(const std::string& filename) {
        std::ostringstream s;
        s << TEST_DATA_BUILDDIR << "/" << filename;
        return (s.str());
    }

    /// @brief Returns the configuration string for the backend.
    ///
    /// This string configures the @c LeaseMgrFactory to create the memfile
    /// backend and use leasefile4_0.csv and leasefile6_0.csv files as
    /// storage for leases.
    ///
    /// @param no_universe Indicates whether universe parameter should be
    /// included (false), or not (true).
    ///
    /// @return Configuration string for @c LeaseMgrFactory.
    static std::string getConfigString(Universe u) {
        std::ostringstream s;
        s << "type=memfile " << (u == V4 ? "universe=4 " : "universe=6 ")
          << "name="
          << getLeaseFilePath(u == V4 ? "leasefile4_0.csv" : "leasefile6_0.csv")
          << " lfc-interval=0";
        return (s.str());
    }

    /// @brief Creates instance of the backend.
    ///
    /// @param u Universe (v4 or V6).
    void startBackend(Universe u) {
        try {
            LeaseMgrFactory::create(getConfigString(u));
        } catch (...) {
            std::cerr << "*** ERROR: unable to create instance of the Memfile"
                " lease database backend.\n";
            throw;
        }
        lmptr_ = &(LeaseMgrFactory::instance());
    }

    /// @brief Runs IOService and stops after a specified time.
    ///
    /// @param ms Duration in milliseconds.
    void setTestTime(const uint32_t ms) {
        IntervalTimer timer(io_service_);
        timer.setup([this]() {
            io_service_->stop();
        }, ms, IntervalTimer::ONE_SHOT);

        io_service_->run();
        io_service_->stop();
        io_service_->restart();
    }

    /// @brief Waits for the specified process to finish.
    ///
    /// @param process An object which started the process.
    /// @param timeout Timeout in seconds.
    ///
    /// @return true if the process ended, false otherwise
    bool waitForProcess(const Memfile_LeaseMgr& lease_mgr,
                        const uint8_t timeout) {
        const uint32_t iterations_max = timeout * 1000;
        IntervalTimer fast_path_timer(io_service_);
        IntervalTimer timer(io_service_);
        bool elapsed = false;
        timer.setup([&]() {
            io_service_->stop();
            elapsed = true;
        }, iterations_max, IntervalTimer::ONE_SHOT);

        fast_path_timer.setup([&]() {
            if (!lease_mgr.isLFCRunning()) {
                io_service_->stop();
            }
        }, 1, IntervalTimer::REPEATING);

        io_service_->run();
        io_service_->stop();
        io_service_->restart();
        return (!elapsed);
    }

    /// @brief Single instance of IOService.
    static asiolink::IOServicePtr getIOService() {
        static asiolink::IOServicePtr io_service(new asiolink::IOService());
        return (io_service);
    }

    /// @brief Generates a DHCPv4 lease with random content.
    ///
    /// The following lease parameters are randomly generated:
    /// - HW address,
    /// - client identifier,
    /// - hostname,
    /// - subnet identifier,
    /// - client last transmission time,
    ///
    /// The following lease parameters are set to constant values:
    /// - valid lifetime = 1200,
    /// - DNS update forward flag = false,
    /// - DNS update reverse flag = false,
    ///
    /// The lease address is set to address passed as function
    /// argument.
    ///
    /// @param address Lease address.
    ///
    /// @return new lease with random content
    Lease4Ptr initiateRandomLease4(const IOAddress& address) {

        // Randomize HW address.
        vector<uint8_t> mac(6);
        fillRandom(mac.begin(), mac.end());
        HWAddrPtr hwaddr(new HWAddr(mac, HTYPE_ETHER));

        // Let's generate clientid of random length
        vector<uint8_t> clientid(4 + random()%20);
        // And then fill it with random value.
        fillRandom(clientid.begin(), clientid.end());

        uint32_t valid_lft = 1200;
        time_t timestamp = time(NULL) - 86400 + random()%86400;
        bool fqdn_fwd = false;
        bool fqdn_rev = false;
        uint32_t subnet_id = 1000 + random()%16;

        std::ostringstream hostname;
        hostname << "hostname" << (random() % 2048);

        // Return created lease.
        return (Lease4Ptr(new Lease4(address, hwaddr, &clientid[0],
                                     clientid.size(), valid_lft,
                                     timestamp, subnet_id, fqdn_fwd,
                                     fqdn_rev, hostname.str())));
    }

    /// @brief Generates a DHCPv6 lease with random content.
    ///
    /// The following lease parameters are randomly generated:
    /// - DUID,
    /// - IAID,
    /// - hostname,
    /// - subnet identifier,
    /// - client last transmission time,
    ///
    /// The following lease parameters are set to constant values:
    /// - lease type = IA_NA
    /// - valid lifetime = 1200,
    /// - preferred lifetime = 1000
    /// - DNS update forward flag = false,
    /// - DNS update reverse flag = false,
    ///
    /// The lease address is set to address passed as function
    /// argument.
    ///
    /// @param address Lease address.
    ///
    /// @return new lease with random content
    Lease6Ptr initiateRandomLease6(const IOAddress& address) {
        // Let's generate DUID of random length.
        std::vector<uint8_t> duid_vec(8 + random()%20);
        // And then fill it with random value.
        fillRandom(duid_vec.begin(), duid_vec.end());
        DuidPtr duid(new DUID(duid_vec));

        Lease::Type lease_type = Lease::TYPE_NA;
        uint32_t iaid = 1 + random()%100;
        uint32_t valid_lft = 1200;
        uint32_t preferred_lft = 1000;
        time_t timestamp = time(NULL) - 86400 + random()%86400;
        bool fqdn_fwd = false;
        bool fqdn_rev = false;
        uint32_t subnet_id = 1000 + random()%16;

        std::ostringstream hostname;
        hostname << "hostname" << (random() % 2048);

        // Return created lease.
        Lease6Ptr lease(new Lease6(lease_type, address, duid, iaid,
                                   preferred_lft, valid_lft,
                                   subnet_id, fqdn_fwd, fqdn_rev,
                                   hostname.str()));
        lease->cltt_ = timestamp;
        return (lease);
    }

    /// @brief Object providing access to v4 lease IO.
    LeaseFileIO io4_;

    /// @brief Object providing access to v6 lease IO.
    LeaseFileIO io6_;

    /// @brief Pointer to the IO service used by the tests.
    IOServicePtr io_service_;

    /// @brief Pointer to the instance of the @c TimerMgr.
    TimerMgrPtr timer_mgr_;

    /// @brief List of names of other files to removed.
    vector<string> extra_files_;
};

/// @brief This test checks if the LeaseMgr can be instantiated and that it
/// parses parameters string properly.
TEST_F(MemfileLeaseMgrTest, constructor) {<--- syntax error
    DatabaseConnection::ParameterMap pmap;
    pmap["universe"] = "6";
    pmap["persist"] = "false";
    boost::scoped_ptr<Memfile_LeaseMgr> lease_mgr;

    EXPECT_NO_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)));

    // Check the extended info enable flag.
    EXPECT_FALSE(lease_mgr->getExtendedInfoTablesEnabled());
    pmap["extended-info-tables"] = "true";
    EXPECT_NO_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)));
    EXPECT_TRUE(lease_mgr->getExtendedInfoTablesEnabled());

    // Expecting that persist parameter is yes or no. Everything other than
    // that is wrong.
    pmap["lfc-interval"] = "10";
    pmap["name"] = getLeaseFilePath("leasefile6_1.csv");
    pmap["max-row-errors"] = "5";
    pmap["name"] = getLeaseFilePath("leasefile6_1.csv");
    pmap["persist"] = "bogus";
    EXPECT_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)), isc::BadValue);

    // The lfc-interval must be an integer.
    pmap["persist"] = "true";
    pmap["lfc-interval"] = "bogus";
    EXPECT_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)), isc::BadValue);

    // The max-row-errors must be an integer.
    pmap["lfc-interval"] = "10";
    pmap["max-row-errors"] = "bogus";
    EXPECT_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)), isc::BadValue);

    // The max-row-errors must be >= 0.
    pmap["max-row-errors"] = "-1";
    EXPECT_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)), isc::BadValue);

    // Moved to the end as it can leave the timer registered.
    pmap["max-row-errors"] = "5";
    EXPECT_NO_THROW(lease_mgr.reset(new Memfile_LeaseMgr(pmap)));
}

/// @brief Checks if there is no lease manager NoLeaseManager is thrown.
TEST_F(MemfileLeaseMgrTest, noLeaseManager) {
    LeaseMgrFactory::destroy();
    EXPECT_THROW(LeaseMgrFactory::instance(), NoLeaseManager);
}

/// @brief Checks if the getType() and getName() methods both return "memfile".
TEST_F(MemfileLeaseMgrTest, getTypeAndName) {
    startBackend(V4);
    EXPECT_EQ(std::string("memfile"), lmptr_->getType());
    EXPECT_EQ(std::string("memory"),  lmptr_->getName());
}

/// @brief Checks if the path to the lease files is initialized correctly.
TEST_F(MemfileLeaseMgrTest, getLeaseFilePath) {
    // Initialize IO objects, so as the test csv files get removed after the
    // test (when destructors are called).
    LeaseFileIO io4(getLeaseFilePath("leasefile4_1.csv"));
    LeaseFileIO io6(getLeaseFilePath("leasefile6_1.csv"));

    DatabaseConnection::ParameterMap pmap;
    pmap["universe"] = "4";
    pmap["name"] = getLeaseFilePath("leasefile4_1.csv");
    boost::scoped_ptr<Memfile_LeaseMgr> lease_mgr(new Memfile_LeaseMgr(pmap));

    EXPECT_EQ(pmap["name"],
              lease_mgr->getLeaseFilePath(Memfile_LeaseMgr::V4));

    pmap["persist"] = "false";
    lease_mgr.reset(new Memfile_LeaseMgr(pmap));
    EXPECT_TRUE(lease_mgr->getLeaseFilePath(Memfile_LeaseMgr::V4).empty());
    EXPECT_TRUE(lease_mgr->getLeaseFilePath(Memfile_LeaseMgr::V6).empty());
}

/// @brief Check if the persistLeases correctly checks that leases should not be written
/// to disk when disabled through configuration.
TEST_F(MemfileLeaseMgrTest, persistLeases) {
    // Initialize IO objects, so as the test csv files get removed after the
    // test (when destructors are called).
    LeaseFileIO io4(getLeaseFilePath("leasefile4_1.csv"));
    LeaseFileIO io6(getLeaseFilePath("leasefile6_1.csv"));

    DatabaseConnection::ParameterMap pmap;
    pmap["universe"] = "4";
    pmap["lfc-interval"] = "0";
    // Specify the names of the lease files. Leases will be written.
    pmap["name"] = getLeaseFilePath("leasefile4_1.csv");
    boost::scoped_ptr<Memfile_LeaseMgr> lease_mgr(new Memfile_LeaseMgr(pmap));

    lease_mgr.reset(new Memfile_LeaseMgr(pmap));
    EXPECT_TRUE(lease_mgr->persistLeases(Memfile_LeaseMgr::V4));
    EXPECT_FALSE(lease_mgr->persistLeases(Memfile_LeaseMgr::V6));

    pmap["universe"] = "6";
    pmap["name"] = getLeaseFilePath("leasefile6_1.csv");
    lease_mgr.reset(new Memfile_LeaseMgr(pmap));
    EXPECT_FALSE(lease_mgr->persistLeases(Memfile_LeaseMgr::V4));
    EXPECT_TRUE(lease_mgr->persistLeases(Memfile_LeaseMgr::V6));

    // This should disable writes of leases to disk.
    pmap["persist"] = "false";
    lease_mgr.reset(new Memfile_LeaseMgr(pmap));
    EXPECT_FALSE(lease_mgr->persistLeases(Memfile_LeaseMgr::V4));
    EXPECT_FALSE(lease_mgr->persistLeases(Memfile_LeaseMgr::V6));
}

/// @brief Check if it is possible to schedule the timer to perform the Lease
/// File Cleanup periodically.
TEST_F(MemfileLeaseMgrTest, lfcTimer) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    // Specify the names of the lease files. Leases will be written.
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    pmap["lfc-interval"] = "1";

    boost::scoped_ptr<LFCMemfileLeaseMgr>
        lease_mgr(new LFCMemfileLeaseMgr(pmap));

    // Run the test for at most 2.9 seconds.
    setTestTime(2900);

    // Within 2.9 we should record two LFC executions.
    EXPECT_EQ(2, lease_mgr->getLFCCount());
}

/// @brief Check that the kea environment is accesible to the Lease
/// File Cleanup process.
TEST_F(MemfileLeaseMgrTest, lfcEnv) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    pmap["lfc-interval"] = "1";

    std::ostringstream s;
    s << DHCP_DATA_DIR << "/test_kea_lfc_env.sh";
    setenv("KEA_LFC_EXECUTABLE", s.str().c_str(), 1);

    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));

    // Try to run the lease file cleanup.
    ASSERT_NO_THROW(lease_mgr->lfcCallback());

    // Wait for the LFC process to complete.
    ASSERT_TRUE(waitForProcess(*lease_mgr, 1));

    // And make sure it has returned an exit status of 0.
    EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
        << "environment not available to LFC";
}

/// @brief This test checks if the LFC timer is disabled (doesn't trigger)
/// cleanups when the lfc-interval is set to 0.
TEST_F(MemfileLeaseMgrTest, lfcTimerDisabled) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    // Set the LFC interval to 0, which should effectively disable it.
    pmap["lfc-interval"] = "0";

    boost::scoped_ptr<LFCMemfileLeaseMgr>
        lease_mgr(new LFCMemfileLeaseMgr(pmap));

    // Run the test for at most 1.9 seconds.
    setTestTime(1900);

    // There should be no LFC execution recorded.
    EXPECT_EQ(0, lease_mgr->getLFCCount());
}

/// @brief This test checks that the callback function executing the cleanup of the
/// DHCPv4 lease file works as expected.
TEST_F(MemfileLeaseMgrTest, leaseFileCleanup4) {
    // This string contains the lease file header, which matches
    // the contents of the new file in which no leases have been
    // stored.
    std::string new_file_contents =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    // This string contains the contents of the lease file with exactly
    // one lease, but two entries. One of the entries should be removed
    // as a result of lease file cleanup.
    std::string current_file_contents = new_file_contents +
        "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,{ \"foo\": true },0\n"
        "192.0.2.2,02:02:02:02:02:02,,200,800,8,1,1,,1,,0\n";
    LeaseFileIO current_file(getLeaseFilePath("leasefile4_0.csv"));
    current_file.writeFile(current_file_contents);

    std::string previous_file_contents = new_file_contents +
        "192.0.2.3,03:03:03:03:03:03,,200,200,8,1,1,,1,,0\n"
        "192.0.2.3,03:03:03:03:03:03,,200,800,8,1,1,,1,{ \"bar\": true },0\n";
    LeaseFileIO previous_file(getLeaseFilePath("leasefile4_0.csv.2"));
    previous_file.writeFile(previous_file_contents);

    // Create the backend.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    pmap["lfc-interval"] = "1";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));

    // Try to run the lease file cleanup.
    ASSERT_NO_THROW(lease_mgr->lfcCallback());

    // The new lease file should have been created and it should contain
    // no leases.
    ASSERT_TRUE(current_file.exists());
    EXPECT_EQ(new_file_contents, current_file.readFile());

    // Wait for the LFC process to complete.
    ASSERT_TRUE(waitForProcess(*lease_mgr, 2));

    // And make sure it has returned an exit status of 0.
    EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
        << "Executing the LFC process failed: make sure that"
        " the kea-lfc program has been compiled.";

    // Check if we can still write to the lease file.
    std::vector<uint8_t> hwaddr_vec(6);
    HWAddrPtr hwaddr(new HWAddr(hwaddr_vec, HTYPE_ETHER));
    Lease4Ptr new_lease(new Lease4(IOAddress("192.0.2.45"), hwaddr,
                                   static_cast<const uint8_t*>(0), 0,
                                   100, 0, 1));
    ASSERT_NO_THROW(lease_mgr->addLease(new_lease));

    std::string updated_file_contents = new_file_contents +
        "192.0.2.45,00:00:00:00:00:00,,100,100,1,0,0,,0,,0\n";
    EXPECT_EQ(updated_file_contents, current_file.readFile());

    // This string contains the contents of the lease file we
    // expect after the LFC run.  It has two leases with one
    // entry each.
    std::string result_file_contents = new_file_contents +
        "192.0.2.2,02:02:02:02:02:02,,200,800,8,1,1,,1,,0\n"
        "192.0.2.3,03:03:03:03:03:03,,200,800,8,1,1,,1,{ \"bar\": true },0\n";

    // The LFC should have created a file with the two leases and moved it
    // to leasefile4_0.csv.2
    LeaseFileIO input_file(getLeaseFilePath("leasefile4_0.csv.2"), false);
    ASSERT_TRUE(input_file.exists());
    // And this file should contain the contents of the result file.
    EXPECT_EQ(result_file_contents, input_file.readFile());
}

/// @brief This test checks that the callback function executing the cleanup of the
/// DHCPv6 lease file works as expected.
TEST_F(MemfileLeaseMgrTest, leaseFileCleanup6) {
    // This string contains the lease file header, which matches
    // the contents of the new file in which no leases have been
    // stored.
    std::string new_file_contents =
        "address,duid,valid_lifetime,expire,subnet_id,"
        "pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
        "fqdn_rev,hostname,hwaddr,state,user_context,"
        "hwtype,hwaddr_source,pool_id\n";

    // This string contains the contents of the lease file with exactly
    // one lease, but two entries. One of the entries should be removed
    // as a result of lease file cleanup.
    std::string current_file_contents = new_file_contents +
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,200,"
        "8,100,0,7,0,1,1,,,1,,,,0\n"
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
        "8,100,0,7,0,1,1,,,1,{ \"foo\": true },,,0\n";
    LeaseFileIO current_file(getLeaseFilePath("leasefile6_0.csv"));
    current_file.writeFile(current_file_contents);

    std::string previous_file_contents = new_file_contents +
        "2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,200,"
        "8,100,0,7,0,1,1,,,1,{ \"bar\": true },,,0\n"
        "2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
        "8,100,0,7,0,1,1,,,1,,,,0\n";
    LeaseFileIO previous_file(getLeaseFilePath("leasefile6_0.csv.2"));
    previous_file.writeFile(previous_file_contents);

    // Create the backend.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    pmap["lfc-interval"] = "1";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));

    // Try to run the lease file cleanup.
    ASSERT_NO_THROW(lease_mgr->lfcCallback());

    // The new lease file should have been created and it should contain
    // no leases.
    ASSERT_TRUE(current_file.exists());
    EXPECT_EQ(new_file_contents, current_file.readFile());

    // Wait for the LFC process to complete.
    ASSERT_TRUE(waitForProcess(*lease_mgr, 2));

    // And make sure it has returned an exit status of 0.
    EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
        << "Executing the LFC process failed: make sure that"
        " the kea-lfc program has been compiled.";

    // Check if we can still write to the lease file.
    std::vector<uint8_t> duid_vec(13);
    DuidPtr duid(new DUID(duid_vec));
    Lease6Ptr new_lease(new Lease6(Lease::TYPE_NA, IOAddress("3000::1"), duid,
                                   123, 300, 400, 2));
    new_lease->cltt_ = 0;
    ASSERT_NO_THROW(lease_mgr->addLease(new_lease));

    std::string update_file_contents = new_file_contents +
        "3000::1,00:00:00:00:00:00:00:00:00:00:00:00:00,400,"
        "400,2,300,0,123,128,0,0,,,0,,,,0\n";
    EXPECT_EQ(update_file_contents, current_file.readFile());

    // This string contains the contents of the lease file we
    // expect after the LFC run.  It has two leases with one
    // entry each.
    std::string result_file_contents = new_file_contents +
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
        "8,100,0,7,128,1,1,,,1,{ \"foo\": true },,,0\n"
        "2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
        "8,100,0,7,128,1,1,,,1,,,,0\n";

    // The LFC should have created a file with the two leases and moved it
    // to leasefile6_0.csv.2
    LeaseFileIO input_file(getLeaseFilePath("leasefile6_0.csv.2"), false);
    ASSERT_TRUE(input_file.exists());
    // And this file should contain the contents of the result file.
    EXPECT_EQ(result_file_contents, input_file.readFile());
}

/// @brief This test verifies that EXIT_FAILURE status code is returned when
/// the LFC process fails to start.
TEST_F(MemfileLeaseMgrTest, leaseFileCleanupStartFail) {
    // This string contains the lease file header, which matches
    // the contents of the new file in which no leases have been
    // stored.
    std::string new_file_contents =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    // Create the lease file to be used by the backend.
    std::string current_file_contents = new_file_contents +
        "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,,0\n";
    LeaseFileIO current_file(getLeaseFilePath("leasefile4_0.csv"));
    current_file.writeFile(current_file_contents);

    // Specify invalid path to the kea-lfc executable. This should result
    // in failure status code returned by the child process.
    setenv("KEA_LFC_EXECUTABLE", "foobar", 1);

    // Create the backend.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    pmap["lfc-interval"] = "1";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    ASSERT_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)), ProcessSpawnError);
}

/// @brief This test checks that the callback function executing the cleanup of the
/// files doesn't move the current file if the finish file exists
TEST_F(MemfileLeaseMgrTest, leaseFileFinish) {
    // This string contains the lease file header, which matches
    // the contents of the new file in which no leases have been
    // stored.
    std::string new_file_contents =
        "address,duid,valid_lifetime,expire,subnet_id,"
        "pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
        "fqdn_rev,hostname,hwaddr,state,user_context,"
        "hwtype,hwaddr_source,pool_id\n";

    // This string contains the contents of the current lease file.
    // It should not be moved.
    std::string current_file_contents = new_file_contents +
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,200,"
        "8,100,0,7,0,1,1,,,1,,,,0\n"
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
        "8,100,0,7,0,1,1,,,1,,,,0\n";
    LeaseFileIO current_file(getLeaseFilePath("leasefile6_0.csv"));
    current_file.writeFile(current_file_contents);

    // This string contains the contents of the finish file.  It should
    // be moved to the previous file.
    std::string finish_file_contents = new_file_contents +
        "2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
        "8,100,0,7,0,1,1,,,1,,0\n";
    LeaseFileIO finish_file(getLeaseFilePath("leasefile6_0.csv.completed"));
    finish_file.writeFile(finish_file_contents);

    // Create the backend.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    pmap["lfc-interval"] = "1";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));

    // Try to run the lease file cleanup.
    ASSERT_NO_THROW(lease_mgr->lfcCallback());

    // The current lease file should not have been touched.
    ASSERT_TRUE(current_file.exists());
    EXPECT_EQ(current_file_contents, current_file.readFile());

    // Wait for the LFC process to complete.
    ASSERT_TRUE(waitForProcess(*lease_mgr, 5));

    // And make sure it has returned an exit status of 0.
    EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
        << "Executing the LFC process failed: make sure that"
        " the kea-lfc program has been compiled.";

    // The LFC should have moved the finish file to the previous file -
    // leasefile6_0.csv.2
    LeaseFileIO previous_file(getLeaseFilePath("leasefile6_0.csv.2"), false);
    ASSERT_TRUE(previous_file.exists());
    // And this file should contain the contents of the finish file.
    EXPECT_EQ(finish_file_contents, previous_file.readFile());

    // The finish file should have been removed
    ASSERT_FALSE(finish_file.exists());
}

/// @brief This test checks that the callback function executing the cleanup of the
/// files doesn't move the current file if the copy file exists
TEST_F(MemfileLeaseMgrTest, leaseFileCopy) {
    // This string contains the lease file header, which matches
    // the contents of the new file in which no leases have been
    // stored.
    std::string new_file_contents =
        "address,duid,valid_lifetime,expire,subnet_id,"
        "pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
        "fqdn_rev,hostname,hwaddr,state,user_context,"
        "hwtype,hwaddr_source,pool_id\n";

    // This string contains the contents of the current lease file.
    // It should not be moved.
    std::string current_file_contents = new_file_contents +
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,200,"
        "8,100,0,7,0,1,1,,,1,,,,0\n"
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
        "8,100,0,7,0,1,1,,,1,{ \"foo\": true },,,0\n";
    LeaseFileIO current_file(getLeaseFilePath("leasefile6_0.csv"));
    current_file.writeFile(current_file_contents);

    // This string contains the contents of the copy file.  It should
    // be processed and moved to the previous file.  As there is only
    // one lease the processing should result in the previous file being
    // the same.
    std::string input_file_contents = new_file_contents +
        "2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
        "8,100,0,7,128,1,1,,,1,{ \"foo\": true },,,0\n";
    LeaseFileIO input_file(getLeaseFilePath("leasefile6_0.csv.1"));
    input_file.writeFile(input_file_contents);

    // Create the backend.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    pmap["lfc-interval"] = "1";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));

    // Try to run the lease file cleanup.
    ASSERT_NO_THROW(lease_mgr->lfcCallback());

    // The current lease file should not have been touched.
    ASSERT_TRUE(current_file.exists());
    EXPECT_EQ(current_file_contents, current_file.readFile());

    // Wait for the LFC process to complete.
    ASSERT_TRUE(waitForProcess(*lease_mgr, 5));

    // And make sure it has returned an exit status of 0.
    EXPECT_EQ(0, lease_mgr->getLFCExitStatus())
        << "Executing the LFC process failed: make sure that"
        " the kea-lfc program has been compiled.";

    // The LFC should have processed the lease and moved it to the previous
    // file - leasefile6_0.csv.2
    LeaseFileIO previous_file(getLeaseFilePath("leasefile6_0.csv.2"), false);
    ASSERT_TRUE(previous_file.exists());
    // And this file should contain the contents of the copy file.
    EXPECT_EQ(input_file_contents, previous_file.readFile());

    // The input file should have been removed
    ASSERT_FALSE(input_file.exists());
}

/// @brief Checks that adding/getting/deleting a Lease6 object works.
TEST_F(MemfileLeaseMgrTest, addGetDelete6) {
    startBackend(V6);
    testAddGetDelete6();
}

/// @brief Checks that adding/getting/deleting a Lease6 object works.
TEST_F(MemfileLeaseMgrTest, addGetDelete6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testAddGetDelete6();
}

/// @brief Basic Lease4 Checks
///
/// Checks that the addLease, getLease4 (by address) and deleteLease (with an
/// IPv4 address) works.
TEST_F(MemfileLeaseMgrTest, basicLease4) {
    startBackend(V4);
    testBasicLease4();
}

/// @brief Basic Lease4 Checks
TEST_F(MemfileLeaseMgrTest, basicLease4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testBasicLease4();
}

/// @todo Write more memfile tests

/// @brief Simple test about lease4 retrieval through client id method
TEST_F(MemfileLeaseMgrTest, getLease4ClientId) {
    startBackend(V4);
    testGetLease4ClientId();
}

/// @brief Simple test about lease4 retrieval through client id method
TEST_F(MemfileLeaseMgrTest, getLease4ClientIdMultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease4ClientId();
}

/// @brief Checks that lease4 retrieval client id is null is working
TEST_F(MemfileLeaseMgrTest, getLease4NullClientId) {
    startBackend(V4);
    testGetLease4NullClientId();
}

/// @brief Checks that lease4 retrieval client id is null is working
TEST_F(MemfileLeaseMgrTest, getLease4NullClientIdMultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease4NullClientId();
}

/// @brief Checks lease4 retrieval through HWAddr
TEST_F(MemfileLeaseMgrTest, getLease4HWAddr1) {
    startBackend(V4);
    testGetLease4HWAddr1();
}

/// @brief Checks lease4 retrieval through HWAddr
TEST_F(MemfileLeaseMgrTest, getLease4HWAddr1MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease4HWAddr1();
}

/// @brief Check GetLease4 methods - access by Hardware Address
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of DUID and IAID.
TEST_F(MemfileLeaseMgrTest, getLease4HWAddr2) {
    startBackend(V4);
    testGetLease4HWAddr2();
}

/// @brief Check GetLease4 methods - access by Hardware Address
TEST_F(MemfileLeaseMgrTest, getLease4HWAddr2MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease4HWAddr2();
}

/// @brief Basic Lease4 Checks
///
/// Checks that the addLease, getLease4(by address), getLease4(hwaddr,subnet_id),
/// updateLease4() and deleteLease can handle NULL client-id.
/// (client-id is optional and may not be present)
TEST_F(MemfileLeaseMgrTest, lease4NullClientId) {
    startBackend(V4);
    testLease4NullClientId();
}

/// @brief Basic Lease4 Checks
TEST_F(MemfileLeaseMgrTest, lease4NullClientIdMultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testLease4NullClientId();
}

/// @brief Check GetLease4 methods - access by Hardware Address & Subnet ID
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of hardware address and subnet ID
TEST_F(MemfileLeaseMgrTest, DISABLED_getLease4HwaddrSubnetId) {
    /// @todo: fails on memfile. It's probably a memfile bug.
    startBackend(V4);
    testGetLease4HWAddrSubnetId();
}

/// @brief Check GetLease4 methods - access by Hardware Address & Subnet ID
TEST_F(MemfileLeaseMgrTest, DISABLED_getLease4HwaddrSubnetIdMultiThread) {
    /// @todo: fails on memfile. It's probably a memfile bug.
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease4HWAddrSubnetId();
}

/// @brief Check GetLease4 methods - access by Client ID
///
/// Adds leases to the database and checks that they can be accessed via
/// the Client ID.
TEST_F(MemfileLeaseMgrTest, getLease4ClientId2) {
    startBackend(V4);
    testGetLease4ClientId2();
}

/// @brief Check GetLease4 methods - access by Client ID
TEST_F(MemfileLeaseMgrTest, getLease4ClientId2MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease4ClientId2();
}

/// @brief Get Lease4 by client ID
///
/// Check that the system can cope with a client ID of any size.
TEST_F(MemfileLeaseMgrTest, getLease4ClientIdSize) {
    startBackend(V4);
    testGetLease4ClientIdSize();
}

/// @brief Get Lease4 by client ID
TEST_F(MemfileLeaseMgrTest, getLease4ClientIdSizeMultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease4ClientIdSize();
}

/// @brief Check GetLease4 methods - access by Client ID & Subnet ID
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of client and subnet IDs.
TEST_F(MemfileLeaseMgrTest, getLease4ClientIdSubnetId) {
    startBackend(V4);
    testGetLease4ClientIdSubnetId();
}

/// @brief Check GetLease4 methods - access by Client ID & Subnet ID
TEST_F(MemfileLeaseMgrTest, getLease4ClientIdSubnetIdMultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease4ClientIdSubnetId();
}

/// @brief This test checks that all IPv4 leases for a specified subnet id are returned.
TEST_F(MemfileLeaseMgrTest, getLeases4SubnetId) {
    startBackend(V4);
    testGetLeases4SubnetId();
}

/// @brief This test checks that all IPv4 leases for a specified subnet id are returned.
TEST_F(MemfileLeaseMgrTest, getLeases4SubnetIdMultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases4SubnetId();
}

/// @brief This test checks that all IPv4 leases with a specified hostname are returned.
TEST_F(MemfileLeaseMgrTest, getLeases4Hostname) {
    startBackend(V4);
    testGetLeases4Hostname();
}

/// @brief This test checks that all IPv4 leases with a specified hostname are returned.
TEST_F(MemfileLeaseMgrTest, getLeases4HostnameMultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases4Hostname();
}

/// @brief This test checks that all IPv4 leases are returned.
TEST_F(MemfileLeaseMgrTest, getLeases4) {
    startBackend(V4);
    testGetLeases4();
}

/// @brief This test checks that all IPv4 leases are returned.
TEST_F(MemfileLeaseMgrTest, getLeases4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases4();
}

/// @brief Test that a range of IPv4 leases is returned with paging.
TEST_F(MemfileLeaseMgrTest, getLeases4Paged) {
    startBackend(V4);
    testGetLeases4Paged();
}

/// @brief Test that a range of IPv4 leases is returned with paging.
TEST_F(MemfileLeaseMgrTest, getLeases4PagedMultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases4Paged();
}

/// @brief This test checks that all IPv6 leases for a specified subnet id are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6SubnetId) {
    startBackend(V6);
    testGetLeases6SubnetId();
}

/// @brief This test checks that all IPv6 leases for a specified subnet id are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6SubnetIdMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases6SubnetId();
}

/// @brief This test checks that all IPv6 leases for a specified subnet id
/// with paging are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6SubnetIdPaged) {
    startBackend(V6);
    testGetLeases6SubnetIdPaged();
}

/// @brief This test checks that all IPv6 leases for a specified subnet id
/// with paging are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6SubnetIdPagedMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases6SubnetIdPaged();
}

/// @brief This test checks that all IPv6 leases with a specified hostname are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6Hostname) {
    startBackend(V6);
    testGetLeases6Hostname();
}

/// @brief This test checks that all IPv6 leases with a specified hostname are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6HostnameMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases6Hostname();
}

/// @brief This test adds 3 leases and verifies fetch by DUID.
/// Verifies retrieval of non existant DUID fails
TEST_F(MemfileLeaseMgrTest, getLeases6Duid) {
    startBackend(V6);
    testGetLeases6Duid();
}

/// @brief This test adds 3 leases and verifies fetch by DUID.
TEST_F(MemfileLeaseMgrTest, getLeases6DuidMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases6Duid();
}

/// @brief This test checks that all IPv6 leases are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6) {
    startBackend(V6);
    testGetLeases6();
}

/// @brief This test checks that all IPv6 leases are returned.
TEST_F(MemfileLeaseMgrTest, getLeases6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases6();
}

/// @brief Test that a range of IPv6 leases is returned with paging.
TEST_F(MemfileLeaseMgrTest, getLeases6Paged) {
    startBackend(V6);
    testGetLeases6Paged();
}

/// @brief Test that a range of IPv6 leases is returned with paging.
TEST_F(MemfileLeaseMgrTest, getLeases6PagedMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases6Paged();
}

/// @brief Basic Lease6 Checks
///
/// Checks that the addLease, getLease6 (by address) and deleteLease (with an
/// IPv6 address) works.
TEST_F(MemfileLeaseMgrTest, basicLease6) {
    startBackend(V6);
    testBasicLease6();
}

/// @brief Basic Lease6 Checks
TEST_F(MemfileLeaseMgrTest, basicLease6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testBasicLease6();
}

/// @brief Check GetLease6 methods - access by DUID/IAID
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of DUID and IAID.
/// @todo: test disabled, because Memfile_LeaseMgr::getLeases6(Lease::Type,
/// const DUID& duid, uint32_t iaid) const is not implemented yet.
TEST_F(MemfileLeaseMgrTest, getLeases6DuidIaid) {
    startBackend(V6);
    testGetLeases6DuidIaid();
}

/// @brief Check GetLease6 methods - access by DUID/IAID
TEST_F(MemfileLeaseMgrTest, getLeases6DuidIaidMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases6DuidIaid();
}

/// @brief Check that the system can cope with a DUID of allowed size.
TEST_F(MemfileLeaseMgrTest, getLeases6DuidSize) {
    startBackend(V6);
    testGetLeases6DuidSize();
}

/// @brief Check that the system can cope with a DUID of allowed size.
TEST_F(MemfileLeaseMgrTest, getLeases6DuidSizeMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLeases6DuidSize();
}

/// @brief Check that the expired DHCPv4 leases can be retrieved.
///
/// This test adds a number of leases to the lease database and marks
/// some of them as expired. Then it queries for expired leases and checks
/// whether only expired leases are returned, and that they are returned in
/// the order from most to least expired. It also checks that the lease
/// which is marked as 'reclaimed' is not returned.
TEST_F(MemfileLeaseMgrTest, getExpiredLeases4) {
    startBackend(V4);
    testGetExpiredLeases4();
}

/// @brief Check that the expired DHCPv4 leases can be retrieved.
TEST_F(MemfileLeaseMgrTest, getExpiredLeases4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetExpiredLeases4();
}

/// @brief Check that the expired DHCPv6 leases can be retrieved.
///
/// This test adds a number of leases to the lease database and marks
/// some of them as expired. Then it queries for expired leases and checks
/// whether only expired leases are returned, and that they are returned in
/// the order from most to least expired. It also checks that the lease
/// which is marked as 'reclaimed' is not returned.
TEST_F(MemfileLeaseMgrTest, getExpiredLeases6) {
    startBackend(V6);
    testGetExpiredLeases6();
}

/// @brief Check that the expired DHCPv6 leases can be retrieved.
TEST_F(MemfileLeaseMgrTest, getExpiredLeases6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetExpiredLeases6();
}

/// @brief Check that expired reclaimed DHCPv6 leases are removed.
TEST_F(MemfileLeaseMgrTest, deleteExpiredReclaimedLeases6) {
    startBackend(V6);
    testDeleteExpiredReclaimedLeases6();
}

/// @brief Check that expired reclaimed DHCPv6 leases are removed.
TEST_F(MemfileLeaseMgrTest, deleteExpiredReclaimedLeases6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testDeleteExpiredReclaimedLeases6();
}

/// @brief Check that expired reclaimed DHCPv4 leases are removed.
TEST_F(MemfileLeaseMgrTest, deleteExpiredReclaimedLeases4) {
    startBackend(V4);
    testDeleteExpiredReclaimedLeases4();
}

/// @brief Check that expired reclaimed DHCPv4 leases are removed.
TEST_F(MemfileLeaseMgrTest, deleteExpiredReclaimedLeases4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testDeleteExpiredReclaimedLeases4();
}

/// @brief Check that getLease6 methods discriminate by lease type.
///
/// Adds six leases, two per lease type all with the same duid and iad but
/// with alternating subnet_ids.
/// It then verifies that all of getLeases6() method variants correctly
/// discriminate between the leases based on lease type alone.
/// @todo: Disabled, because type parameter in Memfile_LeaseMgr::getLease6
/// (Lease::Type, const isc::asiolink::IOAddress& addr) const is not used.
TEST_F(MemfileLeaseMgrTest, lease6LeaseTypeCheck) {
    startBackend(V6);
    testLease6LeaseTypeCheck();
}

/// @brief Check that getLease6 methods discriminate by lease type.
TEST_F(MemfileLeaseMgrTest, lease6LeaseTypeCheckMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testLease6LeaseTypeCheck();
}

/// @brief Check GetLease6 methods - access by DUID/IAID/SubnetID
///
/// Adds leases to the database and checks that they can be accessed via
/// a combination of DIUID and IAID.
TEST_F(MemfileLeaseMgrTest, getLease6DuidIaidSubnetId) {
    startBackend(V6);
    testGetLease6DuidIaidSubnetId();
}

/// @brief Check GetLease6 methods - access by DUID/IAID/SubnetID
TEST_F(MemfileLeaseMgrTest, getLease6DuidIaidSubnetIdMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease6DuidIaidSubnetId();
}

/// @brief Checks that getLease6(type, duid, iaid, subnet-id) works with different
/// DUID sizes
TEST_F(MemfileLeaseMgrTest, getLease6DuidIaidSubnetIdSize) {
    startBackend(V6);
    testGetLease6DuidIaidSubnetIdSize();
}

/// @brief Checks that getLease6(type, duid, iaid, subnet-id) works with different
/// DUID sizes
TEST_F(MemfileLeaseMgrTest, getLease6DuidIaidSubnetIdSizeMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetLease6DuidIaidSubnetIdSize();
}

/// @brief Lease4 update tests
///
/// Checks that we are able to update a lease in the database.
/// @todo: Disabled, because memfile does not throw when lease is updated.
/// We should reconsider if lease{4,6} structures should have a limit
/// implemented in them.
TEST_F(MemfileLeaseMgrTest, DISABLED_updateLease4) {
    startBackend(V4);
    testUpdateLease4();
}

/// @brief Lease4 update tests
TEST_F(MemfileLeaseMgrTest, DISABLED_updateLease4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testUpdateLease4();
}

/// @brief Lease6 update tests
///
/// Checks that we are able to update a lease in the database.
/// @todo: Disabled, because memfile does not throw when lease is updated.
/// We should reconsider if lease{4,6} structures should have a limit
/// implemented in them.
TEST_F(MemfileLeaseMgrTest, DISABLED_updateLease6) {
    startBackend(V6);
    testUpdateLease6();
}

/// @brief Lease6 update tests
TEST_F(MemfileLeaseMgrTest, DISABLED_updateLease6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testUpdateLease6();
}

/// @brief DHCPv4 Lease recreation tests
///
/// Checks that the lease can be created, deleted and recreated with
/// different parameters. It also checks that the re-created lease is
/// correctly stored in the lease database.
TEST_F(MemfileLeaseMgrTest, testRecreateLease4) {
    startBackend(V4);
    testRecreateLease4();
}

/// @brief DHCPv4 Lease recreation tests
TEST_F(MemfileLeaseMgrTest, testRecreateLease4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testRecreateLease4();
}

/// @brief DHCPv6 Lease recreation tests
///
/// Checks that the lease can be created, deleted and recreated with
/// different parameters. It also checks that the re-created lease is
/// correctly stored in the lease database.
TEST_F(MemfileLeaseMgrTest, testRecreateLease6) {
    startBackend(V6);
    testRecreateLease6();
}

/// @brief DHCPv6 Lease recreation tests
TEST_F(MemfileLeaseMgrTest, testRecreateLease6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testRecreateLease6();
}

// The following tests are not applicable for memfile. When adding
// new tests to the list here, make sure to provide brief explanation
// why they are not applicable:
//
// testGetLease4HWAddrSubnetIdSize() - memfile just keeps Lease structure
//     and does not do any checks of HWAddr content

/// @brief Checks that null DUID is not allowed.
/// Test is disabled as Memfile does not currently defend against a null DUID.
TEST_F(MemfileLeaseMgrTest, DISABLED_nullDuid) {
    // Create leases, although we need only one.
    vector<Lease6Ptr> leases = createLeases6();

    leases[1]->duid_.reset();
    ASSERT_THROW(lmptr_->addLease(leases[1]), DbOperationError);
}

/// @brief Checks that null DUID is not allowed.
TEST_F(MemfileLeaseMgrTest, DISABLED_nullDuidMultiThread) {
    MultiThreadingMgr::instance().setMode(true);
    // Create leases, although we need only one.
    vector<Lease6Ptr> leases = createLeases6();

    leases[1]->duid_.reset();
    ASSERT_THROW(lmptr_->addLease(leases[1]), DbOperationError);
}

/// @brief Tests whether memfile can store and retrieve hardware addresses
TEST_F(MemfileLeaseMgrTest, testLease6Mac) {
    startBackend(V6);
    testLease6MAC();
}

/// @brief Tests whether memfile can store and retrieve hardware addresses
TEST_F(MemfileLeaseMgrTest, testLease6MacMultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testLease6MAC();
}

/// @brief Check that memfile reports version correctly.
TEST_F(MemfileLeaseMgrTest, versionCheck) {
    // Check that V4 backend reports versions correctly.
    startBackend(V4);
    testVersion(Memfile_LeaseMgr::MAJOR_VERSION_V4,
                Memfile_LeaseMgr::MINOR_VERSION_V4);
    LeaseMgrFactory::destroy();

    // Check that V6 backends reports them ok, too.
    startBackend(V6);
    testVersion(Memfile_LeaseMgr::MAJOR_VERSION_V6,
                Memfile_LeaseMgr::MINOR_VERSION_V6);
    LeaseMgrFactory::destroy();
}

/// @brief Checks that declined IPv4 leases can be returned correctly.
TEST_F(MemfileLeaseMgrTest, getDeclined4) {
    startBackend(V4);
    testGetDeclinedLeases4();
}

/// @brief Checks that declined IPv4 leases can be returned correctly.
TEST_F(MemfileLeaseMgrTest, getDeclined4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testGetDeclinedLeases4();
}

/// @brief Checks that declined IPv6 leases can be returned correctly.
TEST_F(MemfileLeaseMgrTest, getDeclined6) {
    startBackend(V6);
    testGetDeclinedLeases6();
}

/// @brief Checks that declined IPv6 leases can be returned correctly.
TEST_F(MemfileLeaseMgrTest, getDeclined6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testGetDeclinedLeases6();
}

/// @brief This test checks that the backend reads DHCPv4 lease data from multiple
/// files.
TEST_F(MemfileLeaseMgrTest, load4MultipleLeaseFiles) {
    LeaseFileIO io2(getLeaseFilePath("leasefile4_0.csv.2"));
    io2.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
                  "fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"
                  "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,,0\n"
                  "192.0.2.11,bb:bb:bb:bb:bb:bb,,200,200,8,1,1,,1,,0\n");

    LeaseFileIO io1(getLeaseFilePath("leasefile4_0.csv.1"));
    io1.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
                  "fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"
                  "192.0.2.1,01:01:01:01:01:01,,200,200,8,1,1,,1,,0\n"
                  "192.0.2.11,bb:bb:bb:bb:bb:bb,,200,400,8,1,1,,1,,0\n"
                  "192.0.2.12,cc:cc:cc:cc:cc:cc,,200,200,8,1,1,,1,,0\n");

    LeaseFileIO io(getLeaseFilePath("leasefile4_0.csv"));
    io.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
                 "fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"
                 "192.0.2.10,0a:0a:0a:0a:0a:0a,,200,200,8,1,1,,1,,0\n"
                 "192.0.2.12,cc:cc:cc:cc:cc:cc,,200,400,8,1,1,,1,,0\n");

    startBackend(V4);

    // This lease only exists in the second file and the cltt should
    // be 0.
    Lease4Ptr lease = lmptr_->getLease4(IOAddress("192.0.2.1"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    // This lease only exists in the first file and the cltt should
    // be 0.
    lease = lmptr_->getLease4(IOAddress("192.0.2.2"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    // This lease only exists in the third file and the cltt should
    // be 0.
    lease = lmptr_->getLease4(IOAddress("192.0.2.10"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    // This lease exists in the first and second file and the cltt
    // should be calculated using the expiration time and the
    // valid lifetime from the second file.
    lease = lmptr_->getLease4(IOAddress("192.0.2.11"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(200, lease->cltt_);

    // This lease exists in the second and third file and the cltt
    // should be calculated using the expiration time and the
    // valid lifetime from the third file.
    lease = lmptr_->getLease4(IOAddress("192.0.2.12"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(200, lease->cltt_);
}

/// @brief This test checks that the lease database backend loads the file with
/// the .completed postfix instead of files with postfixes .1 and .2 if
/// the file with .completed postfix exists.
TEST_F(MemfileLeaseMgrTest, load4CompletedFile) {
    LeaseFileIO io2(getLeaseFilePath("leasefile4_0.csv.2"));
    io2.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
                  "fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"
                  "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,,0\n"
                  "192.0.2.11,bb:bb:bb:bb:bb:bb,,200,200,8,1,1,,1,,0\n");

    LeaseFileIO io1(getLeaseFilePath("leasefile4_0.csv.1"));
    io1.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
                  "fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"
                  "192.0.2.1,01:01:01:01:01:01,,200,200,8,1,1,,1,,0\n"
                  "192.0.2.11,bb:bb:bb:bb:bb:bb,,200,400,8,1,1,,1,,0\n"
                  "192.0.2.12,cc:cc:cc:cc:cc:cc,,200,200,8,1,1,,1,,0\n");

    LeaseFileIO io(getLeaseFilePath("leasefile4_0.csv"));
    io.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
                 "fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"
                 "192.0.2.10,0a:0a:0a:0a:0a:0a,,200,200,8,1,1,,1,,0\n"
                 "192.0.2.12,cc:cc:cc:cc:cc:cc,,200,400,8,1,1,,1,,0\n");

    LeaseFileIO ioc(getLeaseFilePath("leasefile4_0.csv.completed"));
    ioc.writeFile("address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
                  "fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"
                  "192.0.2.13,ff:ff:ff:ff:ff:ff,,200,200,8,1,1,,1,,0\n");

    startBackend(V4);

    // We expect that this file only holds leases that belong to the
    // lease file or to the file with .completed postfix.
    Lease4Ptr lease = lmptr_->getLease4(IOAddress("192.0.2.10"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    lease = lmptr_->getLease4(IOAddress("192.0.2.12"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(200, lease->cltt_);

    // This lease is in the .completed file.
    lease = lmptr_->getLease4(IOAddress("192.0.2.13"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    // Leases from the .1 and .2 files should not be loaded.
    EXPECT_FALSE(lmptr_->getLease4(IOAddress("192.0.2.11")));
    EXPECT_FALSE(lmptr_->getLease4(IOAddress("192.0.2.1")));
}

/// @brief This test checks that backend constructor refuses to load leases from the
/// lease files if the LFC is in progress.
TEST_F(MemfileLeaseMgrTest, load4LFCInProgress) {
    // Create the backend configuration.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    pmap["lfc-interval"] = "1";

    // Create a pid file holding the PID of the current process. Choosing the
    // pid of the current process guarantees that when the backend starts up
    // the process is alive.
    PIDFile pid_file(Memfile_LeaseMgr::appendSuffix(pmap["name"], Memfile_LeaseMgr::FILE_PID));
    pid_file.write();

    // There is a pid file and the process which pid is in the file is
    // running, so the backend should refuse to start.
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    ASSERT_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)),
                 DbOpenError);

    // Remove the pid file, and retry. The backend should be created.
    pid_file.deleteFile();
    ASSERT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));
}

/// @brief This test checks that the backend reads DHCPv6 lease data from multiple
/// files.
TEST_F(MemfileLeaseMgrTest, load6MultipleLeaseFiles) {
    LeaseFileIO io2(getLeaseFilePath("leasefile6_0.csv.2"));
    io2.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                  "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    LeaseFileIO io1(getLeaseFilePath("leasefile6_0.csv.1"));
    io1.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                  "2001:db8:1::3,03:03:03:03:03:03:03:03:03:03:03:03:03,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
                  "300,800,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
    io.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                 "2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
                 "400,1000,8,100,0,7,0,1,1,,,1,,,,0\n"
                 "2001:db8:1::5,05:05:05:05:05:05:05:05:05:05:05:05:05,"
                 "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    startBackend(V6);

    // This lease only exists in the first file and the cltt should be 0.
    Lease6Ptr lease = lmptr_->getLease6(Lease::TYPE_NA,
                                        IOAddress("2001:db8:1::1"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    // This lease exists in the first and second file and the cltt should
    // be calculated using the expiration time and the valid lifetime
    // from the second file.
    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(500, lease->cltt_);

    // This lease only exists in the second file and the cltt should be 0.
    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::3"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    // This lease exists in the second and third file and the cltt should
    // be calculated using the expiration time and the valid lifetime
    // from the third file.
    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(600, lease->cltt_);

    // This lease only exists in the third file and the cltt should be 0.
    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::5"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);
}

/// @brief This test checks that the backend reads DHCPv6 lease data from the
/// leasefile without the postfix and the file with a .1 postfix when
/// the file with the .2 postfix is missing.
TEST_F(MemfileLeaseMgrTest, load6MultipleNoSecondFile) {
    LeaseFileIO io1(getLeaseFilePath("leasefile6_0.csv.1"));
    io1.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                  "2001:db8:1::3,03:03:03:03:03:03:03:03:03:03:03:03:03,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
                  "300,800,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
    io.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                 "2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
                 "400,1000,8,100,0,7,0,1,1,,,1,,,,0\n"
                 "2001:db8:1::5,05:05:05:05:05:05:05:05:05:05:05:05:05,"
                 "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    startBackend(V6);

    // Check that leases from the leasefile6_0 and leasefile6_0.1 have
    // been loaded.
    Lease6Ptr lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(500, lease->cltt_);

    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::3"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(600, lease->cltt_);

    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::5"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    // Make sure that a lease which is not in those files is not loaded.
    EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::1")));
}

/// @brief This test checks that the backend reads DHCPv6 lease data from the
/// leasefile without the postfix and the file with a .2 postfix when
/// the file with the .1 postfix is missing.
TEST_F(MemfileLeaseMgrTest, load6MultipleNoFirstFile) {
    LeaseFileIO io2(getLeaseFilePath("leasefile6_0.csv.2"));
    io2.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                  "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
    io.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                 "2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
                 "400,1000,8,100,0,7,0,1,1,,,1,,,,0\n"
                 "2001:db8:1::5,05:05:05:05:05:05:05:05:05:05:05:05:05,"
                 "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    startBackend(V6);

    // Verify that leases which belong to the leasefile6_0.csv and
    // leasefile6_0.2 are loaded.
    Lease6Ptr lease = lmptr_->getLease6(Lease::TYPE_NA,
                                        IOAddress("2001:db8:1::1"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(600, lease->cltt_);

    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::5"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    // A lease which doesn't belong to these files should not be loaded.
    EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::3")));
}

/// @brief This test checks that the lease database backend loads the file with
/// the .completed postfix instead of files with postfixes .1 and .2 if
/// the file with .completed postfix exists.
TEST_F(MemfileLeaseMgrTest, load6CompletedFile) {
    LeaseFileIO io2(getLeaseFilePath("leasefile6_0.csv.2"));
    io2.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                  "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    LeaseFileIO io1(getLeaseFilePath("leasefile6_0.csv.1"));
    io1.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                  "2001:db8:1::3,03:03:03:03:03:03:03:03:03:03:03:03:03,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
                  "300,800,8,100,0,7,0,1,1,,,1,,,,0\n"
                  "2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
                  "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
    io.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                 "2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
                 "400,1000,8,100,0,7,0,1,1,,,1,,,,0\n"
                 "2001:db8:1::5,05:05:05:05:05:05:05:05:05:05:05:05:05,"
                 "200,200,8,100,0,7,0,1,1,,,1,,,,0\n");

    LeaseFileIO ioc(getLeaseFilePath("leasefile6_0.csv.completed"));
    ioc.writeFile("address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                  "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                  "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"
                  "2001:db8:1::125,ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff:ff,"
                  "400,1000,8,100,0,7,0,1,1,,,1,,,,0\n");

    startBackend(V6);

    // We expect that this file only holds leases that belong to the
    // lease file or to the file with .completed postfix.
    Lease6Ptr lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(600, lease->cltt_);

    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::5"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(0, lease->cltt_);

    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::125"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(600, lease->cltt_);

    // Leases from the .1 and .2 files should not be loaded.
    EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::1")));
    EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2")));
    EXPECT_FALSE(lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::3")));
}

/// @brief This test checks that backend constructor refuses to load leases from the
/// lease files if the LFC is in progress.
TEST_F(MemfileLeaseMgrTest, load6LFCInProgress) {
    // Create the backend configuration.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    pmap["lfc-interval"] = "1";

    // Create a pid file holding the PID of the current process. Choosing the
    // pid of the current process guarantees that when the backend starts up
    // the process is alive.
    PIDFile pid_file(Memfile_LeaseMgr::appendSuffix(pmap["name"], Memfile_LeaseMgr::FILE_PID));
    pid_file.write();

    // There is a pid file and the process which pid is in the file is
    // running, so the backend should refuse to start.
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    ASSERT_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)),
                 DbOpenError);

    // Remove the pid file, and retry. The backend should be created.
    pid_file.deleteFile();
    ASSERT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));
}

/// @brief Verifies that LFC is automatically run during MemfileLeasemMgr construction
/// when the lease file(s) being loaded need to be upgraded.
TEST_F(MemfileLeaseMgrTest, leaseUpgrade4) {
    // Create header strings for each schema
    std::string header_1_0 =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname\n";

    std::string header_2_0 =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context\n";

    std::string header_3_0 =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    // Create 1.0 Schema current lease file with two entries for
    // the same lease
    std::string current_file_contents = header_1_0 +
        "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,\n"
        "192.0.2.2,02:02:02:02:02:02,,200,800,8,1,1,\n";
    LeaseFileIO current_file(getLeaseFilePath("leasefile4_0.csv"));
    current_file.writeFile(current_file_contents);

    // Create 1.0 Schema previous lease file, with two entries for
    // a another lease
    std::string previous_file_contents = header_1_0 +
        "192.0.2.3,03:03:03:03:03:03,,200,200,8,1,1,\n"
        "192.0.2.3,03:03:03:03:03:03,,200,800,8,1,1,\n";
    LeaseFileIO previous_file(getLeaseFilePath("leasefile4_0.csv.2"));
    previous_file.writeFile(previous_file_contents);

    // Create the backend.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    pmap["lfc-interval"] = "0";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));

    // Since lease files are loaded during lease manager
    // constructor, LFC should get launched automatically.
    // The new lease file should be 3.0 schema and have no entries
    ASSERT_TRUE(current_file.exists());
    EXPECT_EQ(header_3_0, current_file.readFile());

    // Wait for the LFC process to complete and
    // make sure it has returned an exit status of 0.
    ASSERT_TRUE(waitForProcess(*lease_mgr, 2));

    ASSERT_EQ(0, lease_mgr->getLFCExitStatus())
        << "Executing the LFC process failed: make sure that"
        " the kea-lfc program has been compiled.";

    // The LFC should have created a 3.0 schema completion file with the
    // one entry for each lease and moved it to leasefile4_0.csv.2
    LeaseFileIO input_file(getLeaseFilePath("leasefile4_0.csv.2"), false);
    ASSERT_TRUE(input_file.exists());

    // Verify cleaned, converted contents
    std::string result_file_contents = header_3_0 +
        "192.0.2.2,02:02:02:02:02:02,,200,800,8,1,1,,0,,0\n"
        "192.0.2.3,03:03:03:03:03:03,,200,800,8,1,1,,0,,0\n";
    EXPECT_EQ(result_file_contents, input_file.readFile());
}

/// @brief Verifies that LFC is automatically run during MemfileLeasemMgr construction
/// when the lease file(s) being loaded need to be upgraded.
TEST_F(MemfileLeaseMgrTest, leaseUpgrade6) {
    // Create header strings for all schemas.
    std::string header_1_0 =
        "address,duid,valid_lifetime,expire,subnet_id,"
        "pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
        "fqdn_rev,hostname\n";

    std::string header_2_0 =
        "address,duid,valid_lifetime,expire,subnet_id,"
        "pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
        "fqdn_rev,hostname,hwaddr\n";

    std::string header_3_0 =
        "address,duid,valid_lifetime,expire,subnet_id,"
        "pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
        "fqdn_rev,hostname,hwaddr,state,user_context\n";

    std::string header_4_0 =
        "address,duid,valid_lifetime,expire,subnet_id,"
        "pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
        "fqdn_rev,hostname,hwaddr,state,user_context,"
        "hwtype,hwaddr_source\n";

    std::string header_5_0 =
        "address,duid,valid_lifetime,expire,subnet_id,"
        "pref_lifetime,lease_type,iaid,prefix_len,fqdn_fwd,"
        "fqdn_rev,hostname,hwaddr,state,user_context,"
        "hwtype,hwaddr_source,pool_id\n";

    // The current lease file is schema 1.0 and has two entries for
    // the same lease
    std::string current_file_contents = header_1_0 +
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,200,"
        "8,100,0,7,0,1,1,,\n"
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
        "8,100,0,7,0,1,1,,\n";
    LeaseFileIO current_file(getLeaseFilePath("leasefile6_0.csv"));
    current_file.writeFile(current_file_contents);

    // The previous lease file is schema 2.0 and has two entries for
    // a different lease
    std::string previous_file_contents = header_2_0 +
        "2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,200,"
        "8,100,0,7,0,1,1,,11:22:33:44:55\n"
        "2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
        "8,100,0,7,0,1,1,,11:22:33:44:55\n";
    LeaseFileIO previous_file(getLeaseFilePath("leasefile6_0.csv.2"));
    previous_file.writeFile(previous_file_contents);

    // Create the backend.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    pmap["lfc-interval"] = "0";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr(new NakedMemfileLeaseMgr(pmap));

    // Since lease files are loaded during lease manager
    // constructor, LFC should get launched automatically.
    // The new lease file should been 5.0 and contain no leases.
    ASSERT_TRUE(current_file.exists());
    EXPECT_EQ(header_5_0, current_file.readFile());

    // Wait for the LFC process to complete and
    // make sure it has returned an exit status of 0.
    ASSERT_TRUE(waitForProcess(*lease_mgr, 2));

    ASSERT_EQ(0, lease_mgr->getLFCExitStatus())
        << "Executing the LFC process failed: make sure that"
        " the kea-lfc program has been compiled.";

    // The LFC should have created a 5.0 schema cleaned file with one entry
    // for each lease as leasefile6_0.csv.2
    LeaseFileIO input_file(getLeaseFilePath("leasefile6_0.csv.2"), false);
    ASSERT_TRUE(input_file.exists());

    // Verify cleaned, converted contents
    std::string result_file_contents = header_5_0 +
        "2001:db8:1::1,00:01:02:03:04:05:06:0a:0b:0c:0d:0e:0f,200,800,"
        "8,100,0,7,128,1,1,,,0,,,,0\n"
        "2001:db8:1::2,01:01:01:01:01:01:01:01:01:01:01:01:01,200,800,"
        "8,100,0,7,128,1,1,,11:22:33:44:55,0,,1,0,0\n";
    EXPECT_EQ(result_file_contents, input_file.readFile());
}

/// @brief This test verifies that the indexes of the container holding
/// DHCPv4 leases are updated correctly when a lease is updated.
TEST_F(MemfileLeaseMgrTest, lease4ContainerIndexUpdate) {

    const uint32_t seed = 12345678; // Used to initialize the random generator
    const uint32_t leases_cnt = 100; // Number of leases generated per round.
    const uint32_t updates_cnt = 5; // Number of times existing leases are updated

    const string leasefile(getLeaseFilePath("leasefile4_0.csv"));

    std::string dbaccess = "universe=4 type=memfile persist=true lfc-interval=0 name=";
    dbaccess += leasefile;

    LeaseMgrFactory::create(dbaccess);

    srand(seed);

    IOAddress addr("10.0.0.1"); // Let's generate leases sequentially

    // Recreate Memfile_LeaseMgr.
    LeaseMgrFactory::destroy();
    ASSERT_NO_THROW(LeaseMgrFactory::create(dbaccess));
    lmptr_ = &(LeaseMgrFactory::instance());

    // We will store addresses here, so it will be easier to randomly
    // pick a lease.
    std::vector<IOAddress> lease_addresses;

    // Generate random leases. We remember their addresses in
    // lease_addresses.
    for (uint32_t i = 0; i < leases_cnt; ++i) {
        Lease4Ptr lease = initiateRandomLease4(addr);
        lease_addresses.push_back(addr);
        ASSERT_NO_THROW(lmptr_->addLease(lease));
        addr = IOAddress::increase(addr);
    }

    // Check that we inserted correct number of leases.
    ASSERT_EQ(leases_cnt, lease_addresses.size());

    // Now, conduct updates. We call initiateRandomLease4(), so most
    // of the fields are randomly changed. The only constant field
    // is the address.
    for (uint32_t i = 0; i < updates_cnt; ++i) {
        uint32_t offset = random() % lease_addresses.size();
        Lease4Ptr existing(lmptr_->getLease4(lease_addresses[offset]));
        Lease4Ptr updated(initiateRandomLease4(lease_addresses[offset]));

        // Update a lease with new data but preserve lease address.
        // This update should also cause lease container indexes to
        // be updated.
        ASSERT_NO_THROW(lmptr_->updateLease4(updated))
            << "Attempt " << i << " out of " << updates_cnt
            << ":Failed to update lease for address "
            << lease_addresses[offset];
    }

    // Re-create lease manager to cause it to reload leases
    // from a lease file. We want to make sure that lease
    // container is rebuilt correctly and the indexes are
    // consistent with lease information held.
    ASSERT_NO_THROW({
        // Recreate Memfile_LeaseMgr.
        LeaseMgrFactory::destroy();
        LeaseMgrFactory::create(dbaccess);
        lmptr_ = &(LeaseMgrFactory::instance());
    });

    // Ok, let's check if the leases are really accessible.
    // First, build an array of leases. Get them by address.
    // This should work in general, as we haven't updated the addresses.
    std::vector<Lease4Ptr> leases;
    for (uint32_t i = 0; i < lease_addresses.size(); ++i) {
        Lease4Ptr from_mgr = lmptr_->getLease4(lease_addresses[i]);
        ASSERT_TRUE(from_mgr) << "Lease for address " << lease_addresses[i].toText()
                              << " not found";
        leases.push_back(from_mgr);
    }

    ASSERT_EQ(leases_cnt, leases.size());

    // Now do the actual checks.
    for (uint32_t i = 0; i < leases.size(); ++i) {
        Lease4Ptr tested = leases[i];

        // Get the lease by different access patterns.
        // In properly working lease manager all queries should return
        // exactly the same lease.

        std::string error_desc = " which indicates that the lease indexes were"
            " not updated correctly when the lease was updated.";

        // Retrieve lease by address.
        Lease4Ptr lease_by_address = lmptr_->getLease4(tested->addr_);
        ASSERT_TRUE(lease_by_address)
            << "Lease " << tested->addr_.toText()
            << " not found by getLease4(addr)"
            << error_desc;
        detailCompareLease(tested, lease_by_address);

        // Retrieve lease by HW address and subnet id.
        Lease4Ptr lease_by_hwaddr_subnet = lmptr_->getLease4(*tested->hwaddr_,
                                                             tested->subnet_id_);
        ASSERT_TRUE(lease_by_hwaddr_subnet)
            << "Lease " << tested->addr_.toText()
            << " not found by getLease4(hwaddr, subnet_id)"
            << error_desc;
        detailCompareLease(tested, lease_by_hwaddr_subnet);

        // Retrieve lease by client identifier and subnet id.
        Lease4Ptr lease_by_clientid_subnet = lmptr_->getLease4(*tested->client_id_,
                                                               tested->subnet_id_);
        ASSERT_TRUE(lease_by_clientid_subnet)
            << "Lease " << tested->addr_.toText()
            << " not found by getLease4(clientid, subnet_id)"
            << error_desc;
        detailCompareLease(tested, lease_by_clientid_subnet);

        // Retrieve lease by HW address.
        Lease4Collection leases_by_hwaddr = lmptr_->getLease4(*tested->hwaddr_);
        ASSERT_EQ(1, leases_by_hwaddr.size());
        detailCompareLease(tested, leases_by_hwaddr[0]);

        // Retrieve lease by client identifier.
        Lease4Collection leases_by_client_id = lmptr_->getLease4(*tested->client_id_);
        ASSERT_EQ(1, leases_by_client_id.size());
        detailCompareLease(tested, leases_by_client_id[0]);
    }
}

/// @brief This test verifies that the indexes of the container holding
/// DHCPv4 leases are updated correctly when a lease is updated.
TEST_F(MemfileLeaseMgrTest, lease6ContainerIndexUpdate) {

    const uint32_t seed = 12345678; // Used to initialize the random generator
    const uint32_t leases_cnt = 100; // Number of leases generated per round.
    const uint32_t updates_cnt = 5; // Number of times existing leases are updated

    const string leasefile(getLeaseFilePath("leasefile6_0.csv"));

    std::string dbaccess = "universe=6 type=memfile persist=true lfc-interval=0 name=";
    dbaccess += leasefile;

    LeaseMgrFactory::create(dbaccess);

    srand(seed);

    IOAddress addr("2001:db8:1::1"); // Let's generate leases sequentially

    // Recreate Memfile_LeaseMgr.
    LeaseMgrFactory::destroy();
    ASSERT_NO_THROW(LeaseMgrFactory::create(dbaccess));
    lmptr_ = &(LeaseMgrFactory::instance());

    // We will store addresses here, so it will be easier to randomly
    // pick a lease.
    std::vector<IOAddress> lease_addresses;

    // Generate random leases. We remember their addresses in
    // lease_addresses.
    for (uint32_t i = 0; i < leases_cnt; ++i) {
        Lease6Ptr lease = initiateRandomLease6(addr);
        lease_addresses.push_back(addr);
        ASSERT_NO_THROW(lmptr_->addLease(lease));
        addr = IOAddress::increase(addr);
    }

    // Check that we inserted correct number of leases.
    ASSERT_EQ(leases_cnt, lease_addresses.size());

    // Now, conduct updates. We call initiateRandomLease6(), so most
    // of the fields are randomly changed. The only constant field
    // is the address.
    for (uint32_t i = 0; i < updates_cnt; ++i) {
        uint32_t offset = random() % lease_addresses.size();
        Lease6Ptr existing(lmptr_->getLease6(Lease::TYPE_NA,
                                             lease_addresses[offset]));
        Lease6Ptr updated(initiateRandomLease6(lease_addresses[offset]));

        // Update a lease with new data but preserve lease address.
        // This update should also cause lease container indexes to
        // be updated.
        ASSERT_NO_THROW(lmptr_->updateLease6(updated))
            << "Attempt " << i << " out of " << updates_cnt
            << ":Failed to update lease for address "
            << lease_addresses[offset];
    }

    // Re-create lease manager to cause it to reload leases
    // from a lease file. We want to make sure that lease
    // container is rebuilt correctly and the indexes are
    // consistent with lease information held.
    ASSERT_NO_THROW({
        // Recreate Memfile_LeaseMgr.
        LeaseMgrFactory::destroy();
        LeaseMgrFactory::create(dbaccess);
        lmptr_ = &(LeaseMgrFactory::instance());
    });

    // Ok, let's check if the leases are really accessible.
    // First, build an array of leases. Get them by address.
    // This should work in general, as we haven't updated the addresses.
    std::vector<Lease6Ptr> leases;
    for (uint32_t i = 0; i < lease_addresses.size(); ++i) {
        Lease6Ptr from_mgr = lmptr_->getLease6(Lease::TYPE_NA,
                                               lease_addresses[i]);
        ASSERT_TRUE(from_mgr) << "Lease for address " << lease_addresses[i].toText()
                              << " not found";
        leases.push_back(from_mgr);
    }

    ASSERT_EQ(leases_cnt, leases.size());

    // Now do the actual checks.
    for (uint32_t i = 0; i < leases.size(); ++i) {
        Lease6Ptr tested = leases[i];

        // Get the lease by different access patterns.
        // In properly working lease manager all queries should return
        // exactly the same lease.

        std::string error_desc = " which indicates that the lease indexes were"
            " not updated correctly when the lease was updated.";

        // Retrieve lease by address.
        Lease6Ptr lease_by_address = lmptr_->getLease6(Lease::TYPE_NA,
                                                       tested->addr_);
        ASSERT_TRUE(lease_by_address)
            << "Lease " << tested->addr_.toText()
            << " not found by getLease6(addr)"
            << error_desc;
        detailCompareLease(tested, lease_by_address);

        // Retrieve lease by type, DUID, IAID.
        Lease6Collection leases_by_duid_iaid = lmptr_->getLeases6(tested->type_,
                                                                  *tested->duid_,
                                                                  tested->iaid_);
        ASSERT_EQ(1, leases_by_duid_iaid.size());
        ASSERT_TRUE(leases_by_duid_iaid[0])
            << "Lease " << tested->addr_.toText()
            << " not found by getLease6(type, duid, iaid)"
            << error_desc;
        detailCompareLease(tested, leases_by_duid_iaid[0]);

        // Retrieve lease by type, DUID, IAID, subnet identifier.
        Lease6Collection leases_by_duid_iaid_subnet =
            lmptr_->getLeases6(tested->type_, *tested->duid_,
                               tested->iaid_, tested->subnet_id_);
        ASSERT_EQ(1, leases_by_duid_iaid_subnet.size());
        ASSERT_TRUE(leases_by_duid_iaid_subnet[0])
            << "Lease " << tested->addr_.toText()
            << " not found by getLease6(type, duid, iaid, subnet_id)"
            << error_desc;
        detailCompareLease(tested, leases_by_duid_iaid_subnet[0]);
    }
}

/// @brief Verifies that IPv4 lease statistics can be recalculated.
TEST_F(MemfileLeaseMgrTest, recountLeaseStats4) {
    startBackend(V4);
    testRecountLeaseStats4();
}

/// @brief Verifies that IPv6 lease statistics can be recalculated.
TEST_F(MemfileLeaseMgrTest, recountLeaseStats6) {
    startBackend(V6);
    testRecountLeaseStats6();
}

/// @brief Tests that leases from specific subnet can be removed.
TEST_F(MemfileLeaseMgrTest, wipeLeases4) {
    startBackend(V4);
    testWipeLeases4();
}

/// @brief Tests that leases from specific subnet can be removed.
TEST_F(MemfileLeaseMgrTest, wipeLeases6) {
    startBackend(V6);
    testWipeLeases6();
}

/// @brief Tests v4 lease stats query variants.
TEST_F(MemfileLeaseMgrTest, leaseStatsQuery4) {
    startBackend(V4);
    testLeaseStatsQuery4();
}

/// @brief Tests v6 lease stats query variants.
TEST_F(MemfileLeaseMgrTest, leaseStatsQuery6) {
    startBackend(V6);
    testLeaseStatsQuery6();
}

/// @brief Tests v4 lease stats to be attributed to the wrong subnet.
TEST_F(MemfileLeaseMgrTest, leaseStatsQueryAttribution4) {
    startBackend(V4);
    testLeaseStatsQueryAttribution4();
}

/// @brief Tests v6 lease stats to be attributed to the wrong subnet.
TEST_F(MemfileLeaseMgrTest, leaseStatsQueryAttribution6) {
    startBackend(V6);
    testLeaseStatsQueryAttribution6();
}

TEST_F(MemfileLeaseMgrTest, checkVersion4) {
    // Create the backend.
    DatabaseConnection::ParameterMap parameters;
    parameters["type"] = "memfile";
    parameters["universe"] = "4";
    parameters["name"] = getLeaseFilePath("leasefile4_0.csv");
    std::unique_ptr<NakedMemfileLeaseMgr> lease_mgr;
    ASSERT_NO_THROW_LOG(lease_mgr.reset(new NakedMemfileLeaseMgr(parameters)));

    // Get the backend version.
    auto const& backend_version(lease_mgr->getVersion());
    std::stringstream s;
    s << backend_version.first << '.' << backend_version.second;

    // Get the CSV version.
    CSVLeaseFile4 f(getLeaseFilePath("leasefile4_0.csv"));

    // They should match.
    EXPECT_EQ(s.str(), f.getSchemaVersion());

    // DBVersion too.
    EXPECT_EQ("Memfile backend " + s.str(),
              lease_mgr->getDBVersionInternal(Memfile_LeaseMgr::V4));
}

TEST_F(MemfileLeaseMgrTest, checkVersion6) {
    // Create the backend.
    DatabaseConnection::ParameterMap parameters;
    parameters["type"] = "memfile";
    parameters["universe"] = "6";
    parameters["name"] = getLeaseFilePath("leasefile6_0.csv");
    std::unique_ptr<NakedMemfileLeaseMgr> lease_mgr;
    ASSERT_NO_THROW_LOG(lease_mgr.reset(new NakedMemfileLeaseMgr(parameters)));

    // Get the backend version.
    auto const& backend_version(lease_mgr->getVersion());
    std::stringstream s;
    s << backend_version.first << '.' << backend_version.second;

    // Get the CSV version.
    CSVLeaseFile6 f(getLeaseFilePath("leasefile6_0.csv"));

    // They should match.
    EXPECT_EQ(s.str(), f.getSchemaVersion());

    // DBVersion too.
    EXPECT_EQ("Memfile backend " + s.str(),
              lease_mgr->getDBVersionInternal(Memfile_LeaseMgr::V6));
}

/// @brief Checks that complex user context can be read in v4.
TEST_F(MemfileLeaseMgrTest, v4UserContext) {
    // Add some leases to the CSV file.
    LeaseFileIO io(getLeaseFilePath("leasefile4_0.csv"));
    io.writeFile(
        "address,hwaddr,client_id,valid_lifetime,expire,subnet_id,"
        "fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"

        "192.0.0.1,01:01:01:01:01:01,,100,100,1,1,1,,1,"
        "{},0\n"

        "192.0.0.2,02:02:02:02:02:02,,200,400,1,1,1,,0,"
        "{ \"comment\": \"this lease is for the kitchen computer\"},0\n"

        // The next lines have escaped commas in user context.

        "192.0.0.4,04:04:04:04:04:04,,400,1600,1,1,1,,0,"
        "{ \"comment\": \"this lease is for the mainframe computer\"&#x2c"
        "  \"comment2\": \"don't release it\" },0\n"

        "192.0.0.8,08:08:08:08:08:08,,800,6400,1,1,1,,0,"
        "{ \"a\": \"b\"&#x2c \"c\": { \"d\": 1&#x2c\"e\": 2 } },0\n"
    );

    // Not sanitize user contexts.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_NONE);

    startBackend(V4);

    // Check the lease with no key-value pairs in the user context.
    Lease4Ptr lease(lmptr_->getLease4(IOAddress("192.0.0.1")));
    ASSERT_TRUE(lease);
    EXPECT_EQ(
        lease->toText(),
        "Address:       192.0.0.1\n"
        "Valid life:    100\n"
        "Cltt:          0\n"
        "Hardware addr: 01:01:01:01:01:01\n"
        "Client id:     (none)\n"
        "Subnet ID:     1\n"
        "Pool ID:       0\n"
        "State:         declined\n"
        "Relay ID:      (none)\n"
        "Remote ID:     (none)\n"
        "User context:  {  }\n"
    );

    // Check the lease with one key-value pair in the user context.
    lease = lmptr_->getLease4(IOAddress("192.0.0.2"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(
        lease->toText(),
        "Address:       192.0.0.2\n"
        "Valid life:    200\n"
        "Cltt:          200\n"
        "Hardware addr: 02:02:02:02:02:02\n"
        "Client id:     (none)\n"
        "Subnet ID:     1\n"
        "Pool ID:       0\n"
        "State:         default\n"
        "Relay ID:      (none)\n"
        "Remote ID:     (none)\n"
        "User context:  { \"comment\": \"this lease is for the kitchen computer\" }\n"
    );

    // Check the lease with two key-value pairs in the user context.
    lease = lmptr_->getLease4(IOAddress("192.0.0.4"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(
        lease->toText(),
        "Address:       192.0.0.4\n"
        "Valid life:    400\n"
        "Cltt:          1200\n"
        "Hardware addr: 04:04:04:04:04:04\n"
        "Client id:     (none)\n"
        "Subnet ID:     1\n"
        "Pool ID:       0\n"
        "State:         default\n"
        "Relay ID:      (none)\n"
        "Remote ID:     (none)\n"
        "User context:  "
        "{ \"comment\": \"this lease is for the mainframe computer\", "
        "\"comment2\": \"don't release it\" }\n"
    );

    // Check the lease with nested key-value pairs in the user context.
    lease = lmptr_->getLease4(IOAddress("192.0.0.8"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(
        lease->toText(),
        "Address:       192.0.0.8\n"
        "Valid life:    800\n"
        "Cltt:          5600\n"
        "Hardware addr: 08:08:08:08:08:08\n"
        "Client id:     (none)\n"
        "Subnet ID:     1\n"
        "Pool ID:       0\n"
        "State:         default\n"
        "Relay ID:      (none)\n"
        "Remote ID:     (none)\n"
        "User context:  { \"a\": \"b\", \"c\": { \"d\": 1, \"e\": 2 } }\n"
    );
}

/// @brief Checks that complex user context can be read in v6.
TEST_F(MemfileLeaseMgrTest, v6UserContext) {
    // Add some leases to the CSV file.
    LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
    io.writeFile(
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"

        "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
        "400,1000,8,100,0,7,0,1,1,,,1,"
        "{},,,0\n"

        "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"comment\": \"this lease is for the kitchen computer\"},,,0\n"

        // The next lines have escaped commas in user context.

        "2001:db8:1::4,04:04:04:04:04:04:04:04:04:04:04:04:04,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"comment\": \"this lease is for the mainframe computer\"&#x2c"
        "  \"comment2\": \"don't release it\" },,,0\n"

        "2001:db8:1::8,08:08:08:08:08:08:08:08:08:08:08:08:08,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"a\": \"b\"&#x2c \"c\": { \"d\": 1&#x2c\"e\": 2 } },,,0\n"
    );

    // Not sanitize user contexts.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_NONE);

    startBackend(V6);

    // Check the lease with no key-value pairs in the user context.
    Lease6Ptr lease(
        lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::1")));
    ASSERT_TRUE(lease);
    EXPECT_EQ(
        lease->toText(),
        "Type:          IA_NA(0)\n"
        "Address:       2001:db8:1::1\n"
        "Prefix length: 128\n"
        "IAID:          7\n"
        "Pref life:     100\n"
        "Valid life:    400\n"
        "Cltt:          600\n"
        "DUID:          01:01:01:01:01:01:01:01:01:01:01:01:01\n"
        "Hardware addr: (none)\n"
        "Subnet ID:     8\n"
        "Pool ID:       0\n"
        "State:         declined\n"
        "User context:  {  }\n"
    );

    // Check the lease with one key-value pair in the user context.
    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(
        lease->toText(),
        "Type:          IA_NA(0)\n"
        "Address:       2001:db8:1::2\n"
        "Prefix length: 128\n"
        "IAID:          7\n"
        "Pref life:     100\n"
        "Valid life:    200\n"
        "Cltt:          0\n"
        "DUID:          02:02:02:02:02:02:02:02:02:02:02:02:02\n"
        "Hardware addr: (none)\n"
        "Subnet ID:     8\n"
        "Pool ID:       0\n"
        "State:         declined\n"
        "User context:  { \"comment\": \"this lease is for the kitchen computer\" }\n"
    );

    // Check the lease with two key-value pairs in the user context.
    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::4"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(
        lease->toText(),
        "Type:          IA_NA(0)\n"
        "Address:       2001:db8:1::4\n"
        "Prefix length: 128\n"
        "IAID:          7\n"
        "Pref life:     100\n"
        "Valid life:    200\n"
        "Cltt:          0\n"
        "DUID:          04:04:04:04:04:04:04:04:04:04:04:04:04\n"
        "Hardware addr: (none)\n"
        "Subnet ID:     8\n"
        "Pool ID:       0\n"
        "State:         declined\n"
        "User context:  { \"comment\": \"this lease is for the mainframe computer\","
        " \"comment2\": \"don't release it\" }\n"
    );

    // Check the lease with nested key-value pairs in the user context.
    lease = lmptr_->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::8"));
    ASSERT_TRUE(lease);
    EXPECT_EQ(
        lease->toText(),
        "Type:          IA_NA(0)\n"
        "Address:       2001:db8:1::8\n"
        "Prefix length: 128\n"
        "IAID:          7\n"
        "Pref life:     100\n"
        "Valid life:    200\n"
        "Cltt:          0\n"
        "DUID:          08:08:08:08:08:08:08:08:08:08:08:08:08\n"
        "Hardware addr: (none)\n"
        "Subnet ID:     8\n"
        "Pool ID:       0\n"
        "State:         declined\n"
        "User context:  { \"a\": \"b\", \"c\": { \"d\": 1, \"e\": 2 } }\n"
    );
}

/// @brief Checks that various hardware information is correctly imported from a
/// CSV file.
TEST_F(MemfileLeaseMgrTest, testHWAddr) {
    // Add some leases to the CSV file.
    LeaseFileIO io(getLeaseFilePath("leasefile6_0.csv"));
    std::stringstream contents;
    contents << "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
                "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
                "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n";

    // Create combinations with all valid values except for 255 which is an
    // unused value for both hwtype and hwaddr_source, but lease construction
    // doesn't complain in that case either.
    std::vector<uint16_t> const hwtypes{0, 1, 6, 8, 255};
    std::vector<uint32_t> const hwsources{
        0xffffffff, 0x00000000, 0x00000001, 0x00000002, 0x00000004, 0x00000008,
        0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x000000ff};
    int i = 0;
    for (uint16_t hwtype : hwtypes) {
        for (uint32_t hwsource : hwsources) {
            std::stringstream hex;
            hex << std::hex << std::setw(2) << std::setfill('0') << i;
            contents << "2001:db8:1::" << hex.str()
                     << ",00:00:00:00:00:" << hex.str()
                     << std::dec << ",7200,8000,1,3600,0,1,128,0,0,,ff:ff:ff:ff:ff:"
                     << hex.str() << ",1,," << hwtype << "," << hwsource << ",0\n";
            ++i;
        }
    }

    io.writeFile(contents.str());
    startBackend(V6);

    // Check leases.
    i = 0;
    for (uint16_t hwtype : hwtypes) {
        for (uint32_t hwsource : hwsources) {
            std::stringstream hex;
            hex << std::hex << std::setw(2) << std::setfill('0') << i;
            IOAddress address("2001:db8:1::" + hex.str());
            Lease6Ptr lease(lmptr_->getLease6(Lease::TYPE_NA, address.toText()));

            ASSERT_TRUE(lease);
            EXPECT_EQ(lease->toText(),
                    "Type:          IA_NA(0)\n"
                    "Address:       " + address.toText() + "\n"
                    "Prefix length: 128\n"
                    "IAID:          1\n"
                    "Pref life:     3600\n"
                    "Valid life:    7200\n"
                    "Cltt:          800\n"
                    "DUID:          00:00:00:00:00:" + hex.str() + "\n"
                    "Hardware addr: ff:ff:ff:ff:ff:" + hex.str() + "\n"
                    "Subnet ID:     1\n"
                    "Pool ID:       0\n"
                    "State:         declined\n");
            ASSERT_TRUE(lease->hwaddr_);
            EXPECT_EQ(lease->hwaddr_->htype_, hwtype);
            EXPECT_EQ(lease->hwaddr_->source_, hwsource);
            ++i;
        }
    }
}

// Verifies that isJsonSupported() returns true for Memfile.
TEST_F(MemfileLeaseMgrTest, isJsonSupported4) {
    startBackend(V4);
    bool json_supported;
    ASSERT_NO_THROW_LOG(json_supported = LeaseMgrFactory::instance().isJsonSupported());
    ASSERT_TRUE(json_supported);
}

// Verifies that isJsonSupported() returns true for Memfile.
TEST_F(MemfileLeaseMgrTest, isJsonSupported6) {
    startBackend(V6);
    bool json_supported;
    ASSERT_NO_THROW_LOG(json_supported = LeaseMgrFactory::instance().isJsonSupported());
    ASSERT_TRUE(json_supported);
}

// Verifies that v4 class lease counts are correctly adjusted
// when leases have class lists.
TEST_F(MemfileLeaseMgrTest, classLeaseCount4) {
    startBackend(V4);
    testClassLeaseCount4();
}

// Verifies that v6 IA_NA class lease counts are correctly adjusted
// when leases have class lists.
TEST_F(MemfileLeaseMgrTest, classLeaseCount6_NA) {
    startBackend(V6);
    testClassLeaseCount6(Lease::TYPE_NA);
}

// Verifies that v6 IA_PD class lease counts are correctly adjusted
// when leases have class lists.
TEST_F(MemfileLeaseMgrTest, classLeaseCount6_PD) {
    startBackend(V6);
    testClassLeaseCount6(Lease::TYPE_PD);
}

// brief Checks that a null user context allows allocation.
TEST_F(MemfileLeaseMgrTest, checkLimitsNull4) {
    startBackend(V4);
    std::string text;
    ASSERT_NO_THROW_LOG(text = LeaseMgrFactory::instance().checkLimits4(nullptr));
    EXPECT_TRUE(text.empty());
}

// brief Checks that a null user context allows allocation.
TEST_F(MemfileLeaseMgrTest, checkLimitsNull6) {
    startBackend(V6);
    std::string text;
    ASSERT_NO_THROW_LOG(text = LeaseMgrFactory::instance().checkLimits6(nullptr));
    EXPECT_TRUE(text.empty());
}

// Checks a few v4 lease limit checking scenarios.
TEST_F(MemfileLeaseMgrTest, checkLimits4) {
    startBackend(V4);
    testLeaseLimits4();
}

// Checks a few v6 lease limit checking scenarios.
TEST_F(MemfileLeaseMgrTest, checkLimits6) {
    startBackend(V6);
    testLeaseLimits6();
}

// Verifies that v4 class lease counts can be recounted.
TEST_F(MemfileLeaseMgrTest, classLeaseRecount4) {
    startBackend(V4);

    // Create a subnet
    CfgSubnets4Ptr cfg = CfgMgr::instance().getStagingCfg()->getCfgSubnets4();
    Subnet4Ptr subnet;
    Pool4Ptr pool;

    subnet.reset(new Subnet4(IOAddress("192.0.1.0"), 24, 1, 2, 3, 777));
    pool.reset(new Pool4(IOAddress("192.0.1.0"), 24));
    subnet->addPool(pool);
    cfg->add(subnet);

    // We need a Memfile_LeaseMgr pointer to access recount and clear functions.
    Memfile_LeaseMgr* memfile_mgr = dynamic_cast<Memfile_LeaseMgr*>(lmptr_);
    ASSERT_TRUE(memfile_mgr);

    // Verify class lease counts are zero.
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("water"));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("melon"));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("slice"));

    // Structure that describes a recipe for a lease.
    struct Recipe {
        std::string address_;
        uint32_t state_;
        std::list<ClientClass> classes_;
    };

    // List of lease recipes.
    std::list<Recipe> recipes{
        { "192.0.1.100", Lease::STATE_DEFAULT, {"water", "slice"} },
        { "192.0.1.101", Lease::STATE_DEFAULT, {"melon"} },
        { "192.0.1.102", Lease::STATE_DEFAULT, {"melon", "slice"} }
    };

    // Bake all the leases.
    for (auto const& recipe : recipes) {
        ElementPtr ctx = makeContextWithClasses(recipe.classes_);
        ASSERT_TRUE(makeLease4(recipe.address_, 777, recipe.state_, ctx));
    }

    // Verify counts are as expected.
    EXPECT_EQ(1, memfile_mgr->getClassLeaseCount("water"));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("melon"));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("slice"));

    // Clear counts
    ASSERT_NO_THROW_LOG(memfile_mgr->clearClassLeaseCounts());

    // Verify counts are zero.
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("water"));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("melon"));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("slice"));

    // Recount
    ASSERT_NO_THROW_LOG(memfile_mgr->recountClassLeases4());

    // Verify counts are recounted correctly.
    EXPECT_EQ(1, memfile_mgr->getClassLeaseCount("water"));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("melon"));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("slice"));
}

// Verifies that v6 class lease counts can be recounted.
TEST_F(MemfileLeaseMgrTest, classLeaseRecount6) {
    startBackend(V6);

    // Create a subnet
    CfgSubnets6Ptr cfg = CfgMgr::instance().getStagingCfg()->getCfgSubnets6();
    Subnet6Ptr subnet;
    Pool6Ptr pool;

    subnet.reset(new Subnet6(IOAddress("3001:1::"), 64, 1, 2, 3, 4, 777));
    pool.reset(new Pool6(Lease::TYPE_NA, IOAddress("3001:1::"),
                         IOAddress("3001:1::FF")));
    subnet->addPool(pool);

    pool.reset(new Pool6(Lease::TYPE_PD, IOAddress("3001:1:2::"), 96, 112));
    subnet->addPool(pool);
    cfg->add(subnet);

    // We need a Memfile_LeaseMgr pointer to access recount and clear functions.
    Memfile_LeaseMgr* memfile_mgr = dynamic_cast<Memfile_LeaseMgr*>(lmptr_);
    ASSERT_TRUE(memfile_mgr);

    // Verify class lease counts are zero.
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("water", Lease::TYPE_NA));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("melon", Lease::TYPE_NA));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("slice", Lease::TYPE_NA));

    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("grapes", Lease::TYPE_PD));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("wrath", Lease::TYPE_PD));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("slice", Lease::TYPE_PD));

    // Structure that describes a recipe for a lease.
    struct Recipe {
        Lease::Type ltype_;
        std::string address_;
        uint32_t prefix_len_;
        uint32_t state_;
        std::list<ClientClass> classes_;
    };

    // List of lease recipes.
    std::list<Recipe> recipes{
        { Lease::TYPE_NA, "3001::1", 128, Lease::STATE_DEFAULT, {"water", "slice"} },
        { Lease::TYPE_NA, "3001::2", 128, Lease::STATE_DEFAULT, {"melon"} },
        { Lease::TYPE_NA, "3001::3", 128, Lease::STATE_DEFAULT, {"melon", "slice"} },

        { Lease::TYPE_PD, "3001:1:2:0100::", 112, Lease::STATE_DEFAULT, {"grapes", "slice"} },
        { Lease::TYPE_PD, "3001:1:2:0200::", 112, Lease::STATE_DEFAULT, {"wrath"} },
        { Lease::TYPE_PD, "3001:1:2:0300::", 112, Lease::STATE_DEFAULT, {"wrath", "slice"} },
    };

    // Bake all the leases.
    for (auto const& recipe : recipes) {
        ElementPtr ctx = makeContextWithClasses(recipe.classes_);
        ASSERT_TRUE(makeLease6(recipe.ltype_, recipe.address_, recipe.prefix_len_, 777, recipe.state_, ctx));
    }

    // Verify counts are as expected.
    EXPECT_EQ(1, memfile_mgr->getClassLeaseCount("water", Lease::TYPE_NA));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("melon", Lease::TYPE_NA));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("slice", Lease::TYPE_NA));

    EXPECT_EQ(1, memfile_mgr->getClassLeaseCount("grapes", Lease::TYPE_PD));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("wrath", Lease::TYPE_PD));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("slice", Lease::TYPE_PD));

    // Clear counts
    ASSERT_NO_THROW_LOG(memfile_mgr->clearClassLeaseCounts());

    // Verify counts are zero.
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("water", Lease::TYPE_NA));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("melon", Lease::TYPE_NA));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("slice", Lease::TYPE_NA));

    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("grapes", Lease::TYPE_PD));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("wrath", Lease::TYPE_PD));
    EXPECT_EQ(0, memfile_mgr->getClassLeaseCount("slice", Lease::TYPE_PD));

    // Recount
    ASSERT_NO_THROW_LOG(memfile_mgr->recountClassLeases6());

    // Verify counts are recounted correctly.
    EXPECT_EQ(1, memfile_mgr->getClassLeaseCount("water", Lease::TYPE_NA));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("melon", Lease::TYPE_NA));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("slice", Lease::TYPE_NA));

    EXPECT_EQ(1, memfile_mgr->getClassLeaseCount("grapes", Lease::TYPE_PD));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("wrath", Lease::TYPE_PD));
    EXPECT_EQ(2, memfile_mgr->getClassLeaseCount("slice", Lease::TYPE_PD));
}

/// @brief Class derived from @c Memfile_LeaseMgr to test write to file.
class WFMemfileLeaseMgr : public Memfile_LeaseMgr {
public:

    /// @brief Constructor.
    WFMemfileLeaseMgr(const DatabaseConnection::ParameterMap& parameters)
        : Memfile_LeaseMgr(parameters) {
    }

    using Memfile_LeaseMgr::lease_file4_;
    using Memfile_LeaseMgr::lease_file6_;
};

/// @brief Check if writeLease fails on bad file name (v4).
TEST_F(MemfileLeaseMgrTest, badWriteLease4) {
    startBackend(V4);
    string expected = "unable to open '/this/does/not/exist'";
    EXPECT_THROW_MSG(lmptr_->writeLeases4("/this/does/not/exist"),
                     CSVFileError, expected);
}

/// @brief Check if writeLease fails on bad file name (v4+MT).
TEST_F(MemfileLeaseMgrTest, badWriteLease4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    string expected = "unable to open '/this/does/not/exist'";
    EXPECT_THROW_MSG(lmptr_->writeLeases4("/this/does/not/exist"),
                     CSVFileError, expected);
}

/// @brief Check if writeLease fails on bad file name (v6).
TEST_F(MemfileLeaseMgrTest, badWriteLease6) {
    startBackend(V6);
    string expected = "unable to open '/this/does/not/exist'";
    EXPECT_THROW_MSG(lmptr_->writeLeases6("/this/does/not/exist"),
                     CSVFileError, expected);
}

/// @brief Check if writeLease fails on bad file name (v6+MT).
TEST_F(MemfileLeaseMgrTest, badWriteLease6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    string expected = "unable to open '/this/does/not/exist'";
    EXPECT_THROW_MSG(lmptr_->writeLeases6("/this/does/not/exist"),
                     CSVFileError, expected);
}

/// @brief Check writeLease basic scenario (v4).
TEST_F(MemfileLeaseMgrTest, basicWriteLease4) {
    startBackend(V4);

    // Empty database should give a header only file.
    string header =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    string filename = getLeaseFilePath("backup.csv");
    LeaseFileIO file(filename);
    file.removeFile();
    extra_files_.push_back(filename);
    ostringstream b;
    b << filename << ".bak" << getpid();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lmptr_->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease4Ptr> leases = createLeases4();

    // Add leases.
    EXPECT_TRUE(lmptr_->addLease(leases[1]));
    EXPECT_TRUE(lmptr_->addLease(leases[2]));
    EXPECT_TRUE(lmptr_->addLease(leases[3]));

    // Try again.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_NO_THROW(lmptr_->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lmptr_->deleteLease(leases[2]));
    EXPECT_NO_THROW(lmptr_->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());
}

/// @brief Check writeLease basic scenario (v4+MT).
TEST_F(MemfileLeaseMgrTest, basicWriteLease4MultiThread) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);

    // Empty database should give a header only file.
    string header =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    string filename = getLeaseFilePath("backup.csv");
    LeaseFileIO file(filename);
    file.removeFile();
    extra_files_.push_back(filename);
    ostringstream b;
    b << filename << ".bak" << getpid();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lmptr_->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease4Ptr> leases = createLeases4();

    // Add leases.
    EXPECT_TRUE(lmptr_->addLease(leases[1]));
    EXPECT_TRUE(lmptr_->addLease(leases[2]));
    EXPECT_TRUE(lmptr_->addLease(leases[3]));

    // Try again.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_NO_THROW(lmptr_->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lmptr_->deleteLease(leases[2]));
    EXPECT_NO_THROW(lmptr_->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());
}

/// @brief Check writeLease basic scenario (v6).
TEST_F(MemfileLeaseMgrTest, basicWriteLease6) {
    startBackend(V6);

    // empty database should give a header only file.
    string header =
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n";

    string filename = getLeaseFilePath("backup.csv");
    LeaseFileIO file(filename);
    file.removeFile();
    extra_files_.push_back(filename);
    ostringstream b;
    b << filename << ".bak" << getpid();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lmptr_->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease6Ptr> leases = createLeases6();

    // Add leases.
    EXPECT_TRUE(lmptr_->addLease(leases[1]));
    EXPECT_TRUE(lmptr_->addLease(leases[2]));
    EXPECT_TRUE(lmptr_->addLease(leases[3]));

    // Try again.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_NO_THROW(lmptr_->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lmptr_->deleteLease(leases[2]));
    EXPECT_NO_THROW(lmptr_->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());
}

/// @brief Check writeLease basic scenario (v6+MT).
TEST_F(MemfileLeaseMgrTest, basicWriteLease6MultiThread) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);

    // empty database should give a header only file.
    string header =
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n";

    string filename = getLeaseFilePath("backup.csv");
    LeaseFileIO file(filename);
    file.removeFile();
    extra_files_.push_back(filename);
    ostringstream b;
    b << filename << ".bak" << getpid();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lmptr_->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease6Ptr> leases = createLeases6();

    // Add leases.
    EXPECT_TRUE(lmptr_->addLease(leases[1]));
    EXPECT_TRUE(lmptr_->addLease(leases[2]));
    EXPECT_TRUE(lmptr_->addLease(leases[3]));

    // Try again.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_NO_THROW(lmptr_->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lmptr_->deleteLease(leases[2]));
    EXPECT_NO_THROW(lmptr_->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());
}

/// @brief Check if writeLease can overwrite the lease file (v4).
TEST_F(MemfileLeaseMgrTest, overWriteLease4) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["lfc-interval"] = "0";
    pmap["persist"] = "true";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    boost::scoped_ptr<WFMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new WFMemfileLeaseMgr(pmap)));

    // Empty database should give a header only file.
    string header =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    ASSERT_TRUE(lease_mgr->lease_file4_);
    string filename = lease_mgr->lease_file4_->getFilename();
    LeaseFileIO file(filename);
    ostringstream b;
    b << filename << ".bak" << getpid();
    LeaseFileIO backup(b.str());
    backup.removeFile();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease4Ptr> leases = createLeases4();

    // Add leases.
    EXPECT_TRUE(lease_mgr->addLease(leases[1]));
    EXPECT_TRUE(lease_mgr->addLease(leases[2]));
    EXPECT_TRUE(lease_mgr->addLease(leases[3]));

    // Try again.
    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lease_mgr->deleteLease(leases[2]));
    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());

    // Backup should have the previous database image.
    ASSERT_TRUE(backup.exists());
    EXPECT_EQ(content, backup.readFile());
}

/// @brief Check if writeLease can overwrite the lease file (v4+MT).
TEST_F(MemfileLeaseMgrTest, overWriteLease4MultiThread) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["lfc-interval"] = "0";
    pmap["persist"] = "true";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    boost::scoped_ptr<WFMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new WFMemfileLeaseMgr(pmap)));

    MultiThreadingMgr::instance().setMode(true);

    // Empty database should give a header only file.
    string header =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    ASSERT_TRUE(lease_mgr->lease_file4_);
    string filename = lease_mgr->lease_file4_->getFilename();
    LeaseFileIO file(filename);
    ostringstream b;
    b << filename << ".bak" << getpid();
    LeaseFileIO backup(b.str());
    backup.removeFile();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease4Ptr> leases = createLeases4();

    // Add leases.
    EXPECT_TRUE(lease_mgr->addLease(leases[1]));
    EXPECT_TRUE(lease_mgr->addLease(leases[2]));
    EXPECT_TRUE(lease_mgr->addLease(leases[3]));

    // Try again.
    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lease_mgr->deleteLease(leases[2]));
    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());

    // Backup should have the previous database image.
    ASSERT_TRUE(backup.exists());
    EXPECT_EQ(content, backup.readFile());
}

/// @brief Check if writeLease can overwrite the lease file (v6).
TEST_F(MemfileLeaseMgrTest, overWriteLease6) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["lfc-interval"] = "0";
    pmap["persist"] = "true";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    boost::scoped_ptr<WFMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new WFMemfileLeaseMgr(pmap)));

    // Empty database should give a header only file.
    string header =
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n";

    ASSERT_TRUE(lease_mgr->lease_file6_);
    string filename = lease_mgr->lease_file6_->getFilename();
    LeaseFileIO file(filename);
    ostringstream b;
    b << filename << ".bak" << getpid();
    LeaseFileIO backup(b.str());
    backup.removeFile();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease6Ptr> leases = createLeases6();

    // Add leases.
    EXPECT_TRUE(lease_mgr->addLease(leases[1]));
    EXPECT_TRUE(lease_mgr->addLease(leases[2]));
    EXPECT_TRUE(lease_mgr->addLease(leases[3]));

    // Try again.
    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lease_mgr->deleteLease(leases[2]));
    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());

    // Backup should have the previous database image.
    ASSERT_TRUE(backup.exists());
    EXPECT_EQ(content, backup.readFile());
}

/// @brief Check if writeLease can overwrite the lease file (v6+MT).
TEST_F(MemfileLeaseMgrTest, overWriteLease6MultiThread) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["lfc-interval"] = "0";
    pmap["persist"] = "true";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    boost::scoped_ptr<WFMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new WFMemfileLeaseMgr(pmap)));

    MultiThreadingMgr::instance().setMode(true);

    // Empty database should give a header only file.
    string header =
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n";

    ASSERT_TRUE(lease_mgr->lease_file6_);
    string filename = lease_mgr->lease_file6_->getFilename();
    LeaseFileIO file(filename);
    ostringstream b;
    b << filename << ".bak" << getpid();
    LeaseFileIO backup(b.str());
    backup.removeFile();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease6Ptr> leases = createLeases6();

    // Add leases.
    EXPECT_TRUE(lease_mgr->addLease(leases[1]));
    EXPECT_TRUE(lease_mgr->addLease(leases[2]));
    EXPECT_TRUE(lease_mgr->addLease(leases[3]));

    // Try again.
    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lease_mgr->deleteLease(leases[2]));
    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());

    // Backup should have the previous database image.
    ASSERT_TRUE(backup.exists());
    EXPECT_EQ(content, backup.readFile());
}

/// @brief Check if writeLease works without a lease file (v4).
TEST_F(MemfileLeaseMgrTest, notPersistWriteLease4) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["lfc-interval"] = "0";
    pmap["persist"] = "false";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    boost::scoped_ptr<WFMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new WFMemfileLeaseMgr(pmap)));

    // Empty database should give a header only file.
    string header =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    ASSERT_FALSE(lease_mgr->lease_file4_);
    string filename = getLeaseFilePath("backup.csv");
    LeaseFileIO file(filename);
    file.removeFile();
    ostringstream b;
    b << filename << ".bak" << getpid();
    LeaseFileIO backup(b.str());
    backup.removeFile();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease4Ptr> leases = createLeases4();

    // Add leases.
    EXPECT_TRUE(lease_mgr->addLease(leases[1]));
    EXPECT_TRUE(lease_mgr->addLease(leases[2]));
    EXPECT_TRUE(lease_mgr->addLease(leases[3]));

    // Try again.
    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lease_mgr->deleteLease(leases[2]));
    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());
}

/// @brief Check if writeLease works without a lease file (v4+MT).
TEST_F(MemfileLeaseMgrTest, notPersistWriteLease4MultiThread) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["lfc-interval"] = "0";
    pmap["persist"] = "false";
    pmap["name"] = getLeaseFilePath("leasefile4_0.csv");
    boost::scoped_ptr<WFMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new WFMemfileLeaseMgr(pmap)));

    MultiThreadingMgr::instance().setMode(true);

    // Empty database should give a header only file.
    string header =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n";

    ASSERT_FALSE(lease_mgr->lease_file4_);
    string filename = getLeaseFilePath("backup.csv");
    LeaseFileIO file(filename);
    file.removeFile();
    ostringstream b;
    b << filename << ".bak" << getpid();
    LeaseFileIO backup(b.str());
    backup.removeFile();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease4Ptr> leases = createLeases4();

    // Add leases.
    EXPECT_TRUE(lease_mgr->addLease(leases[1]));
    EXPECT_TRUE(lease_mgr->addLease(leases[2]));
    EXPECT_TRUE(lease_mgr->addLease(leases[3]));

    // Try again.
    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lease_mgr->deleteLease(leases[2]));
    EXPECT_NO_THROW(lease_mgr->writeLeases4(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());
}

/// @brief Check if writeLease works without a lease file (v6).
TEST_F(MemfileLeaseMgrTest, notPersistWriteLease6) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["lfc-interval"] = "0";
    pmap["persist"] = "false";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    boost::scoped_ptr<WFMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new WFMemfileLeaseMgr(pmap)));

    // Empty database should give a header only file.
    string header =
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n";

    ASSERT_FALSE(lease_mgr->lease_file6_);
    string filename = getLeaseFilePath("backup.csv");
    LeaseFileIO file(filename);
    file.removeFile();
    ostringstream b;
    b << filename << ".bak" << getpid();
    LeaseFileIO backup(b.str());
    backup.removeFile();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease6Ptr> leases = createLeases6();

    // Add leases.
    EXPECT_TRUE(lease_mgr->addLease(leases[1]));
    EXPECT_TRUE(lease_mgr->addLease(leases[2]));
    EXPECT_TRUE(lease_mgr->addLease(leases[3]));

    // Try again.
    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lease_mgr->deleteLease(leases[2]));
    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());
}

/// @brief Check if writeLease works without a lease file (v6+MT).
TEST_F(MemfileLeaseMgrTest, notPersistWriteLease6MultiThread) {
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["lfc-interval"] = "0";
    pmap["persist"] = "false";
    pmap["name"] = getLeaseFilePath("leasefile6_0.csv");
    boost::scoped_ptr<WFMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new WFMemfileLeaseMgr(pmap)));

    MultiThreadingMgr::instance().setMode(true);

    // Empty database should give a header only file.
    string header =
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n";

    ASSERT_FALSE(lease_mgr->lease_file6_);
    string filename = getLeaseFilePath("backup.csv");
    LeaseFileIO file(filename);
    file.removeFile();
    ostringstream b;
    b << filename << ".bak" << getpid();
    LeaseFileIO backup(b.str());
    backup.removeFile();
    extra_files_.push_back(b.str());

    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    EXPECT_EQ(header, file.readFile());

    // Get the leases to be used for the test.
    vector<Lease6Ptr> leases = createLeases6();

    // Add leases.
    EXPECT_TRUE(lease_mgr->addLease(leases[1]));
    EXPECT_TRUE(lease_mgr->addLease(leases[2]));
    EXPECT_TRUE(lease_mgr->addLease(leases[3]));

    // Try again.
    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content = file.readFile();
    ASSERT_GT(content.size(), header.size());
    EXPECT_EQ(header, content.substr(0, header.size()));

    // Delete a lease so shrink the database.
    file.removeFile();
    EXPECT_FALSE(file.exists());
    EXPECT_TRUE(lease_mgr->deleteLease(leases[2]));
    EXPECT_NO_THROW(lease_mgr->writeLeases6(filename));
    ASSERT_TRUE(file.exists());
    string content1 = file.readFile();
    EXPECT_GT(content.size(), content1.size());
}

/// @brief Checks that extractExtendedInfo4 both updates extended info
/// and set id fields at startup.
TEST_F(MemfileLeaseMgrTest, extractExtendedInfo4) {
    // Add some leases to the CSV file: one empty map, one old extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile4_0.csv");
    LeaseFileIO io(lease_file);
    io.writeFile(
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"

        "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,{},0\n"

        "192.0.2.3,03:03:03:03:03:03,,200,200,8,1,1,,1,"
        "{ \"ISC\": { \"relay-agent-info\": \"0x02030102030C03AABBCC\" } },0\n"
    );

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = lease_file;
    pmap["lfc-interval"] = "0";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check the lease with empty user context was updated.
    Lease4Ptr lease = lease_mgr->getLease4(IOAddress("192.0.2.2"));
    ASSERT_TRUE(lease);
    EXPECT_FALSE(lease->getContext());
    EXPECT_TRUE(lease->relay_id_.empty());
    EXPECT_TRUE(lease->remote_id_.empty());

    // Check the lease with extended info was upgraded.
    lease = lease_mgr->getLease4(IOAddress("192.0.2.3"));
    ASSERT_TRUE(lease);
    ConstElementPtr user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ConstElementPtr isc = user_context->get("ISC");
    ASSERT_TRUE(isc);
    ConstElementPtr rai = isc->get("relay-agent-info");
    ASSERT_TRUE(rai);
    ASSERT_EQ(Element::map, rai->getType());
    EXPECT_EQ(3, rai->size());
    ConstElementPtr sub_options = rai->get("sub-options");
    ASSERT_TRUE(sub_options);
    EXPECT_EQ("\"0x02030102030C03AABBCC\"", sub_options->str());
    ConstElementPtr relay_id = rai->get("relay-id");
    ASSERT_TRUE(relay_id);
    EXPECT_EQ("\"AABBCC\"", relay_id->str());
    ConstElementPtr remote_id = rai->get("remote-id");
    ASSERT_TRUE(remote_id);
    EXPECT_EQ("\"010203\"", remote_id->str());

    // Check the lease has the ids.
    const vector<uint8_t> relay = { 0xaa, 0xbb, 0xcc };
    EXPECT_EQ(relay, lease->relay_id_);
    const vector<uint8_t> remote = { 1, 2, 3 };
    EXPECT_EQ(remote, lease->remote_id_);

    // Check the id indexes where updated.
    IOAddress zero = IOAddress::IPV4_ZERO_ADDRESS();
    Lease4Collection leases;
    EXPECT_NO_THROW(leases = lease_mgr->getLeases4ByRelayId(relay,
                                                            zero,
                                                            LeasePageSize(100)));
    ASSERT_EQ(1, leases.size());
    EXPECT_EQ(*lease, *leases[0]);
    EXPECT_NO_THROW(leases = lease_mgr->getLeases4ByRemoteId(remote,
                                                             zero,
                                                             LeasePageSize(100)));
    ASSERT_EQ(1, leases.size());
    EXPECT_EQ(*lease, *leases[0]);
}

/// @brief Checks that extractExtendedInfo4 does not update
/// when extended info sanitizing is disabled.
TEST_F(MemfileLeaseMgrTest, extractExtendedInfo4noSanitize) {
    // Add some leases to the CSV file: one empty map, one old extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile4_0.csv");
    LeaseFileIO io(lease_file);
    io.writeFile(
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"

        "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,{},0\n"

        "192.0.2.3,03:03:03:03:03:03,,200,200,8,1,1,,1,"
        "{ \"ISC\": { \"relay-agent-info\": \"0x02030102030C03AABBCC\" } },0\n"
    );

    // Disable sanitizing.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_NONE);

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = lease_file;
    pmap["lfc-interval"] = "0";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check the lease with empty user context was not updated.
    Lease4Ptr lease = lease_mgr->getLease4(IOAddress("192.0.2.2"));
    ASSERT_TRUE(lease);
    ConstElementPtr user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ASSERT_EQ(Element::map, user_context->getType());
    EXPECT_TRUE(user_context->empty());

    // Check the lease with extended info was not upgraded.
    lease = lease_mgr->getLease4(IOAddress("192.0.2.3"));
    ASSERT_TRUE(lease);
    user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ConstElementPtr isc = user_context->get("ISC");
    ASSERT_TRUE(isc);
    ConstElementPtr rai = isc->get("relay-agent-info");
    ASSERT_TRUE(rai);
    EXPECT_EQ(Element::string, rai->getType());
    EXPECT_EQ("\"0x02030102030C03AABBCC\"", rai->str());

    // Check the lease has no ids.
    EXPECT_TRUE(lease->relay_id_.empty());
    EXPECT_TRUE(lease->remote_id_.empty());
}

/// @brief Checks that extractExtendedInfo4 updates extended info
/// when explicitly requested.
TEST_F(MemfileLeaseMgrTest, extractExtendedInfo4ExplicitSanitize) {
    // Add some leases to the CSV file: one empty map, one old extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile4_0.csv");
    LeaseFileIO io(lease_file);
    string content =
        "address,hwaddr,client_id,valid_lifetime,expire,"
        "subnet_id,fqdn_fwd,fqdn_rev,hostname,state,user_context,pool_id\n"

        "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,{},0\n"

        "192.0.2.3,03:03:03:03:03:03,,200,200,8,1,1,,1,"
        "{ \"ISC\": { \"relay-agent-info\": \"0x02030102030C03AABBCC\" } },0\n";
    io.writeFile(content);

    // Disable sanitizing.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_NONE);

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "4";
    pmap["name"] = lease_file;
    pmap["lfc-interval"] = "0";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check the lease with empty user context was not updated.
    Lease4Ptr lease = lease_mgr->getLease4(IOAddress("192.0.2.2"));
    ASSERT_TRUE(lease);
    ConstElementPtr user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ASSERT_EQ(Element::map, user_context->getType());
    EXPECT_TRUE(user_context->empty());

    // Check the lease with extended info was not upgraded.
    lease = lease_mgr->getLease4(IOAddress("192.0.2.3"));
    ASSERT_TRUE(lease);
    user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ConstElementPtr isc = user_context->get("ISC");
    ASSERT_TRUE(isc);
    ConstElementPtr rai = isc->get("relay-agent-info");
    ASSERT_TRUE(rai);
    EXPECT_EQ(Element::string, rai->getType());
    EXPECT_EQ("\"0x02030102030C03AABBCC\"", rai->str());

    // Check the lease has no ids.
    EXPECT_TRUE(lease->relay_id_.empty());
    EXPECT_TRUE(lease->remote_id_.empty());

    // Enable sanitizing.
    CfgMgr::instance().getCurrentCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_FIX);

    // Now run extractExtendedInfo4 with update set to true.
    size_t updated = 0;
    EXPECT_NO_THROW(updated = lease_mgr->extractExtendedInfo4(true, true));
    EXPECT_EQ(2, updated);

    // Check the lease with empty user context was updated.
    lease = lease_mgr->getLease4(IOAddress("192.0.2.2"));
    ASSERT_TRUE(lease);
    EXPECT_FALSE(lease->getContext());
    EXPECT_TRUE(lease->relay_id_.empty());
    EXPECT_TRUE(lease->remote_id_.empty());

    // Check the lease with extended info was upgraded.
    lease = lease_mgr->getLease4(IOAddress("192.0.2.3"));
    ASSERT_TRUE(lease);
    user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    isc = user_context->get("ISC");
    ASSERT_TRUE(isc);
    rai = isc->get("relay-agent-info");
    ASSERT_TRUE(rai);
    ASSERT_EQ(Element::map, rai->getType());
    EXPECT_EQ(3, rai->size());
    ConstElementPtr sub_options = rai->get("sub-options");
    ASSERT_TRUE(sub_options);
    EXPECT_EQ("\"0x02030102030C03AABBCC\"", sub_options->str());
    ConstElementPtr relay_id = rai->get("relay-id");
    ASSERT_TRUE(relay_id);
    EXPECT_EQ("\"AABBCC\"", relay_id->str());
    ConstElementPtr remote_id = rai->get("remote-id");
    ASSERT_TRUE(remote_id);
    EXPECT_EQ("\"010203\"", remote_id->str());

    // Check the lease has the ids.
    const vector<uint8_t> relay = { 0xaa, 0xbb, 0xcc };
    EXPECT_EQ(relay, lease->relay_id_);
    const vector<uint8_t> remote = { 1, 2, 3 };
    EXPECT_EQ(remote, lease->remote_id_);


    // Check the id indexes where updated.
    IOAddress zero = IOAddress::IPV4_ZERO_ADDRESS();
    Lease4Collection leases;
    EXPECT_NO_THROW(leases = lease_mgr->getLeases4ByRelayId(relay,
                                                            zero,
                                                            LeasePageSize(100)));
    ASSERT_EQ(1, leases.size());
    EXPECT_EQ(*lease, *leases[0]);
    EXPECT_NO_THROW(leases = lease_mgr->getLeases4ByRemoteId(remote,
                                                             zero,
                                                             LeasePageSize(100)));
    ASSERT_EQ(1, leases.size());
    EXPECT_EQ(*lease, *leases[0]);
    // Check the lease file was updated.
    string new_content =
        "192.0.2.2,02:02:02:02:02:02,,200,200,8,1,1,,1,,0\n"

        "192.0.2.3,03:03:03:03:03:03,,200,200,8,1,1,,1,"
        "{ \"ISC\": { \"relay-agent-info\": { "
        "\"relay-id\": \"AABBCC\"&#x2c "
        "\"remote-id\": \"010203\"&#x2c "
        "\"sub-options\": \"0x02030102030C03AABBCC\" } } },0\n";
    string expected = content + new_content;
    EXPECT_EQ(expected, io.readFile());
}

/// @brief Checks that buildExtendedInfoTables6 both updates extended info
/// and add them into tables at startup.
TEST_F(MemfileLeaseMgrTest, buildExtendedInfoTables6) {
    // Add some leases to the CSV file: one empty map, one old extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile6_0.csv");
    LeaseFileIO io(lease_file);
    io.writeFile(
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"

        "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
        "400,1000,8,100,0,7,0,1,1,,,1,"
        "{},,,0\n"

        "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"ISC\": { \"relays\": [ { \"hop\": 44&#x2c"
        " \"link\": \"2001:db8::4\"&#x2c \"peer\": \"2001:db8::5\"&#x2c"
        " \"options\": \"0x00250006010203040506003500086464646464646464\""
        " } ] } },,,0\n"
    );

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = lease_file;
    pmap["lfc-interval"] = "0";
    pmap["extended-info-tables"] = "true";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check the lease with empty user context was updated.
    Lease6Ptr lease = lease_mgr->getLease6(Lease::TYPE_NA,
                                           IOAddress("2001:db8:1::1"));
    ASSERT_TRUE(lease);
    EXPECT_FALSE(lease->getContext());

    // Check the lease with extended info was upgraded.
    lease = lease_mgr->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
    ASSERT_TRUE(lease);
    ConstElementPtr user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ConstElementPtr isc = user_context->get("ISC");
    ASSERT_TRUE(isc);
    EXPECT_FALSE(isc->contains("relays"));
    EXPECT_TRUE(isc->contains("relay-info"));

    // Check that extended info tables were updated.
    ASSERT_EQ(1, lease_mgr->relay_id6_.size());
    auto relay_id_it = lease_mgr->relay_id6_.cbegin();
    ASSERT_NE(relay_id_it, lease_mgr->relay_id6_.cend());
    Lease6ExtendedInfoPtr ex_info = *relay_id_it;
    ASSERT_TRUE(ex_info);
    EXPECT_EQ("2001:db8:1::2", ex_info->lease_addr_.toText());
    const vector<uint8_t>& exp_relay_id = vector<uint8_t>(8, 0x64);
    EXPECT_EQ(exp_relay_id, ex_info->id_);

    ASSERT_EQ(1, lease_mgr->remote_id6_.size());
    auto remote_id_it = lease_mgr->remote_id6_.cbegin();
    ASSERT_NE(remote_id_it, lease_mgr->remote_id6_.cend());
    ex_info = *remote_id_it;
    ASSERT_TRUE(ex_info);
    EXPECT_EQ("2001:db8:1::2", ex_info->lease_addr_.toText());
    const vector<uint8_t>& exp_remote_id = { 1, 2, 3, 4, 5, 6 };
    EXPECT_EQ(exp_remote_id, ex_info->id_);
}

/// @brief Checks that buildExtendedInfoTables6 does not update
/// when extended info sanitizing is disabled.
TEST_F(MemfileLeaseMgrTest, buildExtendedInfoTables6noSanitize) {
    // Add some leases to the CSV file: one empty map, one old extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile6_0.csv");
    LeaseFileIO io(lease_file);
    io.writeFile(
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"

        "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
        "400,1000,8,100,0,7,0,1,1,,,1,"
        "{},,,0\n"

        "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"ISC\": { \"relays\": [ { \"hop\": 44&#x2c"
        " \"link\": \"2001:db8::4\"&#x2c \"peer\": \"2001:db8::5\"&#x2c"
        " \"options\": \"0x00250006010203040506003500086464646464646464\""
        " } ] } },,,0\n"
    );

    // Disable sanitizing.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_NONE);

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = lease_file;
    pmap["lfc-interval"] = "0";
    pmap["extended-info-tables"] = "true";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check the lease with empty user context was not updated.
    Lease6Ptr lease = lease_mgr->getLease6(Lease::TYPE_NA,
                                           IOAddress("2001:db8:1::1"));
    ASSERT_TRUE(lease);
    ConstElementPtr user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ASSERT_EQ(Element::map, user_context->getType());
    EXPECT_TRUE(user_context->empty());

    // Check the lease with extended info was not upgraded.
    lease = lease_mgr->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
    ASSERT_TRUE(lease);
    user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ConstElementPtr isc = user_context->get("ISC");
    ASSERT_TRUE(isc);
    EXPECT_TRUE(isc->contains("relays"));
    EXPECT_FALSE(isc->contains("relay-info"));

    // Check that extended info tables were not updated.
    EXPECT_TRUE(lease_mgr->relay_id6_.empty());
    EXPECT_TRUE(lease_mgr->remote_id6_.empty());
}

/// @brief Checks that buildExtendedInfoTables6 adds extended info to tables
/// when enabled.
TEST_F(MemfileLeaseMgrTest, buildExtendedInfoTables6enabled) {
    // Add some leases to the CSV file: one empty map, one new extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile6_0.csv");
    LeaseFileIO io(lease_file);
    io.writeFile(
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"

        "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
        "400,1000,8,100,0,7,0,1,1,,,1,"
        "{},,,0\n"

        "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"ISC\": { \"relay-info\": [ { \"hop\": 44&#x2c"
        " \"link\": \"2001:db8::4\"&#x2c \"peer\": \"2001:db8::5\"&#x2c"
        " \"remote-id\": \"010203040506\"&#x2c"
        " \"relay-id\": \"6464646464646464\"&#x2c"
        " \"options\": \"0x00250006010203040506003500086464646464646464\""
        " } ] } },,,0\n"
    );

    // Disable sanitizing.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_NONE);

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = lease_file;
    pmap["lfc-interval=0"] = "0";
    pmap["extended-info-tables"] = "true";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check the lease with empty user context was updated.
    Lease6Ptr lease = lease_mgr->getLease6(Lease::TYPE_NA,
                                           IOAddress("2001:db8:1::1"));
    ASSERT_TRUE(lease);
    ConstElementPtr user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ASSERT_EQ(Element::map, user_context->getType());
    EXPECT_TRUE(user_context->empty());

    // Check that extended info tables were updated.
    ASSERT_EQ(1, lease_mgr->relay_id6_.size());
    auto relay_id_it = lease_mgr->relay_id6_.cbegin();
    ASSERT_NE(relay_id_it, lease_mgr->relay_id6_.cend());
    Lease6ExtendedInfoPtr ex_info = *relay_id_it;
    ASSERT_TRUE(ex_info);
    EXPECT_EQ("2001:db8:1::2", ex_info->lease_addr_.toText());
    const vector<uint8_t>& exp_relay_id = vector<uint8_t>(8, 0x64);
    EXPECT_EQ(exp_relay_id, ex_info->id_);

    ASSERT_EQ(1, lease_mgr->remote_id6_.size());
    auto remote_id_it = lease_mgr->remote_id6_.cbegin();
    ASSERT_NE(remote_id_it, lease_mgr->remote_id6_.cend());
    ex_info = *remote_id_it;
    ASSERT_TRUE(ex_info);
    EXPECT_EQ("2001:db8:1::2", ex_info->lease_addr_.toText());
    const vector<uint8_t>& exp_remote_id = { 1, 2, 3, 4, 5, 6 };
    EXPECT_EQ(exp_remote_id, ex_info->id_);
}

/// @brief Checks that buildExtendedInfoTables6 does not add extended info
/// to tables when disabled.
TEST_F(MemfileLeaseMgrTest, buildExtendedInfoTables6disabled) {
    // Add some leases to the CSV file: one empty map, one new extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile6_0.csv");
    LeaseFileIO io(lease_file);
    io.writeFile(
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"

        "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
        "400,1000,8,100,0,7,0,1,1,,,1,"
        "{},,,0\n"

        "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"ISC\": { \"relay-info\": [ { \"hop\": 44&#x2c"
        " \"link\": \"2001:db8::4\"&#x2c \"peer\": \"2001:db8::5\"&#x2c"
        " \"remote-id\": \"010203040506\"&#x2c"
        " \"relay-id\": \"6464646464646464\"&#x2c"
        " \"options\": \"0x00250006010203040506003500086464646464646464\""
        " } ] } },,,0\n"
    );

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = lease_file;
    pmap["lfc-interval"] = "0";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check the lease with empty user context was updated.
    Lease6Ptr lease = lease_mgr->getLease6(Lease::TYPE_NA,
                                           IOAddress("2001:db8:1::1"));
    ASSERT_TRUE(lease);
    EXPECT_FALSE(lease->getContext());

    // Check that extended info tables were not updated.
    EXPECT_TRUE(lease_mgr->relay_id6_.empty());
    EXPECT_TRUE(lease_mgr->remote_id6_.empty());
}

/// @brief Checks that buildExtendedInfoTables6 updates when explicitly
/// requested.
TEST_F(MemfileLeaseMgrTest, buildExtendedInfoTables6ExplicitSanitize) {
    // Add some leases to the CSV file: one empty map, one old extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile6_0.csv");
    LeaseFileIO io(lease_file);
    string content =
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"

        "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
        "400,1000,8,100,0,7,0,1,1,,,1,"
        "{},,,0\n"

        "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"ISC\": { \"relays\": [ { \"hop\": 44&#x2c"
        " \"link\": \"2001:db8::4\"&#x2c \"peer\": \"2001:db8::5\"&#x2c"
        " \"options\": \"0x00250006010203040506003500086464646464646464\""
        " } ] } },,,0\n";
    io.writeFile(content);

    // Disable sanitizing.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_NONE);

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = lease_file;
    pmap["lfc-interval"] = "0";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check the lease with empty user context was not updated.
    Lease6Ptr lease = lease_mgr->getLease6(Lease::TYPE_NA,
                                           IOAddress("2001:db8:1::1"));
    ASSERT_TRUE(lease);
    ConstElementPtr user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ASSERT_EQ(Element::map, user_context->getType());
    EXPECT_TRUE(user_context->empty());

    // Check the lease with extended info was not upgraded.
    lease = lease_mgr->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
    ASSERT_TRUE(lease);
    user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    ConstElementPtr isc = user_context->get("ISC");
    ASSERT_TRUE(isc);
    EXPECT_TRUE(isc->contains("relays"));
    EXPECT_FALSE(isc->contains("relay-info"));

    // Enable sanitizing.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_FIX);

    // Now run buildExtendedInfoTables6.
    EXPECT_NO_THROW(lease_mgr->buildExtendedInfoTables6());

    // Check the lease with empty user context was updated.
    lease = lease_mgr->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::1"));
    ASSERT_TRUE(lease);
    EXPECT_FALSE(lease->getContext());

    // Check the lease with extended info was upgraded.
    lease = lease_mgr->getLease6(Lease::TYPE_NA, IOAddress("2001:db8:1::2"));
    ASSERT_TRUE(lease);
    user_context = lease->getContext();
    ASSERT_TRUE(user_context);
    isc = user_context->get("ISC");
    ASSERT_TRUE(isc);
    EXPECT_FALSE(isc->contains("relays"));
    EXPECT_TRUE(isc->contains("relay-info"));

    // The lease file is not more updated.
}

/// @brief Checks that buildExtendedInfoTables6 can rebuild tables.
TEST_F(MemfileLeaseMgrTest, buildExtendedInfoTables6rebuild) {
    // Add some leases to the CSV file: one empty map, one new extended
    // info format.
    string lease_file = getLeaseFilePath("leasefile6_0.csv");
    LeaseFileIO io(lease_file);
    io.writeFile(
        "address,duid,valid_lifetime,expire,subnet_id,pref_lifetime,"
        "lease_type,iaid,prefix_len,fqdn_fwd,fqdn_rev,hostname,"
        "hwaddr,state,user_context,hwtype,hwaddr_source,pool_id\n"

        "2001:db8:1::1,01:01:01:01:01:01:01:01:01:01:01:01:01,"
        "400,1000,8,100,0,7,0,1,1,,,1,"
        "{},,,0\n"

        "2001:db8:1::2,02:02:02:02:02:02:02:02:02:02:02:02:02,"
        "200,200,8,100,0,7,0,1,1,,,1,"
        "{ \"ISC\": { \"relay-info\": [ { \"hop\": 44&#x2c"
        " \"link\": \"2001:db8::4\"&#x2c \"peer\": \"2001:db8::5\"&#x2c"
        " \"remote-id\": \"010203040506\"&#x2c"
        " \"relay-id\": \"6464646464646464\"&#x2c"
        " \"options\": \"0x00250006010203040506003500086464646464646464\""
        " } ] } },,,0\n"
    );

    // Disable sanitizing.
    CfgMgr::instance().getStagingCfg()->getConsistency()->
        setExtendedInfoSanityCheck(CfgConsistency::EXTENDED_INFO_CHECK_NONE);

    // Start the lease manager.
    DatabaseConnection::ParameterMap pmap;
    pmap["type"] = "memfile";
    pmap["universe"] = "6";
    pmap["name"] = lease_file;
    pmap["lfc-interval=0"] = "0";
    pmap["extended-info-tables"] = "true";
    boost::scoped_ptr<NakedMemfileLeaseMgr> lease_mgr;
    EXPECT_NO_THROW(lease_mgr.reset(new NakedMemfileLeaseMgr(pmap)));

    // Check that extended info tables were updated.
    EXPECT_EQ(1, lease_mgr->relay_id6_.size());
    EXPECT_EQ(1, lease_mgr->remote_id6_.size());

    // Add a junk entry in each table.
    IOAddress lease_addr("2001:db8:1::10");
    const vector<uint8_t>& relay_id = vector<uint8_t>(10, 0x65);
    Lease6ExtendedInfoPtr relay;
    relay.reset(new Lease6ExtendedInfo(lease_addr, relay_id));
    lease_mgr->relay_id6_.insert(relay);
    const vector<uint8_t>& remote_id = { 10, 11, 12, 13, 14, 15, 16 };
    Lease6ExtendedInfoPtr remote;
    remote.reset(new Lease6ExtendedInfo(lease_addr, remote_id));
    lease_mgr->remote_id6_.insert(remote);

    // Check that tables grown.
    EXPECT_EQ(2, lease_mgr->relay_id6_.size());
    EXPECT_EQ(2, lease_mgr->remote_id6_.size());

    // Rebuild the tables.
    EXPECT_NO_THROW(lease_mgr->buildExtendedInfoTables6());

    // Check tables.
    ASSERT_EQ(1, lease_mgr->relay_id6_.size());
    auto relay_id_it = lease_mgr->relay_id6_.cbegin();
    ASSERT_NE(relay_id_it, lease_mgr->relay_id6_.cend());
    Lease6ExtendedInfoPtr ex_info = *relay_id_it;
    ASSERT_TRUE(ex_info);
    EXPECT_EQ("2001:db8:1::2", ex_info->lease_addr_.toText());
    const vector<uint8_t>& exp_relay_id = vector<uint8_t>(8, 0x64);
    EXPECT_EQ(exp_relay_id, ex_info->id_);

    ASSERT_EQ(1, lease_mgr->remote_id6_.size());
    auto remote_id_it = lease_mgr->remote_id6_.cbegin();
    ASSERT_NE(remote_id_it, lease_mgr->remote_id6_.cend());
    ex_info = *remote_id_it;
    ASSERT_TRUE(ex_info);
    EXPECT_EQ("2001:db8:1::2", ex_info->lease_addr_.toText());
    const vector<uint8_t>& exp_remote_id = { 1, 2, 3, 4, 5, 6 };
    EXPECT_EQ(exp_remote_id, ex_info->id_);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv4 lease is added.
TEST_F(MemfileLeaseMgrTest, trackAddLease4) {
    startBackend(V4);
    testTrackAddLease4(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv4 lease is added.
TEST_F(MemfileLeaseMgrTest, trackAddLease4MultiThreading) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testTrackAddLease4(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 address lease is added.
TEST_F(MemfileLeaseMgrTest, trackAddLeaseNA) {
    startBackend(V6);
    testTrackAddLeaseNA(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 address lease is added.
TEST_F(MemfileLeaseMgrTest, trackAddLeaseNAMultiThreading) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testTrackAddLeaseNA(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 prefix lease is added.
TEST_F(MemfileLeaseMgrTest, trackAddLeasePD) {
    startBackend(V6);
    testTrackAddLeasePD(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 prefix lease is added.
TEST_F(MemfileLeaseMgrTest, trackAddLeasePDMultiThreading) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testTrackAddLeasePD(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv4 lease is added.
TEST_F(MemfileLeaseMgrTest, trackUpdateLease4) {
    startBackend(V4);
    testTrackUpdateLease4(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv4 lease is added.
TEST_F(MemfileLeaseMgrTest, trackUpdateLease4MultiThreading) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testTrackUpdateLease4(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 address lease is updated.
TEST_F(MemfileLeaseMgrTest, trackUpdateLeaseNA) {
    startBackend(V6);
    testTrackUpdateLeaseNA(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 address lease is updated.
TEST_F(MemfileLeaseMgrTest, trackUpdateLeaseNAMultiThreading) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testTrackUpdateLeaseNA(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 prefix lease is updated.
TEST_F(MemfileLeaseMgrTest, trackUpdateLeasePD) {
    startBackend(V6);
    testTrackUpdateLeasePD(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 prefix lease is updated.
TEST_F(MemfileLeaseMgrTest, trackUpdateLeasePDMultiThreading) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testTrackUpdateLeasePD(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv4 lease is added.
TEST_F(MemfileLeaseMgrTest, trackDeleteLease4) {
    startBackend(V4);
    testTrackDeleteLease4(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv4 lease is added.
TEST_F(MemfileLeaseMgrTest, trackDeleteLease4MultiThreading) {
    startBackend(V4);
    MultiThreadingMgr::instance().setMode(true);
    testTrackDeleteLease4(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 address lease is deleted.
TEST_F(MemfileLeaseMgrTest, trackDeleteLeaseNA) {
    startBackend(V6);
    testTrackDeleteLeaseNA(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 addres lease is deleted.
TEST_F(MemfileLeaseMgrTest, trackDeleteLeaseNAMultiThreading) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testTrackDeleteLeaseNA(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 prefix lease is deleted.
TEST_F(MemfileLeaseMgrTest, trackDeleteLeasePD) {
    startBackend(V6);
    testTrackDeleteLeasePD(false);
}

/// @brief Checks if the backends call the callbacks when an
/// IPv6 prefix lease is deleted.
TEST_F(MemfileLeaseMgrTest, trackDeleteLeasePDMultiThreading) {
    startBackend(V6);
    MultiThreadingMgr::instance().setMode(true);
    testTrackDeleteLeasePD(false);
}

/// @brief Checks that the lease manager can be recreated and its
/// registered callbacks preserved, if desired.
TEST_F(MemfileLeaseMgrTest, recreateWithCallbacks) {
    startBackend(V4);
    testRecreateWithCallbacks(getConfigString(V4));
}

/// @brief Checks that the lease manager can be recreated without the
/// previously registered callbacks.
TEST_F(MemfileLeaseMgrTest, recreateWithoutCallbacks) {
    startBackend(V4);
    testRecreateWithoutCallbacks(getConfigString(V4));
}

TEST_F(MemfileLeaseMgrTest, bigStats) {
    startBackend(V4);
    testBigStats();
}

}  // namespace