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
// 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 <cc/command_interpreter.h>
#include <cc/data.h>
#include <cc/simple_parser.h>
#include <dhcp/classify.h>
#include <dhcp/option.h>
#include <dhcp/option_custom.h>
#include <dhcp/option_int.h>
#include <dhcp/option_string.h>
#include <dhcp/option4_addrlst.h>
#include <dhcp/option6_addrlst.h>
#include <dhcp/testutils/iface_mgr_test_config.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/subnet.h>
#include <dhcpsrv/cfg_mac_source.h>
#include <dhcpsrv/flq_allocator.h>
#include <dhcpsrv/flq_allocation_state.h>
#include <dhcpsrv/iterative_allocator.h>
#include <dhcpsrv/iterative_allocation_state.h>
#include <dhcpsrv/parsers/dhcp_parsers.h>
#include <dhcpsrv/parsers/option_data_parser.h>
#include <dhcpsrv/parsers/shared_network_parser.h>
#include <dhcpsrv/parsers/shared_networks_list_parser.h>
#include <dhcpsrv/random_allocator.h>
#include <dhcpsrv/random_allocation_state.h>
#include <dhcpsrv/tests/test_libraries.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <dhcpsrv/testutils/config_result_check.h>
#include <exceptions/exceptions.h>
#include <hooks/hooks_parser.h>
#include <hooks/hooks_manager.h>
#include <testutils/gtest_utils.h>
#include <testutils/test_to_element.h>

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

#include <map><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <string><--- 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::config;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::dhcp::test;
using namespace isc::hooks;
using namespace isc::test;

namespace {

/// @brief DHCP Parser test fixture class
class DhcpParserTest : public ::testing::Test {
public:
    /// @brief Constructor
    DhcpParserTest() {
        resetIfaceCfg();
    }

    /// @brief Destructor.
    virtual ~DhcpParserTest() {
        resetIfaceCfg();
    }

    /// @brief Resets selection of the interfaces from previous tests.
    void resetIfaceCfg() {
        CfgMgr::instance().clear();
    }

    // Verifies valid permutations of ddns-ttl-percent, ddns-ttl,
    // ddns-ttl-min, and ddns-ttl-max values for SubnetX.
    template<typename ParserType, typename NetworkPtrType>
	void validDdnsTtlParmatersSubnet(int family) {
	    struct Scenario {
	        size_t line_no_;
	        std::string json_;
	        double ddns_ttl_percent_;
	        uint32_t ddns_ttl_;
	        uint32_t ddns_ttl_min_;
	        uint32_t ddns_ttl_max_;
	    };

	    std::list<Scenario> scenarios = {
	    {
	        __LINE__,
	        R"^({
	            "id": 1,
	            "ddns-ttl": 100
	        })^",
	        0.0, 100, 0, 0
	    },{
	        __LINE__,
	        R"^({
	            "id": 1,
	            "ddns-ttl-percent": 5.0 
	        })^",
	        5.0, 0, 0, 0
	    },{
	        __LINE__,
	        R"^({
	            "id": 1,
	            "ddns-ttl-min": 25 
	        })^",
	        0.0, 0, 25, 0
	    },{
	        __LINE__,
	        R"^({
	            "id": 1, 
	            "ddns-ttl-max": 150 
	        })^",
	        0.0, 0, 0, 150 
	    },{
	        __LINE__,
	        R"^({
	            "id": 1,
	            "ddns-ttl-min": 25,
	            "ddns-ttl-max": 150 
	        })^",
	        0.0, 0, 25, 150 
	    },{
	        __LINE__,
	        R"^({
	            "id": 1, "subnet": "192.0.2.0/24",
	            "ddns-ttl-percent": 5.0,
	            "ddns-ttl-min": 25,
	            "ddns-ttl-max": 150 
	        })^",
	        5.0, 0, 25, 150 
	    }};

        ElementPtr subnet_elem = Element::create(family == AF_INET ?
                                                 "192.0.2.0/24" : "2001:db8::/64");	
	    for (const auto& scenario : scenarios) {
	        std::stringstream oss; 
	        oss << "scenario at " << scenario.line_no_;
	        SCOPED_TRACE(oss.str());
	
	        // Parse configuration specified above.
	        ElementPtr config_element;
	        ASSERT_NO_THROW_LOG(config_element = Element::fromJSON(scenario.json_));
            config_element->set("subnet", subnet_elem);

	        ParserType parser(family);

	        NetworkPtrType subnet;
	
	        ASSERT_NO_THROW_LOG(subnet = parser.parse(config_element));
	        ASSERT_TRUE(subnet);
	
	        EXPECT_EQ(subnet->getDdnsTtlPercent().unspecified(), (scenario.ddns_ttl_percent_ == 0.0)); 
	        EXPECT_EQ(subnet->getDdnsTtlPercent(), scenario.ddns_ttl_percent_); 
	
	        EXPECT_EQ(subnet->getDdnsTtl().unspecified(), (scenario.ddns_ttl_ == 0)); 
	        EXPECT_EQ(subnet->getDdnsTtl(), scenario.ddns_ttl_); 
	
	        EXPECT_EQ(subnet->getDdnsTtlMin().unspecified(), (scenario.ddns_ttl_min_ == 0)); 
	        EXPECT_EQ(subnet->getDdnsTtlMin(), scenario.ddns_ttl_min_); 
	
	        EXPECT_EQ(subnet->getDdnsTtlMax().unspecified(), (scenario.ddns_ttl_max_ == 0)); 
	        EXPECT_EQ(subnet->getDdnsTtlMax(), scenario.ddns_ttl_max_); 
	    }
	}
	
	// Verifies invalid permutations of ddns-ttl-percent, ddns-ttl,
	// ddns-ttl-min, and ddns-ttl-max values for SubnetX.
    template<typename ParserType>
	void invalidDdnsTtlParmatersSubnet(int family) {
	    struct Scenario {
	        size_t line_no_;
	        std::string json_;
	        std::string exp_message_;
	    };
	
	    std::list<Scenario> scenarios = {
	    {
	        __LINE__,
	        R"^({
	            "id": 1,
	            "ddns-ttl-percent": 5.0,
	            "ddns-ttl": 100
	        })^",
	        "subnet configuration failed: cannot specify both ddns-ttl-percent and ddns-ttl"
	    },{
	        __LINE__,
	        R"^({
	            "id": 1,
	            "ddns-ttl": 100,
	            "ddns-ttl-min": 25
	        })^",
	        "subnet configuration failed: cannot specify both ddns-ttl-min and ddns-ttl"
	    },{
	        __LINE__,
	        R"^({
	            "id": 1,
	            "ddns-ttl": 100,
	            "ddns-ttl-max": 150 
	        })^",
	        "subnet configuration failed: cannot specify both ddns-ttl-max and ddns-ttl"
	    },{
	        __LINE__,
	        R"^({
	            "id": 1,
	            "ddns-ttl-min": 150,
	            "ddns-ttl-max": 25 
	        })^",
	        "subnet configuration failed: ddns-ttl-max: 25 must be greater than ddns-ttl-min: 150"
	    }};
	
        ElementPtr subnet_elem = Element::create(family == AF_INET ?
                                                 "192.0.2.0/24" : "2001:db8::/64");	
	    for (const auto& scenario : scenarios) {
	        std::stringstream oss; 
	        oss << "scenario at " << scenario.line_no_;
	        SCOPED_TRACE(oss.str());
	
	        // Parse configuration specified above.
	        ElementPtr config_element;
	        ASSERT_NO_THROW_LOG(config_element = Element::fromJSON(scenario.json_));
            config_element->set("subnet", subnet_elem);
	        ParserType parser(family);
	        ASSERT_THROW_MSG(parser.parse(config_element), DhcpConfigError, scenario.exp_message_);
	    }
	}
};

/// Verifies the code that parses mac sources and adds them to CfgMgr
TEST_F(DhcpParserTest, MacSources) {<--- syntax error

    // That's an equivalent of the following snippet:
    // "mac-sources: [ \"duid\", \"ipv6\" ]";
    ElementPtr values = Element::createList();
    values->add(Element::create("duid"));
    values->add(Element::create("ipv6-link-local"));

    // Let's grab server configuration from CfgMgr
    SrvConfigPtr cfg = CfgMgr::instance().getStagingCfg();
    ASSERT_TRUE(cfg);
    CfgMACSource& sources = cfg->getMACSources();

    // This should parse the configuration and check that it doesn't throw.
    MACSourcesListConfigParser parser;
    EXPECT_NO_THROW(parser.parse(sources, values));

    // Finally, check the sources that were configured
    CfgMACSources configured_sources = cfg->getMACSources().get();
    ASSERT_EQ(2, configured_sources.size());
    EXPECT_EQ(HWAddr::HWADDR_SOURCE_DUID, configured_sources[0]);
    EXPECT_EQ(HWAddr::HWADDR_SOURCE_IPV6_LINK_LOCAL, configured_sources[1]);
}

/// @brief Check MACSourcesListConfigParser rejecting empty list
///
/// Verifies that the code rejects an empty mac-sources list.
TEST_F(DhcpParserTest, MacSourcesEmpty) {

    // That's an equivalent of the following snippet:
    // "mac-sources: [ \"duid\", \"ipv6\" ]";
    ElementPtr values = Element::createList();

    // Let's grab server configuration from CfgMgr
    SrvConfigPtr cfg = CfgMgr::instance().getStagingCfg();
    ASSERT_TRUE(cfg);
    CfgMACSource& sources = cfg->getMACSources();

    // This should throw, because if specified, at least one MAC source
    // has to be specified.
    MACSourcesListConfigParser parser;
    EXPECT_THROW(parser.parse(sources, values), DhcpConfigError);
}

/// @brief Check MACSourcesListConfigParser rejecting empty list
///
/// Verifies that the code rejects fake mac source.
TEST_F(DhcpParserTest, MacSourcesBogus) {

    // That's an equivalent of the following snippet:
    // "mac-sources: [ \"duid\", \"ipv6\" ]";
    ElementPtr values = Element::createList();
    values->add(Element::create("from-ebay"));
    values->add(Element::create("just-guess-it"));

    // Let's grab server configuration from CfgMgr
    SrvConfigPtr cfg = CfgMgr::instance().getStagingCfg();
    ASSERT_TRUE(cfg);
    CfgMACSource& sources = cfg->getMACSources();

    // This should throw, because these are not valid sources.
    MACSourcesListConfigParser parser;
    EXPECT_THROW(parser.parse(sources, values), DhcpConfigError);
}

/// Verifies the code that properly catches duplicate entries
/// in mac-sources definition.
TEST_F(DhcpParserTest, MacSourcesDuplicate) {

    // That's an equivalent of the following snippet:
    // "mac-sources: [ \"duid\", \"ipv6\" ]";
    ElementPtr values = Element::createList();
    values->add(Element::create("ipv6-link-local"));
    values->add(Element::create("duid"));
    values->add(Element::create("duid"));
    values->add(Element::create("duid"));

    // Let's grab server configuration from CfgMgr
    SrvConfigPtr cfg = CfgMgr::instance().getStagingCfg();
    ASSERT_TRUE(cfg);
    CfgMACSource& sources = cfg->getMACSources();

    // This should parse the configuration and check that it throws.
    MACSourcesListConfigParser parser;
    EXPECT_THROW(parser.parse(sources, values), DhcpConfigError);
}


/// @brief Test Fixture class which provides basic structure for testing
/// configuration parsing.  This is essentially the same structure provided
/// by dhcp servers.
class ParseConfigTest : public ::testing::Test {
public:
    /// @brief Constructor
    ParseConfigTest()
        :family_(AF_INET6) {
        reset_context();
    }

    ~ParseConfigTest() {
        reset_context();
        CfgMgr::instance().clear();
    }

    /// @brief Parses a configuration.
    ///
    /// Parse the given configuration, populating the context storage with
    /// the parsed elements.
    ///
    /// @param config_set is the set of elements to parse.
    /// @param v6 boolean flag indicating if this is a DHCPv6 configuration.
    /// @return returns an ConstElementPtr containing the numeric result
    /// code and outcome comment.
    isc::data::ConstElementPtr
    parseElementSet(isc::data::ConstElementPtr config_set, bool v6) {
        // Answer will hold the result.
        ConstElementPtr answer;
        if (!config_set) {
            answer = isc::config::createAnswer(CONTROL_RESULT_ERROR,
                                 string("Can't parse NULL config"));
            return (answer);
        }

        try {
            // Iterate over the config elements.
            const std::map<std::string, ConstElementPtr>& values_map =
                                                      config_set->mapValue();
            for (auto const& config_pair : values_map) {

                // These are the simple parsers. No need to go through
                // the ParserPtr hooplas with them.
                if ((config_pair.first == "option-data") ||
                    (config_pair.first == "option-def") ||
                    (config_pair.first == "dhcp-ddns")) {
                    continue;
                }

                // We also don't care about the default values that may be been
                // inserted
                if ((config_pair.first == "preferred-lifetime") ||
                    (config_pair.first == "valid-lifetime") ||
                    (config_pair.first == "renew-timer") ||
                    (config_pair.first == "rebind-timer")) {
                    continue;
                }

                // Save global hostname-char-*.
                if ((config_pair.first == "hostname-char-set") ||
                    (config_pair.first == "hostname-char-replacement")) {
                    CfgMgr::instance().getStagingCfg()->addConfiguredGlobal(config_pair.first,
                                                                            config_pair.second);
                    continue;
                }

                if (config_pair.first == "hooks-libraries") {
                    HooksLibrariesParser hook_parser;
                    HooksConfig& libraries =
                        CfgMgr::instance().getStagingCfg()->getHooksConfig();
                    hook_parser.parse(libraries, config_pair.second);
                    libraries.verifyLibraries(config_pair.second->getPosition(), false);
                    libraries.loadLibraries(false);
                    continue;
                }
            }

            // The option definition parser is the next one to be run.
            std::map<std::string, ConstElementPtr>::const_iterator
                                def_config = values_map.find("option-def");
            if (def_config != values_map.end()) {

                CfgOptionDefPtr cfg_def = CfgMgr::instance().getStagingCfg()->getCfgOptionDef();
                OptionDefListParser def_list_parser(family_);
                def_list_parser.parse(cfg_def, def_config->second);
            }

            // The option values parser is the next one to be run.
            std::map<std::string, ConstElementPtr>::const_iterator
                                option_config = values_map.find("option-data");
            if (option_config != values_map.end()) {
                CfgOptionPtr cfg_option = CfgMgr::instance().getStagingCfg()->getCfgOption();

                OptionDataListParser option_list_parser(family_);
                option_list_parser.parse(cfg_option, option_config->second);
            }

            // The dhcp-ddns parser is the next one to be run.
            std::map<std::string, ConstElementPtr>::const_iterator
                                d2_client_config = values_map.find("dhcp-ddns");
            if (d2_client_config != values_map.end()) {
                // Used to be done by parser commit
                D2ClientConfigParser parser;
                D2ClientConfigPtr cfg = parser.parse(d2_client_config->second);
                cfg->validateContents();
                CfgMgr::instance().setD2ClientConfig(cfg);
            }

            std::map<std::string, ConstElementPtr>::const_iterator
                                subnets4_config = values_map.find("subnet4");
            if (subnets4_config != values_map.end()) {
                auto srv_config = CfgMgr::instance().getStagingCfg();
                Subnets4ListConfigParser parser;
                parser.parse(srv_config, subnets4_config->second);
            }

            std::map<std::string, ConstElementPtr>::const_iterator
                                subnets6_config = values_map.find("subnet6");
            if (subnets6_config != values_map.end()) {
                auto srv_config = CfgMgr::instance().getStagingCfg();
                Subnets6ListConfigParser parser;
                parser.parse(srv_config, subnets6_config->second);
            }

            std::map<std::string, ConstElementPtr>::const_iterator
                                networks_config = values_map.find("shared-networks");
            if (networks_config != values_map.end()) {
                if (v6) {
                    auto cfg_shared_networks = CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks6();
                    SharedNetworks6ListParser parser;
                    parser.parse(cfg_shared_networks, networks_config->second);

                } else {
                    auto cfg_shared_networks = CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks4();
                    SharedNetworks4ListParser parser;
                    parser.parse(cfg_shared_networks, networks_config->second);
                }
            }

            // Everything was fine. Configuration is successful.
            answer = isc::config::createAnswer(CONTROL_RESULT_SUCCESS, "Configuration committed.");
        } catch (const isc::Exception& ex) {
            answer = isc::config::createAnswer(CONTROL_RESULT_ERROR,
                        string("Configuration parsing failed: ") + ex.what());

        } catch (...) {
            answer = isc::config::createAnswer(CONTROL_RESULT_ERROR,
                                        string("Configuration parsing failed"));
        }

        return (answer);
    }

    /// @brief DHCP-specific method that sets global, and option specific defaults
    ///
    /// This method sets the defaults in the global scope, in option definitions,
    /// and in option data.
    ///
    /// @param global pointer to the Element tree that holds configuration
    /// @param global_defaults array with global default values
    /// @param option_defaults array with option-data default values
    /// @param option_def_defaults array with default values for option definitions
    /// @return number of default values inserted.
    size_t setAllDefaults(isc::data::ElementPtr global,
                          const SimpleDefaults& global_defaults,
                          const SimpleDefaults& option_defaults,
                          const SimpleDefaults& option_def_defaults) {
        size_t cnt = 0;
        // Set global defaults first.
        cnt = SimpleParser::setDefaults(global, global_defaults);

        // Now set option definition defaults for each specified option definition
        ConstElementPtr option_defs = global->get("option-def");
        if (option_defs) {
            for (auto const& single_def : option_defs->listValue()) {
                cnt += SimpleParser::setDefaults(single_def, option_def_defaults);
            }
        }

        ConstElementPtr options = global->get("option-data");
        if (options) {
            for (auto const& single_option : options->listValue()) {
                cnt += SimpleParser::setDefaults(single_option, option_defaults);
            }
        }

        return (cnt);
    }

    /// This table defines default values for option definitions in DHCPv6
    static const SimpleDefaults OPTION6_DEF_DEFAULTS;

    /// This table defines default values for option definitions in DHCPv4
    static const SimpleDefaults OPTION4_DEF_DEFAULTS;

    /// This table defines default values for options in DHCPv6
    static const SimpleDefaults OPTION6_DEFAULTS;

    /// This table defines default values for options in DHCPv4
    static const SimpleDefaults OPTION4_DEFAULTS;

    /// This table defines default values for both DHCPv4 and DHCPv6
    static const SimpleDefaults GLOBAL6_DEFAULTS;

    /// @brief sets all default values for DHCPv4 and DHCPv6
    ///
    /// This function largely duplicates what SimpleParser4 and SimpleParser6 classes
    /// provide. However, since there are tons of unit-tests in dhcpsrv that need
    /// this functionality and there are good reasons to keep those classes in
    /// src/bin/dhcp{4,6}, the most straightforward way is to simply copy the
    /// minimum code here. Hence this method.
    ///
    /// @todo - TKM, I think this is fairly hideous and we should figure out a
    /// a way to not have to replicate in this fashion.  It may be minimum code
    /// now, but it won't be fairly soon.
    ///
    /// @param config configuration structure to be filled with default values
    /// @param v6 true = DHCPv6, false = DHCPv4
    void setAllDefaults(ElementPtr config, bool v6) {
        if (v6) {
            setAllDefaults(config, GLOBAL6_DEFAULTS, OPTION6_DEFAULTS,
                           OPTION6_DEF_DEFAULTS);
        } else {
            setAllDefaults(config, GLOBAL6_DEFAULTS, OPTION4_DEFAULTS,
                           OPTION4_DEF_DEFAULTS);
        }

        /// D2 client configuration code is in this library
        ConstElementPtr d2_client = config->get("dhcp-ddns");
        if (d2_client) {
            D2ClientConfigParser::setAllDefaults(d2_client);
        }
    }

    /// @brief Convenience method for parsing a configuration
    ///
    /// Given a configuration string, convert it into Elements
    /// and parse them.
    /// @param config is the configuration string to parse
    /// @param v6 boolean value indicating if this is DHCPv6 configuration.
    /// @param set_defaults boolean value indicating if the defaults should
    /// be derived before parsing the configuration.
    ///
    /// @return returns 0 if the configuration parsed successfully,
    /// non-zero otherwise failure.
    int parseConfiguration(const std::string& config, bool v6 = false,
                           bool set_defaults = true) {
        int rcode_ = 1;
        // Turn config into elements.
        // Test json just to make sure its valid.
        ElementPtr json = Element::fromJSON(config);
        EXPECT_TRUE(json);
        if (json) {
            if (set_defaults) {
                setAllDefaults(json, v6);
            }

            ConstElementPtr status = parseElementSet(json, v6);
            ConstElementPtr comment = parseAnswer(rcode_, status);
            error_text_ = comment->stringValue();
            // If error was reported, the error string should contain
            // position of the data element which caused failure.
            if (rcode_ != 0) {
                EXPECT_TRUE(errorContainsPosition(status, "<string>"))
                            << "error text: " << error_text_;
            }
        }

        return (rcode_);
    }

    /// @brief Find an option for a given space and code within the parser
    /// context.
    /// @param space is the space name of the desired option.
    /// @param code is the numeric "type" of the desired option.
    /// @return returns an OptionPtr which points to the found
    /// option or is empty.
    /// ASSERT_ tests don't work inside functions that return values
    OptionPtr getOptionPtr(std::string space, uint32_t code) {
        OptionPtr option_ptr;
        OptionContainerPtr options = CfgMgr::instance().getStagingCfg()->
            getCfgOption()->getAll(space);
        // Should always be able to get options list even if it is empty.
        EXPECT_TRUE(options);
        if (options) {
            // Attempt to find desired option.
            const OptionContainerTypeIndex& idx = options->get<1>();
            const OptionContainerTypeRange& range = idx.equal_range(code);
            int cnt = std::distance(range.first, range.second);
            EXPECT_EQ(1, cnt);
            if (cnt == 1) {
                OptionDescriptor desc = *(idx.begin());
                option_ptr = desc.option_;
                EXPECT_TRUE(option_ptr);
            }
        }

        return (option_ptr);
    }

    /// @brief Find the OptionDescriptor for a given space and code within
    /// the parser context.
    ///
    /// @param space is the space name of the desired option.
    /// @param code is the numeric "type" of the desired option.
    /// @return an OptionDecriptorPtr to the descriptor found or an empty ptr.
    OptionDescriptorPtr getOptionDescriptor(std::string space, uint32_t code) {
        OptionDescriptorPtr od_ptr;
        const auto &cfg_options = CfgMgr::instance().getStagingCfg()->getCfgOption();
        auto od = cfg_options->get(space, code);
        if (od.option_) {
            od_ptr = OptionDescriptor::create(od);
        }

        return (od_ptr);
    }

    /// @brief Wipes the contents of the context to allowing another parsing
    /// during a given test if needed.
    /// @param family protocol family to use during the test, defaults
    /// to AF_INET6
    void reset_context(uint16_t family = AF_INET6){
        // Note set context universe to V6 as it has to be something.
        CfgMgr::instance().clear();
        family_ = family;

        // Ensure no hooks libraries are loaded.
        EXPECT_TRUE(HooksManager::unloadLibraries());

        // Set it to minimal, disabled config
        D2ClientConfigPtr tmp(new D2ClientConfig());
        CfgMgr::instance().setD2ClientConfig(tmp);
    }

    /// Allows the tests to interrogate the state of the libraries (if required).
    const isc::hooks::HookLibsCollection& getLibraries() {
        return (CfgMgr::instance().getStagingCfg()->getHooksConfig().get());
    }

    /// @brief specifies IP protocol family (AF_INET or AF_INET6)
    uint16_t family_;

    /// @brief Error string if the parsing failed
    std::string error_text_;
};

/// This table defines default values for option definitions in DHCPv6
const SimpleDefaults ParseConfigTest::OPTION6_DEF_DEFAULTS = {
    { "record-types", Element::string,  ""},
    { "space",        Element::string,  "dhcp6"},
    { "array",        Element::boolean, "false"},
    { "encapsulate",  Element::string,  "" }
};

/// This table defines default values for option definitions in DHCPv4
const SimpleDefaults ParseConfigTest::OPTION4_DEF_DEFAULTS = {
    { "record-types", Element::string,  ""},
    { "space",        Element::string,  "dhcp4"},
    { "array",        Element::boolean, "false"},
    { "encapsulate",  Element::string,  "" }
};

/// This table defines default values for options in DHCPv6
const SimpleDefaults ParseConfigTest::OPTION6_DEFAULTS = {
    { "space",        Element::string,  "dhcp6"},
    { "csv-format",   Element::boolean, "true"},
    { "always-send",  Element::boolean, "false"},
    { "never-send",   Element::boolean, "false"}
};

/// This table defines default values for options in DHCPv4
const SimpleDefaults ParseConfigTest::OPTION4_DEFAULTS = {
    { "space",        Element::string,  "dhcp4"},
    { "csv-format",   Element::boolean, "true"},
    { "always-send",  Element::boolean, "false"},
    { "never-send",   Element::boolean, "false"}
};

/// This table defines default values for both DHCPv4 and DHCPv6
const SimpleDefaults ParseConfigTest::GLOBAL6_DEFAULTS = {
    { "renew-timer",        Element::integer, "900" },
    { "rebind-timer",       Element::integer, "1800" },
    { "preferred-lifetime", Element::integer, "3600" },
    { "valid-lifetime",     Element::integer, "7200" }
};

/// @brief Option configuration class
///
/// This class handles option-def and option-data which can be recovered
/// using the toElement() method
class CfgOptionsTest : public CfgToElement {
public:
    /// @brief Constructor
    ///
    /// @param cfg the server configuration where to get option-{def,data}
    CfgOptionsTest(SrvConfigPtr cfg) :
        cfg_option_def_(cfg->getCfgOptionDef()),
        cfg_option_(cfg->getCfgOption()) { }

    /// @brief Unparse a configuration object
    ///
    /// @return a pointer to unparsed configuration (a map with
    /// not empty option-def and option-data lists)
    ElementPtr toElement() const {
        ElementPtr result = Element::createMap();
        // Set option-def
        ConstElementPtr option_def = cfg_option_def_->toElement();
        if (!option_def->empty()) {
            result->set("option-def", option_def);
        }
        // Set option-data
        ConstElementPtr option_data = cfg_option_->toElement();
        if (!option_data->empty()) {
            result->set("option-data", option_data);
        }
        return (result);
    }

    /// @brief Run a toElement test (Element version)
    ///
    /// Use the runToElementTest template but add defaults to the config
    ///
    /// @param family the address family
    /// @param config the expected result without defaults
    void runCfgOptionsTest(uint16_t family, ConstElementPtr expected) {
        ConstElementPtr option_def = expected->get("option-def");
        if (option_def) {
            SimpleParser::setListDefaults(option_def,
                                          family == AF_INET ?
                                          ParseConfigTest::OPTION4_DEF_DEFAULTS :
                                          ParseConfigTest::OPTION6_DEF_DEFAULTS);
        }
        ConstElementPtr option_data = expected->get("option-data");
        if (option_data) {
            SimpleParser::setListDefaults(option_data,
                                          family == AF_INET ?
                                          ParseConfigTest::OPTION4_DEFAULTS :
                                          ParseConfigTest::OPTION6_DEFAULTS);
        }
        runToElementTest<CfgOptionsTest>(expected, *this);
    }

    /// @brief Run a toElement test
    ///
    /// Use the runToElementTest template but add defaults to the config
    ///
    /// @param family the address family
    /// @param expected the expected result without defaults
    void runCfgOptionsTest(uint16_t family, std::string config) {
        ConstElementPtr json;
        ASSERT_NO_THROW(json = Element::fromJSON(config)) << config;
        runCfgOptionsTest(family, json);
    }

private:
    /// @brief Pointer to option definitions configuration.
    CfgOptionDefPtr cfg_option_def_;

    /// @brief Reference to options (data) configuration.
    CfgOptionPtr cfg_option_;
};

/// @brief Check basic parsing of option definitions.
///
/// Note that this tests basic operation of the OptionDefinitionListParser and
/// OptionDefinitionParser.  It uses a simple configuration consisting of
/// one definition and verifies that it is parsed and committed to storage
/// correctly.
TEST_F(ParseConfigTest, basicOptionDefTest) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 100,"
        "      \"type\": \"ipv4-address\","
        "      \"array\": false,"
        "      \"record-types\": \"\","
        "      \"space\": \"isc\","
        "      \"encapsulate\": \"\""
        "  } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);


    // Verify that the option definition can be retrieved.
    OptionDefinitionPtr def =
        CfgMgr::instance().getStagingCfg()->getCfgOptionDef()->get("isc", 100);
    ASSERT_TRUE(def);

    // Verify that the option definition is correct.
    EXPECT_EQ("foo", def->getName());
    EXPECT_EQ(100, def->getCode());
    EXPECT_FALSE(def->getArrayType());
    EXPECT_EQ(OPT_IPV4_ADDRESS_TYPE, def->getType());
    EXPECT_TRUE(def->getEncapsulatedSpace().empty());

    // Check if libdhcp++ runtime options have been updated.
    OptionDefinitionPtr def_libdhcp = LibDHCP::getRuntimeOptionDef("isc", 100);
    ASSERT_TRUE(def_libdhcp);

    // The LibDHCP should return a separate instance of the option definition
    // but the values should be equal.
    EXPECT_TRUE(def_libdhcp != def);
    EXPECT_TRUE(*def_libdhcp == *def);

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

/// @brief Check minimal parsing of option definitions.
///
/// Same than basic but without optional parameters set to their default.
TEST_F(ParseConfigTest, minimalOptionDefTest) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 100,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        "  } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);


    // Verify that the option definition can be retrieved.
    OptionDefinitionPtr def =
        CfgMgr::instance().getStagingCfg()->getCfgOptionDef()->get("isc", 100);
    ASSERT_TRUE(def);

    // Verify that the option definition is correct.
    EXPECT_EQ("foo", def->getName());
    EXPECT_EQ(100, def->getCode());
    EXPECT_FALSE(def->getArrayType());
    EXPECT_EQ(OPT_IPV4_ADDRESS_TYPE, def->getType());
    EXPECT_TRUE(def->getEncapsulatedSpace().empty());

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

/// @brief Check parsing of option definitions using default dhcp6 space.
///
/// Same than minimal but using the fact the default universe is V6
/// so the default space is dhcp6
TEST_F(ParseConfigTest, defaultSpaceOptionDefTest) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 10000,"
        "      \"type\": \"ipv6-address\""
        "  } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config, true);
    ASSERT_EQ(0, rcode);


    // Verify that the option definition can be retrieved.
    OptionDefinitionPtr def =
        CfgMgr::instance().getStagingCfg()->getCfgOptionDef()->get(DHCP6_OPTION_SPACE, 10000);
    ASSERT_TRUE(def);

    // Verify that the option definition is correct.
    EXPECT_EQ("foo", def->getName());
    EXPECT_EQ(10000, def->getCode());
    EXPECT_FALSE(def->getArrayType());
    EXPECT_EQ(OPT_IPV6_ADDRESS_TYPE, def->getType());
    EXPECT_TRUE(def->getEncapsulatedSpace().empty());

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

/// @brief Check parsing of option definitions using invalid code fails.
TEST_F(ParseConfigTest, badCodeOptionDefTest) {

    {
        SCOPED_TRACE("negative code");
        std::string config =
            "{ \"option-def\": [ {"
            "      \"name\": \"negative\","
            "      \"code\": -1,"
            "      \"type\": \"ipv6-address\","
            "      \"space\": \"isc\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, true);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("out of range code (v6)");
        std::string config =
            "{ \"option-def\": [ {"
            "      \"name\": \"hundred-thousands\","
            "      \"code\": 100000,"
            "      \"type\": \"ipv6-address\","
            "      \"space\": \"isc\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, true);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("out of range code (v4)");
        family_ = AF_INET;     // Switch to DHCPv4.

        std::string config =
            "{ \"option-def\": [ {"
            "      \"name\": \"thousand\","
            "      \"code\": 1000,"
            "      \"type\": \"ip-address\","
            "      \"space\": \"isc\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, false);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("conflict with PAD");
        family_ = AF_INET;     // Switch to DHCPv4.

        std::string config =
            "{ \"option-def\": [ {"
            "      \"name\": \"zero\","
            "      \"code\": 0,"
            "      \"type\": \"ip-address\","
            "      \"space\": \"dhcp4\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, false);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("conflict with END");
        family_ = AF_INET;     // Switch to DHCPv4.

        std::string config =
            "{ \"option-def\": [ {"
            "      \"name\": \"max\","
            "      \"code\": 255,"
            "      \"type\": \"ip-address\","
            "      \"space\": \"dhcp4\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, false);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("conflict with reserved");

        std::string config =
            "{ \"option-def\": [ {"
            "      \"name\": \"zero\","
            "      \"code\": 0,"
            "      \"type\": \"ipv6-address\","
            "      \"space\": \"dhcp6\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, false);
        ASSERT_NE(0, rcode);
    }
}

/// @brief Check parsing of option definitions using invalid space fails.
TEST_F(ParseConfigTest, badSpaceOptionDefTest) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 100,"
        "      \"type\": \"ipv6-address\","
        "      \"space\": \"-1\""
        "  } ]"
        "}";

    // Verify that the configuration string does not parse.
    int rcode = parseConfiguration(config, true);
    ASSERT_NE(0, rcode);
}

/// @brief Check basic parsing of options.
///
/// Note that this tests basic operation of the OptionDataListParser and
/// OptionDataParser.  It uses a simple configuration consisting of one
/// one definition and matching option data.  It verifies that the option
/// is parsed and committed to storage correctly.
TEST_F(ParseConfigTest, basicOptionDataTest) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 100,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"code\": 100,"
        "    \"data\": \"192.0.2.0\","
        "    \"csv-format\": true,"
        "    \"always-send\": false"
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt_ptr = getOptionPtr("isc", 100);
    ASSERT_TRUE(opt_ptr);

    // Verify that the option data is correct.
    std::string val = "type=00100, len=00004: 192.0.2.0 (ipv4-address)";

    EXPECT_EQ(val, opt_ptr->toText());

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

/// @brief Check parsing of options with code 0.
TEST_F(ParseConfigTest, optionDataTest0) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 0,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"code\": 0,"
        "    \"data\": \"192.0.2.0\","
        "    \"csv-format\": true,"
        "    \"always-send\": false"
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt_ptr = getOptionPtr("isc", 0);
    ASSERT_TRUE(opt_ptr);

    // Verify that the option data is correct.
    std::string val = "type=00000, len=00004: 192.0.2.0 (ipv4-address)";

    EXPECT_EQ(val, opt_ptr->toText());

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

/// @brief Check parsing of options with code 255.
TEST_F(ParseConfigTest, optionDataTest255) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 255,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"code\": 255,"
        "    \"data\": \"192.0.2.0\","
        "    \"csv-format\": true,"
        "    \"always-send\": false"
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt_ptr = getOptionPtr("isc", 255);
    ASSERT_TRUE(opt_ptr);

    // Verify that the option data is correct.
    std::string val = "type=00255, len=00004: 192.0.2.0 (ipv4-address)";

    EXPECT_EQ(val, opt_ptr->toText());

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

/// @brief Check minimal parsing of options.
///
/// Same than basic but without optional parameters set to their default.
TEST_F(ParseConfigTest, minimalOptionDataTest) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 100,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"data\": \"192.0.2.0\""
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt_ptr = getOptionPtr("isc", 100);
    ASSERT_TRUE(opt_ptr);

    // Verify that the option data is correct.
    std::string val = "type=00100, len=00004: 192.0.2.0 (ipv4-address)";

    EXPECT_EQ(val, opt_ptr->toText());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("code", Element::create(100));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);
}

/// @brief Check parsing of unknown options fails.
TEST_F(ParseConfigTest, unknownOptionDataTest) {

    // Configuration string.
    std::string config =
        "{ \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"data\": \"01\","
        "    \"space\": \"bar\""
        " } ]"
        "}";

    // Verify that the configuration string does not parse.
    int rcode = parseConfiguration(config, true);
    ASSERT_NE(0, rcode);
}

/// @brief Check parsing of option data using invalid code fails.
TEST_F(ParseConfigTest, badCodeOptionDataTest) {

    {
        SCOPED_TRACE("negative code");
        std::string config =
            "{ \"option-data\": [ {"
            "      \"code\": -1,"
            "      \"data\": \"01\","
            "      \"space\": \"isc\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, true);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("out of range code (v6)");
        std::string config =
            "{ \"option-data\": [ {"
            "      \"code\": 100000,"
            "      \"data\": \"01\","
            "      \"space\": \"isc\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, true);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("out of range code (v4)");
        family_ = AF_INET;     // Switch to DHCPv4.

        std::string config =
            "{ \"option-data\": [ {"
            "      \"code\": 1000,"
            "      \"data\": \"01\","
            "      \"space\": \"isc\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, false);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("conflict with PAD");
        family_ = AF_INET;     // Switch to DHCPv4.

        std::string config =
            "{ \"option-data\": [ {"
            "      \"code\": 0,"
            "      \"data\": \"01\","
            "      \"csv-format\": false,"
            "      \"space\": \"dhcp4\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, false);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("conflict with END");
        family_ = AF_INET;     // Switch to DHCPv4.

        std::string config =
            "{ \"option-data\": [ {"
            "      \"code\": 255,"
            "      \"data\": \"01\","
            "      \"csv-format\": false,"
            "      \"space\": \"dhcp4\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, false);
        ASSERT_NE(0, rcode);
    }

    {
        SCOPED_TRACE("conflict with reserved");
        family_ = AF_INET6;    // Switch to DHCPv6.

        std::string config =
            "{ \"option-data\": [ {"
            "      \"code\": 0,"
            "      \"data\": \"01\","
            "      \"csv-format\": false,"
            "      \"space\": \"dhcp6\""
            "  } ]"
            "}";

        int rcode = parseConfiguration(config, false);
        ASSERT_NE(0, rcode);
    }
}

/// @brief Check parsing of options with invalid space fails.
TEST_F(ParseConfigTest, badSpaceOptionDataTest) {

    // Configuration string.
    std::string config =
        "{ \"option-data\": [ {"
        "    \"code\": 100,"
        "    \"data\": \"01\","
        "    \"space\": \"-1\""
        " } ]"
        "}";

    // Verify that the configuration string does not parse.
    int rcode = parseConfiguration(config, true);
    ASSERT_NE(0, rcode);
}

/// @brief Check parsing of options with escape characters.
///
/// Note that this tests basic operation of the OptionDataListParser and
/// OptionDataParser.  It uses a simple configuration consisting of one
/// one definition and matching option data.  It verifies that the option
/// is parsed and committed to storage correctly and that its content
/// has the actual character (e.g. an actual backslash, not double backslash).
TEST_F(ParseConfigTest, escapedOptionDataTest) {

    family_ = AF_INET;

    // We need to use double escapes here. The first backslash will
    // be consumed by C++ preprocessor, so the actual string will
    // have two backslash characters: \\SMSBoot\\x64\\wdsnbp.com.
    //
    std::string config =
        "{\"option-data\": [ {"
        "    \"name\": \"boot-file-name\","
        "    \"data\": \"\\\\SMSBoot\\\\x64\\\\wdsnbp.com\""
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt = getOptionPtr(DHCP4_OPTION_SPACE, DHO_BOOT_FILE_NAME);
    ASSERT_TRUE(opt);

    util::OutputBuffer buf(100);

    uint8_t exp[] = { DHO_BOOT_FILE_NAME, 23, '\\', 'S', 'M', 'S', 'B', 'o', 'o',
                      't', '\\', 'x', '6', '4', '\\', 'w', 'd', 's', 'n', 'b',
                      'p', '.', 'c', 'o', 'm' };
    ASSERT_EQ(25, sizeof(exp));

    opt->pack(buf);
    EXPECT_EQ(Option::OPTION4_HDR_LEN + 23, buf.getLength());

    EXPECT_TRUE(0 == memcmp(buf.getData(), exp, 25));

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("code", Element::create(DHO_BOOT_FILE_NAME));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);
}

// This test checks behavior of the configuration parser for option data
// for different values of csv-format parameter and when there is an option
// definition present.
TEST_F(ParseConfigTest, optionDataCSVFormatWithOptionDef) {
    std::string config =
        "{ \"option-data\": [ {"
        "    \"name\": \"swap-server\","
        "    \"space\": \"dhcp4\","
        "    \"code\": 16,"
        "    \"data\": \"192.0.2.0\""
        " } ]"
        "}";

    // The default universe is V6. We need to change it to use dhcp4 option
    // space.
    family_ = AF_INET;
    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config));
    ASSERT_EQ(0, rcode);

    // Verify that the option data is correct.
    OptionCustomPtr addr_opt = boost::dynamic_pointer_cast<
        OptionCustom>(getOptionPtr(DHCP4_OPTION_SPACE, 16));
    ASSERT_TRUE(addr_opt);
    EXPECT_EQ("192.0.2.0", addr_opt->readAddress().toText());

    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);

    // Explicitly enable csv-format.
    CfgMgr::instance().clear();
    config =
        "{ \"option-data\": [ {"
        "    \"name\": \"swap-server\","
        "    \"space\": \"dhcp4\","
        "    \"code\": 16,"
        "    \"csv-format\": true,"
        "    \"data\": \"192.0.2.0\""
        " } ]"
        "}";
    ASSERT_NO_THROW(rcode = parseConfiguration(config));
    ASSERT_EQ(0, rcode);

    // Verify that the option data is correct.
    addr_opt = boost::dynamic_pointer_cast<
        OptionCustom>(getOptionPtr(DHCP4_OPTION_SPACE, 16));
    ASSERT_TRUE(addr_opt);
    EXPECT_EQ("192.0.2.0", addr_opt->readAddress().toText());

    // To make runToElementTest to work the csv-format must be removed...

    // Explicitly disable csv-format and use hex instead.
    CfgMgr::instance().clear();
    config =
        "{ \"option-data\": [ {"
        "    \"name\": \"swap-server\","
        "    \"space\": \"dhcp4\","
        "    \"code\": 16,"
        "    \"csv-format\": false,"
        "    \"data\": \"C0000200\""
        " } ]"
        "}";
    ASSERT_NO_THROW(rcode = parseConfiguration(config));
    ASSERT_EQ(0, rcode);

    // Verify that the option data is correct.
    addr_opt = boost::dynamic_pointer_cast<
        OptionCustom>(getOptionPtr(DHCP4_OPTION_SPACE, 16));
    ASSERT_TRUE(addr_opt);
    EXPECT_EQ("192.0.2.0", addr_opt->readAddress().toText());

    CfgOptionsTest cfg2(CfgMgr::instance().getStagingCfg());
    cfg2.runCfgOptionsTest(family_, config);
}

// This test verifies that definitions of standard encapsulated
// options can be used.
TEST_F(ParseConfigTest, encapsulatedOptionData) {
    std::string config =
        "{ \"option-data\": [ {"
        "    \"space\": \"s46-cont-mape-options\","
        "    \"name\": \"s46-rule\","
        "    \"data\": \"1, 0, 24, 192.0.2.0, 2001:db8:1::/64\""
        " } ]"
        "}";

    // Make sure that we're using correct universe.
    family_ = AF_INET6;
    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config));
    ASSERT_EQ(0, rcode);

    // Verify that the option data is correct.
    OptionCustomPtr s46_rule = boost::dynamic_pointer_cast<OptionCustom>
        (getOptionPtr(MAPE_V6_OPTION_SPACE, D6O_S46_RULE));
    ASSERT_TRUE(s46_rule);

    uint8_t flags = 0;
    uint8_t ea_len = 0;
    uint8_t prefix4_len = 0;
    IOAddress ipv4_prefix(IOAddress::IPV4_ZERO_ADDRESS());
    PrefixTuple ipv6_prefix(PrefixLen(0), IOAddress::IPV6_ZERO_ADDRESS());;

    ASSERT_NO_THROW({
        flags = s46_rule->readInteger<uint8_t>(0);
        ea_len = s46_rule->readInteger<uint8_t>(1);
        prefix4_len = s46_rule->readInteger<uint8_t>(2);
        ipv4_prefix = s46_rule->readAddress(3);
        ipv6_prefix = s46_rule->readPrefix(4);
    });

    EXPECT_EQ(1, flags);
    EXPECT_EQ(0, ea_len);
    EXPECT_EQ(24, prefix4_len);
    EXPECT_EQ("192.0.2.0", ipv4_prefix.toText());
    EXPECT_EQ(64, ipv6_prefix.first.asUnsigned());
    EXPECT_EQ("2001:db8:1::", ipv6_prefix.second.toText());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("code", Element::create(D6O_S46_RULE));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);
}

// This test checks behavior of the configuration parser for option data
// for different values of csv-format parameter and when there is no
// option definition.
TEST_F(ParseConfigTest, optionDataCSVFormatNoOptionDef) {
    // This option doesn't have any definition. It is ok to use such
    // an option but the data should be specified in hex, not as CSV.
    // Note that the parser will by default use the CSV format for the
    // data but only in case there is a suitable option definition.
    std::string config =
        "{ \"option-data\": [ {"
        "    \"name\": \"foo-name\","
        "    \"space\": \"dhcp6\","
        "    \"code\": 25000,"
        "    \"data\": \"1, 2, 5\""
        " } ]"
        "}";
    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_NE(0, rcode);

    CfgMgr::instance().clear();
    // The data specified here will work both for CSV format and hex format.
    // What we want to test here is that when the csv-format is enforced, the
    // parser will fail because of lack of an option definition.
    config =
        "{ \"option-data\": [ {"
        "    \"name\": \"foo-name\","
        "    \"space\": \"dhcp6\","
        "    \"code\": 25000,"
        "    \"csv-format\": true,"
        "    \"data\": \"0\""
        " } ]"
        "}";
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_NE(0, rcode);

    CfgMgr::instance().clear();
    // The same test case as above, but for the data specified in hex should
    // be successful.
    config =
        "{ \"option-data\": [ {"
        "    \"name\": \"foo-name\","
        "    \"space\": \"dhcp6\","
        "    \"code\": 25000,"
        "    \"csv-format\": false,"
        "    \"data\": \"0\""
        " } ]"
        "}";
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    ASSERT_EQ(0, rcode);
    OptionPtr opt = getOptionPtr(DHCP6_OPTION_SPACE, 25000);
    ASSERT_TRUE(opt);
    ASSERT_EQ(1, opt->getData().size());
    EXPECT_EQ(0, opt->getData()[0]);

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->remove("name");
    opt_data->set("data", Element::create(std::string("00")));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);

    CfgMgr::instance().clear();
    // When csv-format is not specified, the parser will check if the definition
    // exists or not. Since there is no definition, the parser will accept the
    // data in hex.
    config =
        "{ \"option-data\": [ {"
        "    \"name\": \"foo-name\","
        "    \"space\": \"dhcp6\","
        "    \"code\": 25000,"
        "    \"csv-format\": false,"
        "    \"data\": \"123456\""
        " } ]"
        "}";
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_EQ(0, rcode);
    opt = getOptionPtr(DHCP6_OPTION_SPACE, 25000);
    ASSERT_TRUE(opt);
    ASSERT_EQ(3, opt->getData().size());
    EXPECT_EQ(0x12, opt->getData()[0]);
    EXPECT_EQ(0x34, opt->getData()[1]);
    EXPECT_EQ(0x56, opt->getData()[2]);

    expected = Element::fromJSON(config);
    opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->remove("name");
    CfgOptionsTest cfg2(CfgMgr::instance().getStagingCfg());
    cfg2.runCfgOptionsTest(family_, expected);
}

// This test verifies that the option name is not mandatory, if the option
// code has been specified.
TEST_F(ParseConfigTest, optionDataNoName) {
    std::string config =
        "{ \"option-data\": [ {"
        "    \"space\": \"dhcp6\","
        "    \"code\": 23,"
        "    \"data\": \"2001:db8:1::1\""
        " } ]"
        "}";
    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_EQ(0, rcode);
    Option6AddrLstPtr opt = boost::dynamic_pointer_cast<
        Option6AddrLst>(getOptionPtr(DHCP6_OPTION_SPACE, 23));
    ASSERT_TRUE(opt);
    ASSERT_EQ(1, opt->getAddresses().size());
    EXPECT_EQ( "2001:db8:1::1", opt->getAddresses()[0].toText());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("name", Element::create(std::string("dns-servers")));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);
}

// This test verifies that the option code is not mandatory, if the option
// name has been specified.
TEST_F(ParseConfigTest, optionDataNoCode) {
    std::string config =
        "{ \"option-data\": [ {"
        "    \"space\": \"dhcp6\","
        "    \"name\": \"dns-servers\","
        "    \"data\": \"2001:db8:1::1\""
        " } ]"
        "}";
    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_EQ(0, rcode);
    Option6AddrLstPtr opt = boost::dynamic_pointer_cast<
        Option6AddrLst>(getOptionPtr(DHCP6_OPTION_SPACE, 23));
    ASSERT_TRUE(opt);
    ASSERT_EQ(1, opt->getAddresses().size());
    EXPECT_EQ( "2001:db8:1::1", opt->getAddresses()[0].toText());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("code", Element::create(D6O_NAME_SERVERS));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);
}

// This test verifies that the option data configuration with a minimal
// set of parameters works as expected.
TEST_F(ParseConfigTest, optionDataMinimal) {
    std::string config =
        "{ \"option-data\": [ {"
        "    \"name\": \"dns-servers\","
        "    \"data\": \"2001:db8:1::10\""
        " } ]"
        "}";
    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_EQ(0, rcode);
    Option6AddrLstPtr opt = boost::dynamic_pointer_cast<
        Option6AddrLst>(getOptionPtr(DHCP6_OPTION_SPACE, 23));
    ASSERT_TRUE(opt);
    ASSERT_EQ(1, opt->getAddresses().size());
    EXPECT_EQ( "2001:db8:1::10", opt->getAddresses()[0].toText());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("code", Element::create(D6O_NAME_SERVERS));
    opt_data->set("space", Element::create(std::string(DHCP6_OPTION_SPACE)));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);

    CfgMgr::instance().clear();
    // This time using an option code.
    config =
        "{ \"option-data\": [ {"
        "    \"code\": 23,"
        "    \"data\": \"2001:db8:1::20\""
        " } ]"
        "}";
    rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_EQ(0, rcode);
    opt = boost::dynamic_pointer_cast<Option6AddrLst>(getOptionPtr(DHCP6_OPTION_SPACE,
                                                                   23));
    ASSERT_TRUE(opt);
    ASSERT_EQ(1, opt->getAddresses().size());
    EXPECT_EQ( "2001:db8:1::20", opt->getAddresses()[0].toText());

    expected = Element::fromJSON(config);
    opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("name", Element::create(std::string("dns-servers")));
    opt_data->set("space", Element::create(std::string(DHCP6_OPTION_SPACE)));
    CfgOptionsTest cfg2(CfgMgr::instance().getStagingCfg());
    cfg2.runCfgOptionsTest(family_, expected);
}

// This test verifies that the option data configuration with a minimal
// set of parameters works as expected when option definition is
// created in the configuration file.
TEST_F(ParseConfigTest, optionDataMinimalWithOptionDef) {
    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo-name\","
        "      \"code\": 2345,"
        "      \"type\": \"ipv6-address\","
        "      \"array\": true,"
        "      \"space\": \"dhcp6\""
        "  } ],"
        "  \"option-data\": [ {"
        "    \"name\": \"foo-name\","
        "    \"data\": \"2001:db8:1::10, 2001:db8:1::123\""
        " } ]"
        "}";

    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_EQ(0, rcode);
    Option6AddrLstPtr opt = boost::dynamic_pointer_cast<
        Option6AddrLst>(getOptionPtr(DHCP6_OPTION_SPACE, 2345));
    ASSERT_TRUE(opt);
    ASSERT_EQ(2, opt->getAddresses().size());
    EXPECT_EQ("2001:db8:1::10", opt->getAddresses()[0].toText());
    EXPECT_EQ("2001:db8:1::123", opt->getAddresses()[1].toText());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("code", Element::create(2345));
    opt_data->set("space", Element::create(std::string(DHCP6_OPTION_SPACE)));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);

    CfgMgr::instance().clear();
    // Do the same test but now use an option code.
    config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo-name\","
        "      \"code\": 2345,"
        "      \"type\": \"ipv6-address\","
        "      \"array\": true,"
        "      \"space\": \"dhcp6\""
        "  } ],"
        "  \"option-data\": [ {"
        "    \"code\": 2345,"
        "    \"data\": \"2001:db8:1::10, 2001:db8:1::123\""
        " } ]"
        "}";

    rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_EQ(0, rcode);
    opt = boost::dynamic_pointer_cast<Option6AddrLst>(getOptionPtr(DHCP6_OPTION_SPACE,
                                                                   2345));
    ASSERT_TRUE(opt);
    ASSERT_EQ(2, opt->getAddresses().size());
    EXPECT_EQ("2001:db8:1::10", opt->getAddresses()[0].toText());
    EXPECT_EQ("2001:db8:1::123", opt->getAddresses()[1].toText());

    expected = Element::fromJSON(config);
    opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("name", Element::create(std::string("foo-name")));
    opt_data->set("space", Element::create(std::string(DHCP6_OPTION_SPACE)));
    CfgOptionsTest cfg2(CfgMgr::instance().getStagingCfg());
    cfg2.runCfgOptionsTest(family_, expected);
}

// This test verifies an empty option data configuration is supported.
TEST_F(ParseConfigTest, emptyOptionData) {
    // Configuration string.
    const std::string config =
        "{ \"option-data\": [ {"
        "    \"name\": \"dhcp4o6-server-addr\""
        " } ]"
        "}";

    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config, true));
    EXPECT_EQ(0, rcode);
    const Option6AddrLstPtr opt = boost::dynamic_pointer_cast<
        Option6AddrLst>(getOptionPtr(DHCP6_OPTION_SPACE, D6O_DHCPV4_O_DHCPV6_SERVER));
    ASSERT_TRUE(opt);
    ASSERT_EQ(0, opt->getAddresses().size());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("code", Element::create(D6O_DHCPV4_O_DHCPV6_SERVER));
    opt_data->set("space", Element::create(std::string(DHCP6_OPTION_SPACE)));
    opt_data->set("csv-format", Element::create(false));
    opt_data->set("data", Element::create(std::string("")));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);
}

// This test verifies an option data without suboptions is supported
TEST_F(ParseConfigTest, optionDataNoSubOption) {
    // Configuration string. A global definition for option 43 is needed.
    const std::string config =
        "{ \"option-def\": [ {"
        " \"name\": \"vendor-encapsulated-options\","
        " \"code\": 43,"
        " \"type\": \"empty\","
        " \"space\": \"dhcp4\","
        " \"encapsulate\": \"vendor-encapsulated-options\""
        " } ],"
        " \"option-data\": [ {"
        "    \"name\": \"vendor-encapsulated-options\""
        " } ]"
        "}";

    // The default universe is V6. We need to change it to use dhcp4 option
    // space.
    family_ = AF_INET;
    int rcode = 0;
    ASSERT_NO_THROW(rcode = parseConfiguration(config));
    EXPECT_EQ(0, rcode);
    const OptionPtr opt = getOptionPtr(DHCP4_OPTION_SPACE, DHO_VENDOR_ENCAPSULATED_OPTIONS);
    ASSERT_TRUE(opt);
    ASSERT_EQ(0, opt->getOptions().size());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->set("code", Element::create(DHO_VENDOR_ENCAPSULATED_OPTIONS));
    opt_data->set("space", Element::create(std::string(DHCP4_OPTION_SPACE)));
    opt_data->set("csv-format", Element::create(false));
    opt_data->set("data", Element::create(std::string("")));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);
}

// This tests option-data in CSV format and embedded commas.
TEST_F(ParseConfigTest, commaCSVFormatOptionData) {

    // Configuration string.
    std::string config =
        "{ \"option-data\": [ {"
        "     \"csv-format\": true,"
        "     \"code\": 41,"
        "     \"data\": \"EST5EDT4\\\\,M3.2.0/02:00\\\\,M11.1.0/02:00\","
        "     \"space\": \"dhcp6\""
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config, true);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt = getOptionPtr(DHCP6_OPTION_SPACE, 41);
    ASSERT_TRUE(opt);

    // Get the option as an option string.
    OptionStringPtr opt_str = boost::dynamic_pointer_cast<OptionString>(opt);
    ASSERT_TRUE(opt_str);


    // Verify that the option data is correct.
    string val = "EST5EDT4,M3.2.0/02:00,M11.1.0/02:00";
    EXPECT_EQ(val, opt_str->getValue());

    ElementPtr expected = Element::fromJSON(config);
    ElementPtr opt_data = expected->get("option-data")->getNonConst(0);
    opt_data->remove("csv-format");
    opt_data->set("name", Element::create(std::string("new-posix-timezone")));
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, expected);
}

// Verifies that hex literals can support a variety of formats.
TEST_F(ParseConfigTest, hexOptionData) {

    // All of the following variants should parse correctly
    // into the same two IPv4 addresses: 12.0.3.1 and 192.0.3.2
    std::vector<std::string> valid_hexes = {
        "0C000301C0000302", // even number
        "C000301C0000302",  // odd number
        "0C 00 03 01 C0 00 03 02", // spaces
        "0C:00:03:01:C0:00:03:02", // colons
        "0x0C000301C0000302",  // 0x
        "C 0 3 1 C0 0 3 02",   // one or two digit octets
        "0x0c000301C0000302"   // upper or lower case digits
    };

    for (auto const& hex_str : valid_hexes) {
        ostringstream os;
        os <<
            "{ \n"
            "  \"option-data\": [ { \n"
            "    \"name\": \"domain-name-servers\", \n"
            "    \"code\": 6, \n"
            "    \"space\": \"dhcp4\", \n"
            "    \"csv-format\": false, \n"
            "    \"data\": \"" << hex_str << "\" \n"
            " } ] \n"
            "} \n";

        reset_context(AF_INET);
        int rcode = 0;
        ASSERT_NO_THROW(rcode = parseConfiguration(os.str(), true));
        EXPECT_EQ(0, rcode);

        Option4AddrLstPtr opt = boost::dynamic_pointer_cast<Option4AddrLst>
                                (getOptionPtr(DHCP4_OPTION_SPACE, 6));
        ASSERT_TRUE(opt);
        ASSERT_EQ(2, opt->getAddresses().size());
        EXPECT_EQ("12.0.3.1", opt->getAddresses()[0].toText());
        EXPECT_EQ("192.0.3.2", opt->getAddresses()[1].toText());
    }
}

// Verifies that binary option data can be configured with either
// "'strings'" or hex literals.
TEST_F(ParseConfigTest, stringOrHexBinaryData) {
    // Structure the defines a given test scenario
    struct Scenario {
        std::string description_;  // describes the scenario for logging
        std::string str_data_;     // configured data value of the option
        std::vector<uint8_t> exp_binary_; // expected parsed binary data
        std::string exp_error_;    // expected error test for invalid input
    };

    // Convenience value to use for initting valid scenarios
    std::string no_error("");

    // Valid and invalid scenarios we will test.
    // Note we are not concerned with the varitions of valid or invalid
    // hex literals those are tested elsewhere.
    std::vector<Scenario> scenarios = {
        {
            "valid hex digits",
            "0C:00:03:01:C0:00:03:02",
            {0x0C,0x00,0x03,0x01,0xC0,0x00,0x03,0x02},
            no_error
        },
        {
            "valid string",
            "'abcdefghijk'",
            {0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B},
            no_error
        },
        {
            "valid empty",
            "",
            {},
            no_error
        },
        {
            "invalid empty",
            "''",
            {},
            "Configuration parsing failed: option data is not a valid string"
            " of hexadecimal digits: '' (<string>:7:13)"
        },
        {
            "missing end quote",
            "'abcdefghijk",
            {},
            "Configuration parsing failed: option data is not a valid string"
            " of hexadecimal digits: 'abcdefghijk (<string>:7:13)"
        },
        {
            "missing open quote",
            "abcdefghijk'",
            {},
            "Configuration parsing failed: option data is not a valid string"
            " of hexadecimal digits: abcdefghijk' (<string>:7:13)"
        },
        {
            "no quotes",
            "abcdefghijk",
            {},
            "Configuration parsing failed: option data is not a valid string"
            " of hexadecimal digits: abcdefghijk (<string>:7:13)"
        }
    };

    // Iterate over our test scenarios
    for (auto const& scenario : scenarios) {
        SCOPED_TRACE(scenario.description_);
        {
            // Build the configuration text.
            ostringstream os;
            os <<
                "{ \n"
                "  \"option-data\": [ { \n"
                "    \"name\": \"user-class\", \n"
                "    \"code\": 77, \n"
                "    \"space\": \"dhcp4\", \n"
                "    \"csv-format\": false, \n"
                "    \"data\": \"" << scenario.str_data_ << "\" \n"
                " } ] \n"
                "} \n";

            // Attempt to parse it.
            reset_context(AF_INET);
            int rcode = 0;
            ASSERT_NO_THROW(rcode = parseConfiguration(os.str(), true));

            if (!scenario.exp_error_.empty()) {
                // We expected to fail, did we?
                ASSERT_NE(0, rcode);
                // Did we fail for the reason we think we should?
                EXPECT_EQ(error_text_, scenario.exp_error_);
            } else {
                // We expected to succeed, did we?
                ASSERT_EQ(0, rcode);
                OptionPtr opt = getOptionPtr(DHCP4_OPTION_SPACE, 77);
                ASSERT_TRUE(opt);
                // Verify the parsed data is correct.
                EXPECT_EQ(opt->getData(), scenario.exp_binary_);
            }
        }
    }
}


/// The next set of tests check basic operation of the HooksLibrariesParser.
//
// Convenience function to set a configuration of zero or more hooks
// libraries:
//
// lib1 - No parameters
// lib2 - Empty parameters statement
// lib3 - Valid parameters
std::string
setHooksLibrariesConfig(const char* lib1 = NULL, const char* lib2 = NULL,
                        const char* lib3 = NULL) {
    const string lbrace("{");
    const string rbrace("}");
    const string quote("\"");
    const string comma_space(", ");
    const string library("\"library\": ");

    string config = string("{ \"hooks-libraries\": [");
    if (lib1 != NULL) {
        // Library 1 has no parameters
        config += lbrace;
        config += library + quote + std::string(lib1) + quote;
        config += rbrace;

        if (lib2 != NULL) {
            // Library 2 has an empty parameters statement
            config += comma_space + lbrace;
            config += library + quote + std::string(lib2) + quote + comma_space;
            config += string("\"parameters\": {}");
            config += rbrace;

            if (lib3 != NULL) {
                // Library 3 has valid parameters
                config += comma_space + lbrace;
                config += library + quote + std::string(lib3) + quote + comma_space;
                config += string("\"parameters\": {");
                config += string("    \"svalue\": \"string value\", ");
                config += string("    \"ivalue\": 42, ");     // Integer value
                config += string("    \"bvalue\": true");     // Boolean value
                config += string("}");
                config += rbrace;
            }
        }
    }
    config += std::string("] }");

    return (config);
}

/// @brief Check parsing of a v4 option with a client-class list.
TEST_F(ParseConfigTest, optionDataClientClasses4) {
    family_ = AF_INET;
    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 0,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"code\": 0,"
        "    \"data\": \"192.0.2.0\","
        "    \"csv-format\": true,"
        "    \"always-send\": false,"
        "    \"client-classes\": [ \"water\", \"melon\" ]"
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt_ptr = getOptionPtr("isc", 0);
    ASSERT_TRUE(opt_ptr);

    // Verify the option descriptor's client-classes lists is correct.
    ClientClasses exp_cc("water, melon");
    OptionDescriptorPtr od = getOptionDescriptor("isc", 0);
    ASSERT_TRUE(od);
    EXPECT_EQ(od->client_classes_, exp_cc);

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

/// @brief Check parsing of a v4 option with a client-class list.
TEST_F(ParseConfigTest, optionDataClientClassesEmpty4) {
    family_ = AF_INET;
    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 0,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"code\": 0,"
        "    \"data\": \"192.0.2.0\","
        "    \"csv-format\": true,"
        "    \"always-send\": false,"
        "    \"client-classes\": []"
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt_ptr = getOptionPtr("isc", 0);
    ASSERT_TRUE(opt_ptr);

    // Verify the option descriptor's client-classes list is empty.
    OptionDescriptorPtr od = getOptionDescriptor("isc", 0);
    ASSERT_TRUE(od);
    EXPECT_TRUE(od->client_classes_.empty());

    // We skip unparse test because client-classes is only emitted if not empty.
}

/// @brief Check parsing of a v6 option with a client-class list.
TEST_F(ParseConfigTest, optionDataClientClasses6) {
    family_ = AF_INET6;
    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 0,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"code\": 0,"
        "    \"data\": \"192.0.2.0\","
        "    \"csv-format\": true,"
        "    \"always-send\": false,"
        "    \"client-classes\": [ \"water\", \"melon\" ]"
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt_ptr = getOptionPtr("isc", 0);
    ASSERT_TRUE(opt_ptr);

    // Verify the option descriptor's client-classes lists is correct.
    ClientClasses exp_cc("water, melon");
    OptionDescriptorPtr od = getOptionDescriptor("isc", 0);
    ASSERT_TRUE(od);
    EXPECT_EQ(od->client_classes_, exp_cc);

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

/// @brief Check parsing of a v4 option with a client-class list.
TEST_F(ParseConfigTest, optionDataClientClassesEmpty6) {
    family_ = AF_INET6;
    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 0,"
        "      \"type\": \"ipv4-address\","
        "      \"space\": \"isc\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"code\": 0,"
        "    \"data\": \"192.0.2.0\","
        "    \"csv-format\": true,"
        "    \"always-send\": false,"
        "    \"client-classes\": []"
        " } ]"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionPtr opt_ptr = getOptionPtr("isc", 0);
    ASSERT_TRUE(opt_ptr);

    // Verify the option descriptor's client-classes list is empty.
    OptionDescriptorPtr od = getOptionDescriptor("isc", 0);
    ASSERT_TRUE(od);
    EXPECT_TRUE(od->client_classes_.empty());

    // We skip unparse test because client-classes is only emitted if not empty.
}

// hooks-libraries element that does not contain anything.
TEST_F(ParseConfigTest, noHooksLibraries) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Create an empty hooks-libraries configuration element.
    const string config = setHooksLibrariesConfig();

    // Verify that the configuration string parses.
    const int rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that the configuration object unparses.
    ConstElementPtr expected;
    ASSERT_NO_THROW(expected =
                    Element::fromJSON(config)->get("hooks-libraries"));
    ASSERT_TRUE(expected);
    const HooksConfig& cfg =
        CfgMgr::instance().getStagingCfg()->getHooksConfig();
    runToElementTest<HooksConfig>(expected, cfg);

    // Check that the parser recorded nothing.
    isc::hooks::HookLibsCollection libraries = getLibraries();
    EXPECT_TRUE(libraries.empty());

    // Check that there are still no libraries loaded.
    hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());
}

// hooks-libraries element that contains a single library.
TEST_F(ParseConfigTest, oneHooksLibrary) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Configuration with hooks-libraries set to a single library.
    const string config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1);

    // Verify that the configuration string parses.
    const int rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that the configuration object unparses.
    ConstElementPtr expected;
    ASSERT_NO_THROW(expected =
                    Element::fromJSON(config)->get("hooks-libraries"));
    ASSERT_TRUE(expected);
    const HooksConfig& cfg =
        CfgMgr::instance().getStagingCfg()->getHooksConfig();
    runToElementTest<HooksConfig>(expected, cfg);

    // Check that the parser recorded a single library.
    isc::hooks::HookLibsCollection libraries = getLibraries();
    ASSERT_EQ(1, libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, libraries[0].first);

    // Check that the change was propagated to the hooks manager.
    hooks_libraries = HooksManager::getLibraryNames();
    ASSERT_EQ(1, hooks_libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, hooks_libraries[0]);
}

// hooks-libraries element that contains two libraries
TEST_F(ParseConfigTest, twoHooksLibraries) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Configuration with hooks-libraries set to two libraries.
    const string config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1,
                                                  CALLOUT_LIBRARY_2);

    // Verify that the configuration string parses.
    const int rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that the configuration object unparses.
    ConstElementPtr expected;
    ASSERT_NO_THROW(expected =
                    Element::fromJSON(config)->get("hooks-libraries"));
    ASSERT_TRUE(expected);
    const HooksConfig& cfg =
        CfgMgr::instance().getStagingCfg()->getHooksConfig();
    runToElementTest<HooksConfig>(expected, cfg);

    // Check that the parser recorded two libraries in the expected order.
    isc::hooks::HookLibsCollection libraries = getLibraries();
    ASSERT_EQ(2, libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, libraries[0].first);
    EXPECT_EQ(CALLOUT_LIBRARY_2, libraries[1].first);

    // Verify that the change was propagated to the hooks manager.
    hooks_libraries = HooksManager::getLibraryNames();
    ASSERT_EQ(2, hooks_libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, hooks_libraries[0]);
    EXPECT_EQ(CALLOUT_LIBRARY_2, hooks_libraries[1]);
}

// Configure with two libraries, then reconfigure with the same libraries.
TEST_F(ParseConfigTest, reconfigureSameHooksLibraries) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Configuration with hooks-libraries set to two libraries.
    const std::string config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1,
                                                       CALLOUT_LIBRARY_2);

    // Verify that the configuration string parses. The twoHooksLibraries
    // test shows that the list will be as expected.
    int rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that the configuration object unparses.
    ConstElementPtr expected;
    ASSERT_NO_THROW(expected =
                    Element::fromJSON(config)->get("hooks-libraries"));
    ASSERT_TRUE(expected);
    const HooksConfig& cfg =
        CfgMgr::instance().getStagingCfg()->getHooksConfig();
    runToElementTest<HooksConfig>(expected, cfg);

    // The previous test shows that the parser correctly recorded the two
    // libraries and that they loaded correctly.

    // Parse the string again.
    rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // The list has not changed between the two parse operations. However,
    // the parameters (or the files they could point to) could have
    // changed, so the libraries are reloaded anyway.
    const HooksConfig& cfg2 =
        CfgMgr::instance().getStagingCfg()->getHooksConfig();
    runToElementTest<HooksConfig>(expected, cfg2);
    isc::hooks::HookLibsCollection libraries = getLibraries();
    ASSERT_EQ(2, libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, libraries[0].first);
    EXPECT_EQ(CALLOUT_LIBRARY_2, libraries[1].first);

    // ... and check that the same two libraries are still loaded in the
    // HooksManager.
    hooks_libraries = HooksManager::getLibraryNames();
    ASSERT_EQ(2, hooks_libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, hooks_libraries[0]);
    EXPECT_EQ(CALLOUT_LIBRARY_2, hooks_libraries[1]);
}

// Configure the hooks with two libraries, then reconfigure with the same
// libraries, but in reverse order.
TEST_F(ParseConfigTest, reconfigureReverseHooksLibraries) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Configuration with hooks-libraries set to two libraries.
    std::string config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1,
                                                 CALLOUT_LIBRARY_2);

    // Verify that the configuration string parses. The twoHooksLibraries
    // test shows that the list will be as expected.
    int rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // A previous test shows that the parser correctly recorded the two
    // libraries and that they loaded correctly.

    // Parse the reversed set of libraries.
    config = setHooksLibrariesConfig(CALLOUT_LIBRARY_2, CALLOUT_LIBRARY_1);
    rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // The list has changed, and this is what we should see.
    isc::hooks::HookLibsCollection libraries = getLibraries();
    ASSERT_EQ(2, libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_2, libraries[0].first);
    EXPECT_EQ(CALLOUT_LIBRARY_1, libraries[1].first);

    // ... and check that this was propagated to the HooksManager.
    hooks_libraries = HooksManager::getLibraryNames();
    ASSERT_EQ(2, hooks_libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_2, hooks_libraries[0]);
    EXPECT_EQ(CALLOUT_LIBRARY_1, hooks_libraries[1]);
}

// Configure the hooks with two libraries, then reconfigure with
// no libraries.
TEST_F(ParseConfigTest, reconfigureZeroHooksLibraries) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Configuration with hooks-libraries set to two libraries.
    std::string config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1,
                                                 CALLOUT_LIBRARY_2);

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // A previous test shows that the parser correctly recorded the two
    // libraries and that they loaded correctly.

    // Parse the string again, this time without any libraries.
    config = setHooksLibrariesConfig();
    rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that the configuration object unparses.
    ConstElementPtr expected;
    ASSERT_NO_THROW(expected =
                    Element::fromJSON(config)->get("hooks-libraries"));
    ASSERT_TRUE(expected);
    const HooksConfig& cfg =
        CfgMgr::instance().getStagingCfg()->getHooksConfig();
    runToElementTest<HooksConfig>(expected, cfg);

    // The list has changed, and this is what we should see.
    isc::hooks::HookLibsCollection libraries = getLibraries();
    EXPECT_TRUE(libraries.empty());

    // Check that no libraries are currently loaded
    hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());
}

// Check with a set of libraries, some of which are invalid.
TEST_F(ParseConfigTest, invalidHooksLibraries) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Configuration string.  This contains an invalid library which should
    // trigger an error in the "build" stage.
    const std::string config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1,
                                                       NOT_PRESENT_LIBRARY,
                                                       CALLOUT_LIBRARY_2);

    // Verify that the configuration fails to parse. (Syntactically it's OK,
    // but the library is invalid).
    const int rcode = parseConfiguration(config);
    ASSERT_FALSE(rcode == 0) << error_text_;

    // Check that the message contains the library in error.
    EXPECT_FALSE(error_text_.find(NOT_PRESENT_LIBRARY) == string::npos) <<
        "Error text returned from parse failure is " << error_text_;

    // Check that the parser recorded the names but, as they were in error,
    // does not flag them as changed.
    isc::hooks::HookLibsCollection libraries = getLibraries();
    ASSERT_EQ(3, libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, libraries[0].first);
    EXPECT_EQ(NOT_PRESENT_LIBRARY, libraries[1].first);
    EXPECT_EQ(CALLOUT_LIBRARY_2, libraries[2].first);

    // ...and check it did not alter the libraries in the hooks manager.
    hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());
}

// Check that trying to reconfigure with an invalid set of libraries fails.
TEST_F(ParseConfigTest, reconfigureInvalidHooksLibraries) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Configure with a single library.
    std::string config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1);
    int rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // A previous test shows that the parser correctly recorded the two
    // libraries and that they loaded correctly.

    // Configuration string.  This contains an invalid library which should
    // trigger an error in the "build" stage.
    config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1, NOT_PRESENT_LIBRARY,
                                     CALLOUT_LIBRARY_2);

    // Verify that the configuration fails to parse. (Syntactically it's OK,
    // but the library is invalid).
    rcode = parseConfiguration(config);
    EXPECT_FALSE(rcode == 0) << error_text_;

    // Check that the message contains the library in error.
    EXPECT_FALSE(error_text_.find(NOT_PRESENT_LIBRARY) == string::npos) <<
        "Error text returned from parse failure is " << error_text_;

    // Check that the parser recorded the names but, as the library set was
    // incorrect, did not mark the configuration as changed.
    isc::hooks::HookLibsCollection libraries = getLibraries();
    ASSERT_EQ(3, libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, libraries[0].first);
    EXPECT_EQ(NOT_PRESENT_LIBRARY, libraries[1].first);
    EXPECT_EQ(CALLOUT_LIBRARY_2, libraries[2].first);

    // ... but check that the hooks manager was not updated with the incorrect
    // names.
    hooks_libraries.clear();
    hooks_libraries = HooksManager::getLibraryNames();
    ASSERT_EQ(1, hooks_libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, hooks_libraries[0]);
}

// Check that if hooks-libraries contains invalid syntax, it is detected.
TEST_F(ParseConfigTest, invalidSyntaxHooksLibraries) {

    // Element holds a mixture of (valid) maps and non-maps.
    string config1 = "{ \"hooks-libraries\": [ "
        "{ \"library\": \"/opt/lib/lib1\" }, "
        "\"/opt/lib/lib2\" "
        "] }";
    string error1 = "one or more entries in the hooks-libraries list is not"
                    " a map";

    int rcode = parseConfiguration(config1);
    ASSERT_NE(0, rcode);
    EXPECT_TRUE(error_text_.find(error1) != string::npos) <<
        "Error text returned from parse failure is " << error_text_;

    // Element holds valid maps, except one where the library element is not
    // a string.
    string config2 = "{ \"hooks-libraries\": [ "
        "{ \"library\": \"/opt/lib/lib1\" }, "
        "{ \"library\": 123 } "
        "] }";
    string error2 = "value of 'library' element is not a string giving"
                    " the path to a hooks library";

    rcode = parseConfiguration(config2);
    ASSERT_NE(0, rcode);
    EXPECT_TRUE(error_text_.find(error2) != string::npos) <<
        "Error text returned from parse failure is " << error_text_;

    // Element holds valid maps, except one where the library element is the
    // empty string.
    string config3 = "{ \"hooks-libraries\": [ "
        "{ \"library\": \"/opt/lib/lib1\" }, "
        "{ \"library\": \"\" } "
        "] }";
    string error3 = "value of 'library' element must not be blank";

    rcode = parseConfiguration(config3);
    ASSERT_NE(0, rcode);
    EXPECT_TRUE(error_text_.find(error3) != string::npos) <<
        "Error text returned from parse failure is " << error_text_;

    // Element holds valid maps, except one where the library element is all
    // spaces.
    string config4 = "{ \"hooks-libraries\": [ "
        "{ \"library\": \"/opt/lib/lib1\" }, "
        "{ \"library\": \"      \" } "
        "] }";
    string error4 = "value of 'library' element must not be blank";

    rcode = parseConfiguration(config4);
    ASSERT_NE(0, rcode);
    EXPECT_TRUE(error_text_.find(error3) != string::npos) <<
        "Error text returned from parse failure is " << error_text_;

    // Element holds valid maps, except one that does not contain a
    // 'library' element.
    string config5 = "{ \"hooks-libraries\": [ "
        "{ \"library\": \"/opt/lib/lib1\" }, "
        "{ \"parameters\": { \"alpha\": 123 } }, "
        "{ \"library\": \"/opt/lib/lib2\" } "
        "] }";
    string error5 = "one or more hooks-libraries elements are missing the"
                    " name of the library";

    rcode = parseConfiguration(config5);
    ASSERT_NE(0, rcode);
    EXPECT_TRUE(error_text_.find(error5) != string::npos) <<
        "Error text returned from parse failure is " << error_text_;
}

// Check that some parameters may have configuration parameters configured.
TEST_F(ParseConfigTest, HooksLibrariesParameters) {
    // Check that no libraries are currently loaded
    vector<string> hooks_libraries = HooksManager::getLibraryNames();
    EXPECT_TRUE(hooks_libraries.empty());

    // Configuration string.  This contains an invalid library which should
    // trigger an error in the "build" stage.
    const std::string config = setHooksLibrariesConfig(CALLOUT_LIBRARY_1,
                                                       CALLOUT_LIBRARY_2,
                                                       CALLOUT_PARAMS_LIBRARY);

    // Verify that the configuration fails to parse. (Syntactically it's OK,
    // but the library is invalid).
    const int rcode = parseConfiguration(config);
    ASSERT_EQ(0, rcode);

    // Verify that the configuration object unparses.
    ConstElementPtr expected;
    ASSERT_NO_THROW(expected =
                    Element::fromJSON(config)->get("hooks-libraries"));
    ASSERT_TRUE(expected);
    const HooksConfig& cfg =
        CfgMgr::instance().getStagingCfg()->getHooksConfig();
    runToElementTest<HooksConfig>(expected, cfg);

    // Check that the parser recorded the names.
    isc::hooks::HookLibsCollection libraries = getLibraries();
    ASSERT_EQ(3, libraries.size());
    EXPECT_EQ(CALLOUT_LIBRARY_1, libraries[0].first);
    EXPECT_EQ(CALLOUT_LIBRARY_2, libraries[1].first);
    EXPECT_EQ(CALLOUT_PARAMS_LIBRARY, libraries[2].first);

    // Also, check that the third library has its parameters specified.
    // They were set by setHooksLibrariesConfig. The first has no
    // parameters, the second one has an empty map and the third
    // one has actual parameters.
    EXPECT_FALSE(libraries[0].second);
    EXPECT_TRUE(libraries[1].second);
    ASSERT_TRUE(libraries[2].second);

    // Ok, get the parameter for the third library.
    ConstElementPtr params = libraries[2].second;

    // It must be a map.
    ASSERT_EQ(Element::map, params->getType());

    // This map should have 3 parameters:
    // - svalue (and will expect its value to be "string value")
    // - ivalue (and will expect its value to be 42)
    // - bvalue (and will expect its value to be true)
    ConstElementPtr svalue = params->get("svalue");
    ConstElementPtr ivalue = params->get("ivalue");
    ConstElementPtr bvalue = params->get("bvalue");

    // There should be no extra parameters.
    EXPECT_FALSE(params->get("nonexistent"));

    ASSERT_TRUE(svalue);
    ASSERT_TRUE(ivalue);
    ASSERT_TRUE(bvalue);

    ASSERT_EQ(Element::string, svalue->getType());
    ASSERT_EQ(Element::integer, ivalue->getType());
    ASSERT_EQ(Element::boolean, bvalue->getType());

    EXPECT_EQ("string value", svalue->stringValue());
    EXPECT_EQ(42, ivalue->intValue());
    EXPECT_EQ(true, bvalue->boolValue());
}

/// @brief Checks that a valid, enabled D2 client configuration works correctly.
TEST_F(ParseConfigTest, validD2Config) {

    // Configuration string containing valid values.
    std::string config_str =
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
        "     \"server-ip\" : \"192.0.2.0\", "
        "     \"server-port\" : 3432, "
        "     \"sender-ip\" : \"192.0.2.1\", "
        "     \"sender-port\" : 3433, "
        "     \"max-queue-size\" : 2048, "
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\", "
        "     \"user-context\": { \"foo\": \"bar\" } "
        "    }"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config_str);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that DHCP-DDNS is enabled and we can fetch the configuration.
    EXPECT_TRUE(CfgMgr::instance().ddnsEnabled());
    D2ClientConfigPtr d2_client_config;
    ASSERT_NO_THROW(d2_client_config = CfgMgr::instance().getD2ClientConfig());
    ASSERT_TRUE(d2_client_config);

    // Verify that the configuration values are as expected.
    EXPECT_TRUE(d2_client_config->getEnableUpdates());
    EXPECT_EQ("192.0.2.0", d2_client_config->getServerIp().toText());
    EXPECT_EQ(3432, d2_client_config->getServerPort());
    EXPECT_EQ(dhcp_ddns::NCR_UDP, d2_client_config->getNcrProtocol());
    EXPECT_EQ(dhcp_ddns::FMT_JSON, d2_client_config->getNcrFormat());
    ASSERT_TRUE(d2_client_config->getContext());
    EXPECT_EQ("{ \"foo\": \"bar\" }", d2_client_config->getContext()->str());

    // Verify that the configuration object unparses.
    ConstElementPtr expected;
    ASSERT_NO_THROW(expected = Element::fromJSON(config_str)->get("dhcp-ddns"));
    ASSERT_TRUE(expected);
    runToElementTest<D2ClientConfig>(expected, *d2_client_config);

    // Another valid Configuration string.
    // This one is disabled, has IPV6 server ip, control flags false,
    // empty prefix/suffix
    std::string config_str2 =
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : false, "
        "     \"server-ip\" : \"2001:db8::\", "
        "     \"server-port\" : 43567, "
        "     \"sender-ip\" : \"2001:db8::1\", "
        "     \"sender-port\" : 3433, "
        "     \"max-queue-size\" : 2048, "
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\", "
        "     \"user-context\": { \"foo\": \"bar\" } "
        "    }"
        "}";

    // Verify that the configuration string parses.
    rcode = parseConfiguration(config_str2);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that DHCP-DDNS is disabled and we can fetch the configuration.
    EXPECT_FALSE(CfgMgr::instance().ddnsEnabled());
    ASSERT_NO_THROW(d2_client_config = CfgMgr::instance().getD2ClientConfig());
    ASSERT_TRUE(d2_client_config);

    // Verify that the configuration values are as expected.
    EXPECT_FALSE(d2_client_config->getEnableUpdates());
    EXPECT_EQ("2001:db8::", d2_client_config->getServerIp().toText());
    EXPECT_EQ(43567, d2_client_config->getServerPort());
    EXPECT_EQ(dhcp_ddns::NCR_UDP, d2_client_config->getNcrProtocol());
    EXPECT_EQ(dhcp_ddns::FMT_JSON, d2_client_config->getNcrFormat());
    ASSERT_TRUE(d2_client_config->getContext());
    EXPECT_EQ("{ \"foo\": \"bar\" }", d2_client_config->getContext()->str());

    ASSERT_NO_THROW(expected = Element::fromJSON(config_str2)->get("dhcp-ddns"));
    ASSERT_TRUE(expected);
    runToElementTest<D2ClientConfig>(expected, *d2_client_config);
}

/// @brief Checks that D2 client can be configured with enable flag of
/// false only.
TEST_F(ParseConfigTest, validDisabledD2Config) {

    // Configuration string.  This defines a disabled D2 client config.
    std::string config_str =
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : false"
        "    }"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config_str);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that DHCP-DDNS is disabled.
    EXPECT_FALSE(CfgMgr::instance().ddnsEnabled());

    // Make sure fetched config agrees.
    D2ClientConfigPtr d2_client_config;
    ASSERT_NO_THROW(d2_client_config = CfgMgr::instance().getD2ClientConfig());
    EXPECT_TRUE(d2_client_config);
    EXPECT_FALSE(d2_client_config->getEnableUpdates());
}

/// @brief Checks that given a partial configuration, parser supplies
/// default values
TEST_F(ParseConfigTest, parserDefaultsD2Config) {

    // Configuration string.  This defines an enabled D2 client config
    // with the mandatory parameter in such a case, all other parameters
    // are optional and their default values will be used.
    std::string config_str =
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true "
        "    }"
        "}";

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config_str);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Verify that DHCP-DDNS is enabled.
    EXPECT_TRUE(CfgMgr::instance().ddnsEnabled());

    // Make sure fetched config is correct.
    D2ClientConfigPtr d2_client_config;
    ASSERT_NO_THROW(d2_client_config = CfgMgr::instance().getD2ClientConfig());
    EXPECT_TRUE(d2_client_config);
    EXPECT_TRUE(d2_client_config->getEnableUpdates());
    EXPECT_EQ(D2ClientConfig::DFT_SERVER_IP,
              d2_client_config->getServerIp().toText());
    EXPECT_EQ(D2ClientConfig::DFT_SERVER_PORT,
              d2_client_config->getServerPort());
    EXPECT_EQ(dhcp_ddns::stringToNcrProtocol(D2ClientConfig::DFT_NCR_PROTOCOL),
              d2_client_config->getNcrProtocol());
    EXPECT_EQ(dhcp_ddns::stringToNcrFormat(D2ClientConfig::DFT_NCR_FORMAT),
              d2_client_config->getNcrFormat());
}


/// @brief Check various invalid D2 client configurations.
TEST_F(ParseConfigTest, invalidD2Config) {
    std::string invalid_configs[] = {
        // Invalid server ip value
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
        "     \"server-ip\" : \"x192.0.2.0\", "
        "     \"server-port\" : 53001, "
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\" "
        "    }"
        "}",
        // Unknown protocol
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
        "     \"server-ip\" : \"192.0.2.0\", "
        "     \"server-port\" : 53001, "
        "     \"ncr-protocol\" : \"Bogus\", "
        "     \"ncr-format\" : \"JSON\" "
        "    }"
        "}",
        // Unsupported protocol
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
        "     \"server-ip\" : \"192.0.2.0\", "
        "     \"server-port\" : 53001, "
        "     \"ncr-protocol\" : \"TCP\", "
        "     \"ncr-format\" : \"JSON\" "
        "    }"
        "}",
        // Unknown format
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
        "     \"server-ip\" : \"192.0.2.0\", "
        "     \"server-port\" : 53001, "
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"Bogus\" "
        "    }"
        "}",
        // Invalid Port
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
        "     \"server-ip\" : \"192.0.2.0\", "
        "     \"server-port\" : \"bogus\", "
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\" "
        "    }"
        "}",
        // Mismatched server and sender IPs
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
        "     \"server-ip\" : \"192.0.2.0\", "
        "     \"server-port\" : 3432, "
        "     \"sender-ip\" : \"3001::5\", "
        "     \"sender-port\" : 3433, "
        "     \"max-queue-size\" : 2048, "
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\" "
        "    }"
        "}",
        // Identical server and sender IP/port
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
        "     \"server-ip\" : \"3001::5\", "
        "     \"server-port\" : 3433, "
        "     \"sender-ip\" : \"3001::5\", "
        "     \"sender-port\" : 3433, "
        "     \"max-queue-size\" : 2048, "
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\" "
        "    }"
        "}",
        // stop
        ""
    };

    // Fetch the original config.
    D2ClientConfigPtr original_config;
    ASSERT_NO_THROW(original_config = CfgMgr::instance().getD2ClientConfig());

    // Iterate through the invalid configuration strings, attempting to
    // parse each one.  They should fail to parse, but fail gracefully.
    D2ClientConfigPtr current_config;
    int i = 0;
    while (!invalid_configs[i].empty()) {
        // Verify that the configuration string parses without throwing.
        int rcode = parseConfiguration(invalid_configs[i]);

        // Verify that parse result indicates a parsing error.
        ASSERT_TRUE(rcode != 0) << "Invalid config #: " << i
                                << " should not have passed!";

        // Verify that the "official" config still matches the original config.
        ASSERT_NO_THROW(current_config =
                        CfgMgr::instance().getD2ClientConfig());
        EXPECT_EQ(*original_config, *current_config);
        ++i;
    }
}

/// @brief Checks that a valid relay info structure for IPv4 can be handled
TEST_F(ParseConfigTest, validRelayInfo4) {

    // Relay information structure. Very simple for now.
    std::string config_str =
        "    {"
        "     \"ip-addresses\" : [ \"192.0.2.1\" ]"
        "    }";
    ElementPtr json = Element::fromJSON(config_str);

    // Create an "empty" RelayInfo to hold the parsed result.
    Network::RelayInfoPtr result(new Network::RelayInfo());

    RelayInfoParser parser(Option::V4);

    EXPECT_NO_THROW(parser.parse(result, json));
    EXPECT_TRUE(result->containsAddress(IOAddress("192.0.2.1")));
}

/// @brief Checks that a bogus relay info structure for IPv4 is rejected.
TEST_F(ParseConfigTest, bogusRelayInfo4) {

    // Invalid config (wrong family type of the ip-address field)
    std::string config_str_bogus1 =
        "    {"
        "     \"ip-addresses\" : [ \"2001:db8::1\" ]"
        "    }";
    ElementPtr json_bogus1 = Element::fromJSON(config_str_bogus1);

    // Invalid config (that thing is not an IPv4 address)
    std::string config_str_bogus2 =
        "    {"
        "     \"ip-addresses\" : [ \"256.345.123.456\" ]"
        "    }";
    ElementPtr json_bogus2 = Element::fromJSON(config_str_bogus2);

    // Invalid config (ip-address is mandatory)
    std::string config_str_bogus3 =
        "    {"
        "    }";
    ElementPtr json_bogus3 = Element::fromJSON(config_str_bogus3);

    // Create an "empty" RelayInfo to hold the parsed result.
    Network::RelayInfoPtr result(new Network::RelayInfo());

    RelayInfoParser parser(Option::V4);

    // wrong family type
    EXPECT_THROW(parser.parse(result, json_bogus1), DhcpConfigError);

    // Too large byte values in pseudo-IPv4 addr
    EXPECT_THROW(parser.parse(result, json_bogus2), DhcpConfigError);

    // Mandatory ip-address is missing. What a pity.
    EXPECT_THROW(parser.parse(result, json_bogus2), DhcpConfigError);
}

/// @brief Checks that a valid relay info structure for IPv6 can be handled
TEST_F(ParseConfigTest, validRelayInfo6) {

    // Relay information structure. Very simple for now.
    std::string config_str =
        "    {"
        "     \"ip-addresses\" : [ \"2001:db8::1\" ]"
        "    }";
    ElementPtr json = Element::fromJSON(config_str);

    // Create an "empty" RelayInfo to hold the parsed result.
    Network::RelayInfoPtr result(new Network::RelayInfo());

    RelayInfoParser parser(Option::V6);

    EXPECT_NO_THROW(parser.parse(result, json));
    EXPECT_TRUE(result->containsAddress(IOAddress("2001:db8::1")));
}

/// @brief Checks that a valid relay info structure for IPv6 can be handled
TEST_F(ParseConfigTest, bogusRelayInfo6) {

    // Invalid config (wrong family type of the ip-address field
    std::string config_str_bogus1 =
        "    {"
        "     \"ip-addresses\" : [ \"192.0.2.1\" ]"
        "    }";
    ElementPtr json_bogus1 = Element::fromJSON(config_str_bogus1);

    // That IPv6 address doesn't look right
    std::string config_str_bogus2 =
        "    {"
        "     \"ip-addresses\" : [ \"2001:db8:::4\" ]"
        "    }";
    ElementPtr json_bogus2 = Element::fromJSON(config_str_bogus2);

    // Missing mandatory ip-address field.
    std::string config_str_bogus3 =
        "    {"
        "    }";
    ElementPtr json_bogus3 = Element::fromJSON(config_str_bogus3);

    // Create an "empty" RelayInfo to hold the parsed result.
    Network::RelayInfoPtr result(new Network::RelayInfo());

    RelayInfoParser parser(Option::V6);

    // Negative scenario (wrong family type)
    EXPECT_THROW(parser.parse(result, json_bogus1), DhcpConfigError);

    // Looks like IPv6 address, but has too many colons
    EXPECT_THROW(parser.parse(result, json_bogus2), DhcpConfigError);

    // Mandatory ip-address is missing. What a pity.
    EXPECT_THROW(parser.parse(result, json_bogus3), DhcpConfigError);
}

// This test verifies that it is possible to parse an IPv4 subnet for which
// only mandatory parameters are specified without setting the defaults.
TEST_F(ParseConfigTest, defaultSubnet4) {
    std::string config =
        "{"
        "    \"subnet4\": [ {"
        "        \"subnet\": \"192.0.2.0/24\","
        "        \"id\": 123"
        "    } ]"
        "}";

    int rcode = parseConfiguration(config, false, false);
    ASSERT_EQ(0, rcode);

    auto subnet = CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->getBySubnetId(123);
    ASSERT_TRUE(subnet);

    EXPECT_TRUE(subnet->hasFetchGlobalsFn());

    EXPECT_TRUE(subnet->getIface().unspecified());
    EXPECT_TRUE(subnet->getIface().empty());

    EXPECT_TRUE(subnet->getClientClasses().empty());

    EXPECT_TRUE(subnet->getValid().unspecified());
    EXPECT_EQ(0, subnet->getValid().get());

    EXPECT_TRUE(subnet->getT1().unspecified());
    EXPECT_EQ(0, subnet->getT1().get());

    EXPECT_TRUE(subnet->getT2().unspecified());
    EXPECT_EQ(0, subnet->getT2().get());

    EXPECT_TRUE(subnet->getReservationsGlobal().unspecified());
    EXPECT_FALSE(subnet->getReservationsGlobal().get());

    EXPECT_TRUE(subnet->getReservationsInSubnet().unspecified());
    EXPECT_TRUE(subnet->getReservationsInSubnet().get());

    EXPECT_TRUE(subnet->getReservationsOutOfPool().unspecified());
    EXPECT_FALSE(subnet->getReservationsOutOfPool().get());

    EXPECT_TRUE(subnet->getCalculateTeeTimes().unspecified());
    EXPECT_FALSE(subnet->getCalculateTeeTimes().get());

    EXPECT_TRUE(subnet->getT1Percent().unspecified());
    EXPECT_EQ(0.0, subnet->getT1Percent().get());

    EXPECT_TRUE(subnet->getT2Percent().unspecified());
    EXPECT_EQ(0.0, subnet->getT2Percent().get());

    EXPECT_TRUE(subnet->getMatchClientId().unspecified());
    EXPECT_TRUE(subnet->getMatchClientId().get());

    EXPECT_TRUE(subnet->getAuthoritative().unspecified());
    EXPECT_FALSE(subnet->getAuthoritative().get());

    EXPECT_TRUE(subnet->getSiaddr().unspecified());
    EXPECT_TRUE(subnet->getSiaddr().get().isV4Zero());

    EXPECT_TRUE(subnet->getSname().unspecified());
    EXPECT_TRUE(subnet->getSname().empty());

    EXPECT_TRUE(subnet->getFilename().unspecified());
    EXPECT_TRUE(subnet->getFilename().empty());

    EXPECT_FALSE(subnet->get4o6().enabled());

    EXPECT_TRUE(subnet->get4o6().getIface4o6().unspecified());
    EXPECT_TRUE(subnet->get4o6().getIface4o6().empty());

    EXPECT_TRUE(subnet->get4o6().getSubnet4o6().unspecified());
    EXPECT_TRUE(subnet->get4o6().getSubnet4o6().get().first.isV6Zero());
    EXPECT_EQ(128, subnet->get4o6().getSubnet4o6().get().second);

    EXPECT_TRUE(subnet->getDdnsSendUpdates().unspecified());
    EXPECT_FALSE(subnet->getDdnsSendUpdates().get());

    EXPECT_TRUE(subnet->getDdnsOverrideNoUpdate().unspecified());
    EXPECT_FALSE(subnet->getDdnsOverrideNoUpdate().get());

    EXPECT_TRUE(subnet->getDdnsOverrideClientUpdate().unspecified());
    EXPECT_FALSE(subnet->getDdnsOverrideClientUpdate().get());

    EXPECT_TRUE(subnet->getDdnsReplaceClientNameMode().unspecified());
    EXPECT_EQ(D2ClientConfig::RCM_NEVER, subnet->getDdnsReplaceClientNameMode().get());

    EXPECT_TRUE(subnet->getDdnsGeneratedPrefix().unspecified());
    EXPECT_TRUE(subnet->getDdnsGeneratedPrefix().empty());

    EXPECT_TRUE(subnet->getDdnsQualifyingSuffix().unspecified());
    EXPECT_TRUE(subnet->getDdnsQualifyingSuffix().empty());

    EXPECT_TRUE(subnet->getHostnameCharSet().unspecified());
    EXPECT_TRUE(subnet->getHostnameCharSet().empty());

    EXPECT_TRUE(subnet->getHostnameCharReplacement().unspecified());
    EXPECT_TRUE(subnet->getHostnameCharReplacement().empty());

    EXPECT_TRUE(subnet->getStoreExtendedInfo().unspecified());
    EXPECT_FALSE(subnet->getStoreExtendedInfo().get());

    EXPECT_TRUE(subnet->getDdnsUpdateOnRenew().unspecified());
    EXPECT_FALSE(subnet->getDdnsUpdateOnRenew().get());

    EXPECT_TRUE(subnet->getDdnsConflictResolutionMode().unspecified());
    EXPECT_EQ("", subnet->getDdnsConflictResolutionMode().get());

    EXPECT_TRUE(subnet->getAllocationState(Lease::TYPE_V4));
    EXPECT_TRUE(subnet->getAllocator(Lease::TYPE_V4));

    auto allocator = subnet->getAllocator(Lease::TYPE_V4);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));

    EXPECT_TRUE(subnet->getOfferLft().unspecified());
    EXPECT_EQ(0, subnet->getOfferLft().get());
}

// This test verifies that it is possible to parse an IPv6 subnet for which
// only mandatory parameters are specified without setting the defaults.
TEST_F(ParseConfigTest, defaultSubnet6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": 123"
        "    } ]"
        "}";

    int rcode = parseConfiguration(config, true, false);
    ASSERT_EQ(0, rcode);

    auto subnet = CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getBySubnetId(123);
    ASSERT_TRUE(subnet);

    EXPECT_TRUE(subnet->hasFetchGlobalsFn());

    EXPECT_TRUE(subnet->getIface().unspecified());
    EXPECT_TRUE(subnet->getIface().empty());

    EXPECT_TRUE(subnet->getClientClasses().empty());

    EXPECT_TRUE(subnet->getValid().unspecified());
    EXPECT_EQ(0, subnet->getValid().get());

    EXPECT_TRUE(subnet->getT1().unspecified());
    EXPECT_EQ(0, subnet->getT1().get());

    EXPECT_TRUE(subnet->getT2().unspecified());
    EXPECT_EQ(0, subnet->getT2().get());

    EXPECT_TRUE(subnet->getReservationsGlobal().unspecified());
    EXPECT_FALSE(subnet->getReservationsGlobal().get());

    EXPECT_TRUE(subnet->getReservationsInSubnet().unspecified());
    EXPECT_TRUE(subnet->getReservationsInSubnet().get());

    EXPECT_TRUE(subnet->getReservationsOutOfPool().unspecified());
    EXPECT_FALSE(subnet->getReservationsOutOfPool().get());

    EXPECT_TRUE(subnet->getCalculateTeeTimes().unspecified());
    EXPECT_FALSE(subnet->getCalculateTeeTimes().get());

    EXPECT_TRUE(subnet->getT1Percent().unspecified());
    EXPECT_EQ(0.0, subnet->getT1Percent().get());

    EXPECT_TRUE(subnet->getT2Percent().unspecified());
    EXPECT_EQ(0.0, subnet->getT2Percent().get());

    EXPECT_TRUE(subnet->getPreferred().unspecified());
    EXPECT_EQ(0, subnet->getPreferred().get());

    EXPECT_TRUE(subnet->getRapidCommit().unspecified());
    EXPECT_FALSE(subnet->getRapidCommit().get());

    EXPECT_TRUE(subnet->getDdnsSendUpdates().unspecified());
    EXPECT_FALSE(subnet->getDdnsSendUpdates().get());

    EXPECT_TRUE(subnet->getDdnsOverrideNoUpdate().unspecified());
    EXPECT_FALSE(subnet->getDdnsOverrideNoUpdate().get());

    EXPECT_TRUE(subnet->getDdnsOverrideClientUpdate().unspecified());
    EXPECT_FALSE(subnet->getDdnsOverrideClientUpdate().get());

    EXPECT_TRUE(subnet->getDdnsReplaceClientNameMode().unspecified());
    EXPECT_EQ(D2ClientConfig::RCM_NEVER, subnet->getDdnsReplaceClientNameMode().get());

    EXPECT_TRUE(subnet->getDdnsGeneratedPrefix().unspecified());
    EXPECT_TRUE(subnet->getDdnsGeneratedPrefix().empty());

    EXPECT_TRUE(subnet->getDdnsQualifyingSuffix().unspecified());
    EXPECT_TRUE(subnet->getDdnsQualifyingSuffix().empty());

    EXPECT_TRUE(subnet->getHostnameCharSet().unspecified());
    EXPECT_TRUE(subnet->getHostnameCharSet().empty());

    EXPECT_TRUE(subnet->getHostnameCharReplacement().unspecified());
    EXPECT_TRUE(subnet->getHostnameCharReplacement().empty());

    EXPECT_TRUE(subnet->getStoreExtendedInfo().unspecified());
    EXPECT_FALSE(subnet->getStoreExtendedInfo().get());

    EXPECT_TRUE(subnet->getDdnsUpdateOnRenew().unspecified());
    EXPECT_FALSE(subnet->getDdnsUpdateOnRenew().get());

    EXPECT_TRUE(subnet->getDdnsConflictResolutionMode().unspecified());
    EXPECT_EQ("", subnet->getDdnsConflictResolutionMode().get());

    EXPECT_TRUE(subnet->getAllocationState(Lease::TYPE_NA));
    EXPECT_TRUE(subnet->getAllocationState(Lease::TYPE_TA));
    EXPECT_TRUE(subnet->getAllocationState(Lease::TYPE_PD));

    auto allocator = subnet->getAllocator(Lease::TYPE_NA);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));

    allocator = subnet->getAllocator(Lease::TYPE_TA);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));

    allocator = subnet->getAllocator(Lease::TYPE_PD);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));
}

// This test verifies that it is possible to parse an IPv4 shared network
// for which only mandatory parameter is specified without setting the
// defaults.
TEST_F(ParseConfigTest, defaultSharedNetwork4) {
    std::string config =
        "{"
        "    \"shared-networks\": [ {"
        "        \"name\": \"frog\""
        "    } ]"
        "}";

    int rcode = parseConfiguration(config, false, false);
    ASSERT_EQ(0, rcode);

    auto network =
        CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks4()->getByName("frog");
    ASSERT_TRUE(network);

    EXPECT_TRUE(network->hasFetchGlobalsFn());
    EXPECT_TRUE(network->getIface().unspecified());
    EXPECT_TRUE(network->getIface().empty());

    EXPECT_TRUE(network->getClientClasses().empty());

    EXPECT_TRUE(network->getValid().unspecified());
    EXPECT_EQ(0, network->getValid().get());

    EXPECT_TRUE(network->getT1().unspecified());
    EXPECT_EQ(0, network->getT1().get());

    EXPECT_TRUE(network->getT2().unspecified());
    EXPECT_EQ(0, network->getT2().get());

    EXPECT_TRUE(network->getReservationsGlobal().unspecified());
    EXPECT_FALSE(network->getReservationsGlobal().get());

    EXPECT_TRUE(network->getReservationsInSubnet().unspecified());
    EXPECT_TRUE(network->getReservationsInSubnet().get());

    EXPECT_TRUE(network->getReservationsOutOfPool().unspecified());
    EXPECT_FALSE(network->getReservationsOutOfPool().get());

    EXPECT_TRUE(network->getCalculateTeeTimes().unspecified());
    EXPECT_FALSE(network->getCalculateTeeTimes().get());

    EXPECT_TRUE(network->getT1Percent().unspecified());
    EXPECT_EQ(0.0, network->getT1Percent().get());

    EXPECT_TRUE(network->getT2Percent().unspecified());
    EXPECT_EQ(0.0, network->getT2Percent().get());

    EXPECT_TRUE(network->getMatchClientId().unspecified());
    EXPECT_TRUE(network->getMatchClientId().get());

    EXPECT_TRUE(network->getAuthoritative().unspecified());
    EXPECT_FALSE(network->getAuthoritative().get());

    EXPECT_TRUE(network->getDdnsSendUpdates().unspecified());
    EXPECT_FALSE(network->getDdnsSendUpdates().get());

    EXPECT_TRUE(network->getDdnsOverrideNoUpdate().unspecified());
    EXPECT_FALSE(network->getDdnsOverrideNoUpdate().get());

    EXPECT_TRUE(network->getDdnsOverrideClientUpdate().unspecified());
    EXPECT_FALSE(network->getDdnsOverrideClientUpdate().get());

    EXPECT_TRUE(network->getDdnsReplaceClientNameMode().unspecified());
    EXPECT_EQ(D2ClientConfig::RCM_NEVER, network->getDdnsReplaceClientNameMode().get());

    EXPECT_TRUE(network->getDdnsGeneratedPrefix().unspecified());
    EXPECT_TRUE(network->getDdnsGeneratedPrefix().empty());

    EXPECT_TRUE(network->getDdnsQualifyingSuffix().unspecified());
    EXPECT_TRUE(network->getDdnsQualifyingSuffix().empty());

    EXPECT_TRUE(network->getStoreExtendedInfo().unspecified());
    EXPECT_FALSE(network->getStoreExtendedInfo().get());

    EXPECT_TRUE(network->getDdnsUpdateOnRenew().unspecified());
    EXPECT_FALSE(network->getDdnsUpdateOnRenew().get());

    EXPECT_TRUE(network->getDdnsConflictResolutionMode().unspecified());
    EXPECT_EQ("", network->getDdnsConflictResolutionMode().get());

    EXPECT_TRUE(network->getAllocatorType().unspecified());
    EXPECT_TRUE(network->getAllocatorType().get().empty());

    EXPECT_TRUE(network->getOfferLft().unspecified());
    EXPECT_EQ(0, network->getOfferLft().get());
}

// This test verifies that it is possible to parse an IPv6 shared network
// for which only mandatory parameter is specified without setting the
// defaults.
TEST_F(ParseConfigTest, defaultSharedNetwork6) {
    std::string config =
        "{"
        "    \"shared-networks\": [ {"
        "        \"name\": \"frog\""
        "    } ]"
        "}";

    int rcode = parseConfiguration(config, true, false);
    ASSERT_EQ(0, rcode);

    auto network =
        CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks6()->getByName("frog");
    ASSERT_TRUE(network);

    EXPECT_TRUE(network->hasFetchGlobalsFn());

    EXPECT_TRUE(network->getIface().unspecified());
    EXPECT_TRUE(network->getIface().empty());

    EXPECT_TRUE(network->getClientClasses().empty());

    EXPECT_TRUE(network->getValid().unspecified());
    EXPECT_EQ(0, network->getValid().get());

    EXPECT_TRUE(network->getT1().unspecified());
    EXPECT_EQ(0, network->getT1().get());

    EXPECT_TRUE(network->getT2().unspecified());
    EXPECT_EQ(0, network->getT2().get());

    EXPECT_TRUE(network->getReservationsGlobal().unspecified());
    EXPECT_FALSE(network->getReservationsGlobal().get());

    EXPECT_TRUE(network->getReservationsInSubnet().unspecified());
    EXPECT_TRUE(network->getReservationsInSubnet().get());

    EXPECT_TRUE(network->getReservationsOutOfPool().unspecified());
    EXPECT_FALSE(network->getReservationsOutOfPool().get());

    EXPECT_TRUE(network->getCalculateTeeTimes().unspecified());
    EXPECT_FALSE(network->getCalculateTeeTimes().get());

    EXPECT_TRUE(network->getT1Percent().unspecified());
    EXPECT_EQ(0.0, network->getT1Percent().get());

    EXPECT_TRUE(network->getT2Percent().unspecified());
    EXPECT_EQ(0.0, network->getT2Percent().get());

    EXPECT_TRUE(network->getPreferred().unspecified());
    EXPECT_EQ(0, network->getPreferred().get());

    EXPECT_TRUE(network->getRapidCommit().unspecified());
    EXPECT_FALSE(network->getRapidCommit().get());

    EXPECT_TRUE(network->getDdnsSendUpdates().unspecified());
    EXPECT_FALSE(network->getDdnsSendUpdates().get());

    EXPECT_TRUE(network->getDdnsOverrideNoUpdate().unspecified());
    EXPECT_FALSE(network->getDdnsOverrideNoUpdate().get());

    EXPECT_TRUE(network->getDdnsOverrideClientUpdate().unspecified());
    EXPECT_FALSE(network->getDdnsOverrideClientUpdate().get());

    EXPECT_TRUE(network->getDdnsReplaceClientNameMode().unspecified());
    EXPECT_EQ(D2ClientConfig::RCM_NEVER, network->getDdnsReplaceClientNameMode().get());

    EXPECT_TRUE(network->getDdnsGeneratedPrefix().unspecified());
    EXPECT_TRUE(network->getDdnsGeneratedPrefix().empty());

    EXPECT_TRUE(network->getDdnsQualifyingSuffix().unspecified());
    EXPECT_TRUE(network->getDdnsQualifyingSuffix().empty());

    EXPECT_TRUE(network->getStoreExtendedInfo().unspecified());
    EXPECT_FALSE(network->getStoreExtendedInfo().get());

    EXPECT_TRUE(network->getDdnsUpdateOnRenew().unspecified());
    EXPECT_FALSE(network->getDdnsUpdateOnRenew().get());

    EXPECT_TRUE(network->getDdnsConflictResolutionMode().unspecified());
    EXPECT_EQ("", network->getDdnsConflictResolutionMode().get());

    EXPECT_TRUE(network->getAllocatorType().unspecified());
    EXPECT_TRUE(network->getAllocatorType().get().empty());

    EXPECT_TRUE(network->getPdAllocatorType().unspecified());
    EXPECT_TRUE(network->getPdAllocatorType().get().empty());
}

// This test verifies a negative value for the subnet ID is rejected (v4).
TEST_F(ParseConfigTest, negativeSubnetId4) {
    std::string config =
        "{"
        "    \"subnet4\": [ {"
        "        \"subnet\": \"192.0.2.0/24\","
        "        \"id\": -1"
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_TRUE(comment);
    ASSERT_EQ(comment->getType(), Element::string);
    EXPECT_EQ(1, rcode);
    std::string expected = "Configuration parsing failed: ";
    expected += "subnet configuration failed: ";
    expected += "The 'id' value (-1) is not within expected range: ";
    expected += "(1 - 4294967294)";
    EXPECT_EQ(expected, comment->stringValue());
}

// This test verifies a negative value for the subnet ID is rejected (v6).
TEST_F(ParseConfigTest, negativeSubnetId6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": -1"
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, true);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_TRUE(comment);
    ASSERT_EQ(comment->getType(), Element::string);
    EXPECT_EQ(1, rcode);
    std::string expected = "Configuration parsing failed: ";
    expected += "subnet configuration failed: ";
    expected += "The 'id' value (-1) is not within expected range: ";
    expected += "(1 - 4294967294)";
    EXPECT_EQ(expected, comment->stringValue());
}

// This test verifies a too high value for the subnet ID is rejected (v4).
TEST_F(ParseConfigTest, reservedSubnetId4) {
    std::string config =
        "{"
        "    \"subnet4\": [ {"
        "        \"subnet\": \"192.0.2.0/24\","
        "        \"id\": 4294967295"
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_TRUE(comment);
    ASSERT_EQ(comment->getType(), Element::string);
    EXPECT_EQ(1, rcode);
    std::string expected = "Configuration parsing failed: ";
    expected += "subnet configuration failed: ";
    expected += "The 'id' value (4294967295) is not within expected range: ";
    expected += "(1 - 4294967294)";
    EXPECT_EQ(expected, comment->stringValue());
}

// This test verifies a too high value for the subnet ID is rejected (v6).
TEST_F(ParseConfigTest, reservedSubnetId6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": 4294967295"
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, true);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_TRUE(comment);
    ASSERT_EQ(comment->getType(), Element::string);
    EXPECT_EQ(1, rcode);
    std::string expected = "Configuration parsing failed: ";
    expected += "subnet configuration failed: ";
    expected += "The 'id' value (4294967295) is not within expected range: ";
    expected += "(1 - 4294967294)";
    EXPECT_EQ(expected, comment->stringValue());
}

// This test verifies that random allocator can be selected for
// a subnet.
TEST_F(ParseConfigTest, randomSubnetAllocator4) {
    std::string config =
        "{"
        "    \"subnet4\": [ {"
        "        \"subnet\": \"192.0.2.0/24\","
        "        \"id\": 1,"
        "        \"allocator\": \"random\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_EQ(0, rcode);

    auto subnet = CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->getBySubnetId(1);
    ASSERT_TRUE(subnet);

    EXPECT_EQ("random", subnet->getAllocatorType().get());
    auto allocator = subnet->getAllocator(Lease::TYPE_V4);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<RandomAllocator>(allocator));
}

// This test verifies that Free Lease Queue allocator can be selected for
// a subnet.
TEST_F(ParseConfigTest, flqSubnetAllocator4) {
    std::string config =
        "{"
        "    \"subnet4\": [ {"
        "        \"subnet\": \"192.0.2.0/24\","
        "        \"id\": 1,"
        "        \"allocator\": \"flq\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_EQ(0, rcode);

    auto subnet = CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->getBySubnetId(1);
    ASSERT_TRUE(subnet);

    EXPECT_EQ("flq", subnet->getAllocatorType().get());
    auto allocator = subnet->getAllocator(Lease::TYPE_V4);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<FreeLeaseQueueAllocator>(allocator));
}

// This test verifies that unknown allocator is rejected.
TEST_F(ParseConfigTest, invalidSubnetAllocator4) {
    std::string config =
        "{"
        "    \"subnet4\": [ {"
        "        \"subnet\": \"192.0.2.0/24\","
        "        \"id\": 1,"
        "        \"allocator\": \"unsupported\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_TRUE(comment);
    ASSERT_EQ(comment->getType(), Element::string);
    EXPECT_EQ(1, rcode);
    std::string expected = "Configuration parsing failed: ";
    expected += "supported allocators are: iterative, random and flq";
    EXPECT_EQ(expected, comment->stringValue());
}

// This test verifies that random allocator can be selected for
// a subnet.
TEST_F(ParseConfigTest, randomSubnetAllocator6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": 1,"
        "        \"allocator\": \"random\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_EQ(0, rcode);

    auto subnet = CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getBySubnetId(1);
    ASSERT_TRUE(subnet);

    EXPECT_EQ("random", subnet->getAllocatorType().get());
    auto allocator = subnet->getAllocator(Lease::TYPE_NA);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<RandomAllocator>(allocator));
    allocator = subnet->getAllocator(Lease::TYPE_TA);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<RandomAllocator>(allocator));
    // PD allocator should be iterative.
    allocator = subnet->getAllocator(Lease::TYPE_PD);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));
}

// This test verifies that FLQ allocator is not supported for
// IPv6 address pools.
TEST_F(ParseConfigTest, flqSubnetAllocator6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": 1,"
        "        \"allocator\": \"flq\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_TRUE(comment);
    ASSERT_EQ(comment->getType(), Element::string);
    EXPECT_EQ(1, rcode);
    std::string expected = "Configuration parsing failed: ";
    expected += "Free Lease Queue allocator is not supported for IPv6 address pools";
    EXPECT_EQ(expected, comment->stringValue());
}

// This test verifies that unknown allocator is rejected.
TEST_F(ParseConfigTest, invalidSubnetAllocator6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": 1,"
        "        \"allocator\": \"unsupported\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_TRUE(comment);
    ASSERT_EQ(comment->getType(), Element::string);
    EXPECT_EQ(1, rcode);
    std::string expected = "Configuration parsing failed: ";
    expected += "supported allocators are: iterative, random and flq";
    EXPECT_EQ(expected, comment->stringValue());
}

// This test verifies that random allocator can be selected for
// a subnet.
TEST_F(ParseConfigTest, randomSubnetPdAllocator6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": 1,"
        "        \"pd-allocator\": \"random\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_EQ(0, rcode);

    auto subnet = CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getBySubnetId(1);
    ASSERT_TRUE(subnet);

    EXPECT_EQ("random", subnet->getPdAllocatorType().get());

    // Address allocators should be iterative.
    auto allocator = subnet->getAllocator(Lease::TYPE_NA);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));
    allocator = subnet->getAllocator(Lease::TYPE_TA);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));
    // PD allocator should be random.
    allocator = subnet->getAllocator(Lease::TYPE_PD);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<RandomAllocator>(allocator));
}

// This test verifies that the FLQ allocator can be selected for
// a v6 subnet's pd-allocator.
TEST_F(ParseConfigTest, flqSubnetPdAllocator6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": 1,"
        "        \"pd-allocator\": \"flq\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_EQ(0, rcode);

    auto subnet = CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getBySubnetId(1);
    ASSERT_TRUE(subnet);

    EXPECT_EQ("flq", subnet->getPdAllocatorType().get());

    // Address allocators should be iterative.
    auto allocator = subnet->getAllocator(Lease::TYPE_NA);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));
    allocator = subnet->getAllocator(Lease::TYPE_TA);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<IterativeAllocator>(allocator));
    // PD allocator should use FLQ.
    allocator = subnet->getAllocator(Lease::TYPE_PD);
    ASSERT_TRUE(allocator);
    EXPECT_TRUE(boost::dynamic_pointer_cast<FreeLeaseQueueAllocator>(allocator));
}

// This test verifies that unknown prefix delegation allocator is rejected.
TEST_F(ParseConfigTest, invalidSubnetPdAllocator6) {
    std::string config =
        "{"
        "    \"subnet6\": [ {"
        "        \"subnet\": \"2001:db8:1::/64\","
        "        \"id\": 1,"
        "        \"pd-allocator\": \"unsupported\""
        "    } ]"
        "}";

    ElementPtr json = Element::fromJSON(config);
    EXPECT_TRUE(json);
    ConstElementPtr status = parseElementSet(json, false);
    int rcode = 0;
    ConstElementPtr comment = parseAnswer(rcode, status);
    ASSERT_TRUE(comment);
    ASSERT_EQ(comment->getType(), Element::string);
    EXPECT_EQ(1, rcode);
    std::string expected = "Configuration parsing failed: ";
    expected += "supported allocators are: iterative, random and flq";
    EXPECT_EQ(expected, comment->stringValue());
}

// There's no test for ControlSocketParser, as it is tested in the DHCPv4 code
// (see CtrlDhcpv4SrvTest.commandSocketBasic in
// src/bin/dhcp4/tests/ctrl_dhcp4_srv_unittest.cc).


// Verifies that parsing an option which encapsulates its own option space
// is detected.
TEST_F(ParseConfigTest, selfEncapsulationTest) {
    // Configuration string.
    std::string config =
        "{"
        " \"option-data\": ["
        "{"
        "    \"name\": \"client-data\","
        "    \"code\": 45,"
        "    \"csv-format\": false,"
        "    \"space\": \"dhcp6\","
        "    \"data\": \"0001000B0102020202030303030303\""
        "}"
        "]}";

    // Verify that the configuration string parses.
    family_ = AF_INET6;

    int rcode = parseConfiguration(config, true, true);
    ASSERT_EQ(0, rcode);

    // Verify that the option can be retrieved.
    OptionCustomPtr opt = boost::dynamic_pointer_cast<OptionCustom>
                          (getOptionPtr(DHCP6_OPTION_SPACE, D6O_CLIENT_DATA));
    ASSERT_TRUE(opt);

    // Verify length is correct and doesn't infinitely recurse.
    EXPECT_EQ(19, opt->len());

    // Option D6O_CLIENT_DATA is defined as OPT_EMPTY_TYPE so it is not
    // serializing sub-options.
    config =
        "{"
        " \"option-data\": ["
        "{"
        "    \"name\": \"client-data\","
        "    \"code\": 45,"
        "    \"csv-format\": false,"
        "    \"space\": \"dhcp6\","
        "    \"data\": \"\""
        "}"
        "]}";

    // Check if it can be unparsed.
    CfgOptionsTest cfg(CfgMgr::instance().getStagingCfg());
    cfg.runCfgOptionsTest(family_, config);
}

// This test verifies parsing offer-lifetime for Subnet4.
TEST_F(ParseConfigTest, subnet4OfferLft) {
    std::string config =
        "{"
        "    \"subnet4\": [ {"
        "        \"subnet\": \"192.0.2.0/24\","
        "        \"id\": 123,"
        "        \"offer-lifetime\": 888"
        "    } ]"
        "}";

    int rcode = parseConfiguration(config, false, false);
    ASSERT_EQ(0, rcode);

    auto subnet = CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->getBySubnetId(123);
    ASSERT_TRUE(subnet);

    EXPECT_FALSE(subnet->getOfferLft().unspecified());
    EXPECT_EQ(888, subnet->getOfferLft().get());
}

// This test verifies parsing invalid offer-lifetime for Subnet4.
TEST_F(ParseConfigTest, subnet4InvalidOfferLft) {
    std::string config =
        "{"
        "    \"subnet4\": [ {"
        "        \"subnet\": \"192.0.2.0/24\","
        "        \"id\": 123,"
        "        \"offer-lifetime\": -77"
        "    } ]"
        "}";

    int rcode = parseConfiguration(config, false, false);
    ASSERT_NE(0, rcode);
}

// Verify that deprecated require-client-classes is handled properly
// by Subnet4 parser.
TEST_F(DhcpParserTest, deprecatedRequireClientClassesSubnet4) {
    // Valid entry.
    std::string config =
       R"^({
            "id": 1,
            "subnet": "192.0.2.0/24",
            "require-client-classes": [ "one", "two" ]
        })^";

    ElementPtr config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    Subnet4ConfigParser parser(AF_INET);
    Subnet4Ptr subnet;

    ASSERT_NO_THROW(subnet = parser.parse(config_element));
    ASSERT_TRUE(subnet);

    const auto cclasses = subnet->getAdditionalClasses();
    EXPECT_EQ(cclasses.size(), 2);
    auto cclass = cclasses.begin();
    EXPECT_EQ(*cclass, "one");
    ++cclass;
    EXPECT_EQ(*cclass, "two");

    // Invalid entry specifies both parameters.
    config =
       R"^({
            "id": 1,
            "subnet": "192.0.2.0/24",
            "require-client-classes": [ "one", "two" ],
            "evaluate-additional-classes": [ "one", "two" ]
        })^";

    config_element = Element::fromJSON(config);

    // Should throw a complaint.
    ASSERT_THROW_MSG(parser.parse(config_element),
                     DhcpConfigError,
                     "subnet configuration failed: "
                     "cannot specify both 'require-client-classes' and"
                     " 'evaluate-additional-classes'. Use only the latter.");
}

// Verify that deprecated require-client-classes is handled properly
// by Subnet6 parser.
TEST_F(DhcpParserTest, deprecatedRequireClientClassesSubnet6) {
    // Valid entry.
    std::string config =
       R"^({
            "id": 1,
            "subnet": "2001:db8::/64",
            "require-client-classes": [ "one", "two" ]
        })^";

    ElementPtr config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    Subnet6ConfigParser parser(AF_INET);
    Subnet6Ptr subnet;

    ASSERT_NO_THROW(subnet = parser.parse(config_element));
    ASSERT_TRUE(subnet);

    const auto cclasses = subnet->getAdditionalClasses();
    EXPECT_EQ(cclasses.size(), 2);
    auto cclass = cclasses.begin();
    EXPECT_EQ(*cclass, "one");
    ++cclass;
    EXPECT_EQ(*cclass, "two");

    // Invalid entry specifies both parameters.
    config =
       R"^({
            "id": 1,
            "subnet": "2001:db8::/64",
            "require-client-classes": [ "one", "two" ],
            "evaluate-additional-classes": [ "one", "two" ]
        })^";

    config_element = Element::fromJSON(config);

    // Should throw a complaint.
    ASSERT_THROW_MSG(parser.parse(config_element),
                     DhcpConfigError,
                     "subnet configuration failed: "
                     "cannot specify both 'require-client-classes' and"
                     " 'evaluate-additional-classes'. Use only the latter.");
}

// Verify that deprecated require-client-classes is handled properly
// by Pool4 parser.
TEST_F(DhcpParserTest, deprecatedRequireClientClassesPool4) {
    // Valid entry.
    std::string config =
       R"^({
            "pool": "192.0.2.0/24",
            "require-client-classes": [ "one", "two" ]
        })^";

    ElementPtr config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    Pool4Parser parser;
    PoolStoragePtr pools(new PoolStorage());

    ASSERT_NO_THROW(parser.parse(pools, config_element, AF_INET));
    EXPECT_EQ(1, pools->size());

    const auto cclasses = (*pools)[0]->getAdditionalClasses();
    EXPECT_EQ(cclasses.size(), 2);
    auto cclass = cclasses.begin();
    EXPECT_EQ(*cclass, "one");
    ++cclass;
    EXPECT_EQ(*cclass, "two");

    // Invalid entry specifies both parameters.
    config =
       R"^({
            "pool": "192.0.2.0/24",
            "require-client-classes": [ "one", "two" ],
            "evaluate-additional-classes": [ "one", "two" ]
        })^";

    config_element = Element::fromJSON(config);

    // Should throw a complaint.
    ASSERT_THROW_MSG(parser.parse(pools, config_element, AF_INET),
                     DhcpConfigError,
                     "cannot specify both 'require-client-classes' and"
                     " 'evaluate-additional-classes'. Use only the latter.");
}

// Verify that deprecated require-client-classes is handled properly
// by Pool6 parser.  We only test TYPE_NA and as the same code is
// used for either v6 pool type.
TEST_F(DhcpParserTest, deprecatedRequireClientClassesPool6) {
    // Valid entry.
    std::string config =
       R"^({
            "pool": "2001:db8::/64",
            "require-client-classes": [ "one", "two" ]
        })^";

    ElementPtr config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    Pool6Parser parser;
    PoolStoragePtr pools(new PoolStorage());

    ASSERT_NO_THROW(parser.parse(pools, config_element, AF_INET6, Lease::TYPE_NA));
    EXPECT_EQ(1, pools->size());

    const auto cclasses = (*pools)[0]->getAdditionalClasses();
    EXPECT_EQ(cclasses.size(), 2);
    auto cclass = cclasses.begin();
    EXPECT_EQ(*cclass, "one");
    ++cclass;
    EXPECT_EQ(*cclass, "two");

    // Invalid entry specifies both parameters.
    config =
       R"^({
            "pool": "2001:db8::/64",
            "require-client-classes": [ "one", "two" ],
            "evaluate-additional-classes": [ "one", "two" ]
        })^";

    config_element = Element::fromJSON(config);

    // Should throw a complaint.
    ASSERT_THROW_MSG(parser.parse(pools, config_element, AF_INET6, Lease::TYPE_NA),
                     DhcpConfigError,
                     "cannot specify both 'require-client-classes' and"
                     " 'evaluate-additional-classes'. Use only the latter.");
}

// Verify that deprecated client-class is handled properly
// by Subnet4 parser.
TEST_F(DhcpParserTest, deprecatedClientClassSubnet4) {
    // Valid empty entry.
    std::string config =
       R"^({
            "id": 1,
            "subnet": "192.0.2.0/24",
            "client-class": ""
        })^";

    ElementPtr config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    Subnet4ConfigParser parser(AF_INET);
    Subnet4Ptr subnet;

    ASSERT_NO_THROW(subnet = parser.parse(config_element));
    ASSERT_TRUE(subnet);

    EXPECT_EQ(subnet->getClientClasses().size(), 0);

    // Valid entry.
    config =
       R"^({
            "id": 1,
            "subnet": "192.0.2.0/24",
            "client-class": "one"
        })^";

    config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    ASSERT_NO_THROW(subnet = parser.parse(config_element));
    ASSERT_TRUE(subnet);

    const auto cclasses = subnet->getClientClasses();
    EXPECT_EQ(cclasses.size(), 1);
    auto cclass = cclasses.begin();
    EXPECT_EQ(*cclass, "one");

    // Invalid entry specifies both parameters.
    config =
       R"^({
            "id": 1,
            "subnet": "192.0.2.0/24",
            "client-class": "one",
            "client-classes": [ "one", "two" ]
        })^";

    config_element = Element::fromJSON(config);

    // Should throw a complaint.
    ASSERT_THROW_MSG(parser.parse(config_element),
                     DhcpConfigError,
                     "subnet configuration failed: "
                     "cannot specify both 'client-class' and"
                     " 'client-classes'. Use only the latter.");
}

// Verify that deprecated client-class is handled properly
// by Subnet6 parser.
TEST_F(DhcpParserTest, deprecatedClientClassSubnet6) {
    // Valid empty entry.
    std::string config =
       R"^({
            "id": 1,
            "subnet": "2001:db8::/64",
            "client-class": ""
        })^";

    ElementPtr config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    Subnet6ConfigParser parser(AF_INET);
    Subnet6Ptr subnet;

    ASSERT_NO_THROW(subnet = parser.parse(config_element));
    ASSERT_TRUE(subnet);

    EXPECT_EQ(subnet->getClientClasses().size(), 0);

    // Valid entry.
    config =
       R"^({
            "id": 1,
            "subnet": "2001:db8::/64",
            "client-class": "one"
        })^";

    config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    ASSERT_NO_THROW(subnet = parser.parse(config_element));
    ASSERT_TRUE(subnet);

    const auto cclasses = subnet->getClientClasses();
    EXPECT_EQ(cclasses.size(), 1);
    auto cclass = cclasses.begin();
    EXPECT_EQ(*cclass, "one");

    // Invalid entry specifies both parameters.
    config =
       R"^({
            "id": 1,
            "subnet": "2001:db8::/64",
            "client-class": "one",
            "client-classes": [ "one", "two" ]
        })^";

    config_element = Element::fromJSON(config);

    // Should throw a complaint.
    ASSERT_THROW_MSG(parser.parse(config_element),
                     DhcpConfigError,
                     "subnet configuration failed: "
                     "cannot specify both 'client-class' and"
                     " 'client-classes'. Use only the latter.");
}

// Verify that deprecated client-class is handled properly
// by Pool4 parser. 
TEST_F(DhcpParserTest, deprecatedClientClassPool4) {
    // Valid entry.
    std::string config =
       R"^({
            "pool": "192.0.2.0/24",
            "client-class": "one"
        })^";

    ElementPtr config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    Pool4Parser parser;
    PoolStoragePtr pools(new PoolStorage());

    ASSERT_NO_THROW(parser.parse(pools, config_element, AF_INET));
    EXPECT_EQ(1, pools->size());

    const auto cclasses = (*pools)[0]->getClientClasses();
    EXPECT_EQ(cclasses.size(), 1);
    auto cclass = cclasses.begin();
    EXPECT_EQ(*cclass, "one");

    // Invalid entry specifies both parameters.
    config =
       R"^({
            "pool": "192.0.2.0/24",
            "client-class": "one",
            "client-classes": [ "one", "two" ]
        })^";

    config_element = Element::fromJSON(config);

    // Should throw a complaint.
    ASSERT_THROW_MSG(parser.parse(pools, config_element, AF_INET),
                     DhcpConfigError,
                     "cannot specify both 'client-class' and"
                     " 'client-classes'. Use only the latter.");
}

// Verify that deprecated client-class is handled properly
// by Pool6 parser.  We only test TYPE_NA and as the same code is
// used for either v6 pool type.
TEST_F(DhcpParserTest, deprecatedClientClassPool6) {
    // Valid entry.
    std::string config =
       R"^({
            "pool": "2001:db8::/64",
            "client-class": "one"
        })^";

    ElementPtr config_element = Element::fromJSON(config);

    // Parse configuration specified above.
    Pool6Parser parser;
    PoolStoragePtr pools(new PoolStorage());

    ASSERT_NO_THROW(parser.parse(pools, config_element, AF_INET6, Lease::TYPE_NA));
    EXPECT_EQ(1, pools->size());

    const auto cclasses = (*pools)[0]->getClientClasses();
    EXPECT_EQ(cclasses.size(), 1);
    auto cclass = cclasses.begin();
    EXPECT_EQ(*cclass, "one");

    // Invalid entry specifies both parameters.
    config =
       R"^({
            "pool": "2001:db8::/64",
            "client-class": "one",
            "client-classes": [ "one", "two" ]
        })^";

    config_element = Element::fromJSON(config);

    // Should throw a complaint.
    ASSERT_THROW_MSG(parser.parse(pools, config_element, AF_INET6, Lease::TYPE_NA),
                     DhcpConfigError,
                     "cannot specify both 'client-class' and"
                     " 'client-classes'. Use only the latter.");
}

// Verifies valid permutations of ddns-ttl-percent, ddns-ttl,
// ddns-ttl-min, and ddns-ttl-max values for Subnet4.
TEST_F(DhcpParserTest, validDdnsTtlParmatersSubnet4) {
    validDdnsTtlParmatersSubnet<Subnet4ConfigParser, Subnet4Ptr>(AF_INET);
}

// Verifies invalid permutations of ddns-ttl-percent, ddns-ttl,
// ddns-ttl-min, and ddns-ttl-max values for Subnet4.
TEST_F(DhcpParserTest, invalidDdnsTtlParmatersSubnet4) {
    invalidDdnsTtlParmatersSubnet<Subnet4ConfigParser>(AF_INET);
}

// Verifies valid permutations of ddns-ttl-percent, ddns-ttl,
// ddns-ttl-min, and ddns-ttl-max values for Subnet6.
TEST_F(DhcpParserTest, validDdnsTtlParmatersSubnet6) {
    validDdnsTtlParmatersSubnet<Subnet6ConfigParser, Subnet6Ptr>(AF_INET6);
}

// Verifies invalid permutations of ddns-ttl-percent, ddns-ttl,
// ddns-ttl-min, and ddns-ttl-max values for Subnet6.
TEST_F(DhcpParserTest, invalidDdnsTtlParmatersSubnet6) {
    invalidDdnsTtlParmatersSubnet<Subnet6ConfigParser>(AF_INET6);
}

}  // Anonymous namespace