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
// Copyright (C) 2019-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <asiolink/io_address.h>
#include <cc/stamped_value.h>
#include <dhcp/option_string.h>
#include <dhcpsrv/cb_ctl_dhcp4.h>
#include <dhcpsrv/cb_ctl_dhcp6.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/client_class_def.h>
#include <dhcpsrv/host_mgr.h>
#include <dhcpsrv/random_allocator.h>
#include <dhcpsrv/testutils/memory_host_data_source.h>
#include <dhcpsrv/testutils/generic_backend_unittest.h>
#include <dhcpsrv/testutils/test_config_backend_dhcp4.h>
#include <dhcpsrv/testutils/test_config_backend_dhcp6.h>
#include <hooks/server_hooks.h>
#include <hooks/callout_manager.h>
#include <hooks/hooks_manager.h>
#include <testutils/gtest_utils.h>
#include <boost/foreach.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/date_time/posix_time/posix_time.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/make_shared.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <gtest/gtest.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <iostream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <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 isc::asiolink;
using namespace isc::db;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::dhcp::test;
using namespace isc::process;
using namespace isc::hooks;

namespace {

/// @brief Derivation of the @c MemHostDataSource which always returns
/// @c false when setting IP reservations unique/non-unique mode.
class NonUniqueHostDataSource : public MemHostDataSource {
public:

    /// @brief Virtual destructor.
    virtual ~NonUniqueHostDataSource() {}

    /// @brief Configure unique/non-unique IP reservations.
    ///
    /// @return Always false.
    virtual bool setIPReservationsUnique(const bool) {
        return (false);
    }
};

/// @brief Pointer to the @c NonUniqueHostDataSource instance.
typedef boost::shared_ptr<NonUniqueHostDataSource> NonUniqueHostDataSourcePtr;

/// @brief Base class for testing derivations of the CBControlDHCP.
class CBControlDHCPTest : public GenericBackendTest {
public:

    /// @brief Constructor.
    CBControlDHCPTest()
        : timestamp_(), object_timestamp_(), audit_entries_(),
          modification_id_(2345) {
        CfgMgr::instance().clear();
        initTimestamps();
        callback_name_ = std::string("");
        callback_audit_entries_.reset();
        HostMgr::create();
    }

    /// @brief Destructor.
    virtual ~CBControlDHCPTest() {
        // Unregister the factory to be tidy.
        ConfigBackendDHCPv4Mgr::instance().unregisterBackendFactory("memfile");
        CfgMgr::instance().clear();
        // Unregister hooks.
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("cb4_updated");
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("cb6_updated");
        bool status = HooksManager::unloadLibraries();
        if (!status) {
            std::cerr << "(fixture dtor) unloadLibraries failed" << std::endl;
        }
        HostDataSourceFactory::deregisterFactory("test");
    }

    /// @brief Creates new CREATE audit entry.
    ///
    /// The audit entry is added to the @c audit_entries_ collection.
    ///
    /// @param object_type Object type to be associated with the audit
    /// entry.
    /// @param object_id Identifier of the object to be associated with
    /// the audit entry.
    void addCreateAuditEntry(const std::string& object_type,
                             const uint64_t object_id) {
        AuditEntryPtr entry(new AuditEntry(object_type, object_id,
                                           AuditEntry::ModificationType::CREATE,
                                           ++modification_id_,
                                           "some log message"));
        audit_entries_.insert(entry);
    }

    /// @brief Creates new DELETE audit entry.
    ///
    /// The audit entry is added to the @c audit_entries_ collection.
    ///
    /// @param object_type Object type to be associated with the audit
    /// entry.
    /// @param object_id Identifier of the object to be associated with
    /// the audit entry.
    void addDeleteAuditEntry(const std::string& object_type,
                             const uint64_t object_id) {
        AuditEntryPtr entry(new AuditEntry(object_type, object_id,
                                           AuditEntry::ModificationType::DELETE,
                                           ++modification_id_,
                                           "some log message"));
        audit_entries_.insert(entry);
    }

    /// @brief Initializes timestamps used in tests.
    void initTimestamps() {
        // Get the current timestamp and move it 30 seconds backwards.
        auto now = boost::posix_time::second_clock::local_time() -
            boost::posix_time::seconds(30);

        // Initialize multiple timestamps from the base timestamp. The
        // values with indexes [-5, 0] are in the past. The remaining
        // four are in the future.
        for (int i = -5; i < 5; ++i) {
            timestamp_[i] = now + boost::posix_time::minutes(i);
        }
    }

    /// @brief Returns timestamp associated with a given index.
    ///
    /// @param timestamp_index Index of the timestamp to be returned.
    boost::posix_time::ptime getTimestamp(const int timestamp_index) {
        return (timestamp_[timestamp_index]);
    }

    /// @brief Returns timestamp to be associated with a given object type.
    ///
    /// The object types correspond to the names of the SQL tables holding
    /// them, e.g. dhcp4_global_parameter, dhcp4_subnet etc.
    ///
    /// @param object_type Object type.
    boost::posix_time::ptime getTimestamp(const std::string& object_type) {
        return (object_timestamp_[object_type]);
    }

    /// @brief Associates object type with a timestamp.
    ///
    /// When adding objects to the database, each one is associated with
    /// a modification time value. This value is setup by unit tests
    /// via this method.
    void setTimestamp(const std::string& object_type, const int timestamp_index) {
        object_timestamp_[object_type] = timestamp_[timestamp_index];
    }

    /// @brief Sets timestamps for various object types to the same value.
    ///
    /// @param timestamp_index Index of the timestamp to be set.
    virtual void setAllTimestamps(const int timestamp_index) = 0;

    /// @brief Checks if @c databaseConfigApply should fetch updates for specified
    /// object types.
    ///
    /// @param object_type Object type.
    bool hasConfigElement(const std::string& object_type) const {
        if (!audit_entries_.empty()) {
            auto const& index = audit_entries_.get<AuditEntryObjectTypeTag>();
            auto range = index.equal_range(object_type);
            BOOST_FOREACH(auto const& it, range) {
                if (it->getModificationType() != AuditEntry::ModificationType::DELETE) {
                    return (true);
                }
            }
            return (false);
        }

        return (true);
    }

    /// @brief Check if @c databaseConfigApply should delete a given object from the
    /// local configuration.
    ///
    /// @param object_type Object type.
    /// @param object_id Object identifier.
    bool deleteConfigElement(const std::string& object_type,
                             const uint64_t object_id) const {
        if (!audit_entries_.empty()) {
            auto const& index = audit_entries_.get<AuditEntryObjectTypeTag>();
            auto range = index.equal_range(boost::make_tuple(object_type,
                                                             AuditEntry::ModificationType::DELETE));
            BOOST_FOREACH(auto const& it, range) {
                if (it->getObjectId() == object_id) {
                    return (true);
                }
            }
        }
        return (false);
    }

    /// @brief Callback that stores received callout name and received value.
    ///
    /// @param callout_handle Callout handle.
    static int
    cb4_updated_callout(CalloutHandle& callout_handle) {
        callback_name_ = std::string("cb4_updated");
        callout_handle.getArgument("audit_entries", callback_audit_entries_);
        return (0);
    }

    /// @brief Callback that stores received callout name and received value.
    ///
    /// @param callout_handle Callout handle.
    static int
    cb6_updated_callout(CalloutHandle& callout_handle) {
        callback_name_ = std::string("cb6_updated");
        callout_handle.getArgument("audit_entries", callback_audit_entries_);
        return (0);
    }

    /// @brief Holds test timestamps.
    std::map<int, boost::posix_time::ptime> timestamp_;

    /// @brief Holds mapping of the objects types to their timestamps.
    std::map<std::string, boost::posix_time::ptime> object_timestamp_;

    /// @brief Collection of audit entries used in the unit tests.
    AuditEntryCollection audit_entries_;

    /// @brief Modification id counter.
    uint64_t modification_id_;

    /// @brief Callback name.
    static std::string callback_name_;

    /// @brief Callback value.
    static AuditEntryCollectionPtr callback_audit_entries_;
};

std::string CBControlDHCPTest::callback_name_;
AuditEntryCollectionPtr CBControlDHCPTest::callback_audit_entries_;

// ************************ V4 tests *********************

/// @brief Naked @c CBControlDHCPv4 class exposing protected methods.
class TestCBControlDHCPv4 : public CBControlDHCPv4 {
public:
    /// @brief Constructor.
    TestCBControlDHCPv4() {
        CfgMgr::instance().setFamily(AF_INET);
    }

    using CBControlDHCPv4::getInitialAuditRevisionTime;
    using CBControlDHCPv4::databaseConfigApply;
};

/// @brief Test fixture class for @c CBControlDHCPv4 unit tests.
class CBControlDHCPv4Test : public CBControlDHCPTest {
public:

    /// @brief Constructor.
    CBControlDHCPv4Test()
        : CBControlDHCPTest(), ctl_() {
        ConfigBackendDHCPv4Mgr::instance().registerBackendFactory("memfile",
            [](const DatabaseConnection::ParameterMap& params)
                -> ConfigBackendDHCPv4Ptr {
                    return (TestConfigBackendDHCPv4Ptr(new TestConfigBackendDHCPv4(params)));
             });
        ConfigBackendDHCPv4Mgr::instance().addBackend("type=memfile");

        // By default, set timestamps for all object types to -4. That leaves
        // us with the possibility to use index -5 (earlier) to use as lower
        // bound modification time so as all objects are fetched.
        setAllTimestamps(-4);
    }

    /// @brief Sets timestamps of all DHCPv4 specific object types.
    ///
    /// @param timestamp_index Index of the timestamp to be set.
    virtual void setAllTimestamps(const int timestamp_index) {
        setTimestamp("dhcp4_global_parameter", timestamp_index);
        setTimestamp("dhcp4_option_def", timestamp_index);
        setTimestamp("dhcp4_options", timestamp_index);
        setTimestamp("dhcp4_shared_network", timestamp_index);
        setTimestamp("dhcp4_subnet", timestamp_index);
        setTimestamp("dhcp4_client_class", timestamp_index);
    }

    /// @brief Creates test server configuration and stores it in a test
    /// configuration backend.
    ///
    /// There are pairs of configuration elements stored in the database.
    /// For example: two global parameters, two option definitions etc.
    /// Having two elements of each type in the database is useful in tests
    /// which verify that an element is deleted from the local configuration
    /// as a result of being deleted from the configuration backend. In that
    /// case the test verifies that one of the elements of the given type
    /// is deleted and one is left.
    void remoteStoreTestConfiguration() {
        auto& mgr = ConfigBackendDHCPv4Mgr::instance();

        // Insert global parameters into a database.
        StampedValuePtr global_parameter = StampedValue::create("comment", "bar");
        global_parameter->setModificationTime(getTimestamp("dhcp4_global_parameter"));
        ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter4(BackendSelector::UNSPEC(),
                                                                    ServerSelector::ALL(),
                                                                    global_parameter));

        global_parameter = StampedValue::create("next-server", "teta");
        global_parameter->setModificationTime(getTimestamp("dhcp4_global_parameter"));
        ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter4(BackendSelector::UNSPEC(),
                                                                    ServerSelector::ALL(),
                                                                    global_parameter));

        // Insert option definitions into the database.
        OptionDefinitionPtr def(new OptionDefinition("one", 101, "isc", "uint16"));
        def->setId(1);
        def->setModificationTime(getTimestamp("dhcp4_option_def"));
        ASSERT_NO_THROW(mgr.getPool()->createUpdateOptionDef4(BackendSelector::UNSPEC(),
                                                              ServerSelector::ALL(),
                                                              def));
        def.reset(new OptionDefinition("two", 102, "isc", "uint16"));
        def->setId(2);
        def->setModificationTime(getTimestamp("dhcp4_option_def"));
        ASSERT_NO_THROW(mgr.getPool()->createUpdateOptionDef4(BackendSelector::UNSPEC(),
                                                              ServerSelector::ALL(),
                                                              def));

        // Insert global options into the database.
        OptionDescriptorPtr opt(new OptionDescriptor(createOption<OptionString>
                                                     (Option::V4, DHO_HOST_NAME,
                                                      true, false, false,
                                                      "new.example.com")));
        opt->setId(1);
        opt->space_name_ = DHCP4_OPTION_SPACE;
        opt->setModificationTime(getTimestamp("dhcp4_options"));
        mgr.getPool()->createUpdateOption4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                           opt);

        opt.reset(new OptionDescriptor(createOption<OptionString>
                                       (Option::V4, DHO_TFTP_SERVER_NAME,
                                        true, false, false, "tftp-my")));
        opt->setId(2);
        opt->space_name_ = DHCP4_OPTION_SPACE;
        opt->setModificationTime(getTimestamp("dhcp4_options"));
        mgr.getPool()->createUpdateOption4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                           opt);

        // Insert shared networks into the database.
        SharedNetwork4Ptr network(new SharedNetwork4("one"));
        network->setId(1);
        network->setModificationTime(getTimestamp("dhcp4_shared_network"));
        mgr.getPool()->createUpdateSharedNetwork4(BackendSelector::UNSPEC(),
                                                  ServerSelector::ALL(),
                                                  network);

        network.reset(new SharedNetwork4("two"));
        network->setId(2);
        network->setModificationTime(getTimestamp("dhcp4_shared_network"));
        mgr.getPool()->createUpdateSharedNetwork4(BackendSelector::UNSPEC(),
                                                  ServerSelector::ALL(),
                                                  network);

        // Insert subnets into the database.
        Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.3.0"), 26, 1, 2, 3, SubnetID(1)));
        subnet->setModificationTime(getTimestamp("dhcp4_subnet"));
        subnet->setAllocatorType("random");
        subnet->setSharedNetworkName("one");
        mgr.getPool()->createUpdateSubnet4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                           subnet);

        subnet.reset(new Subnet4(IOAddress("192.0.4.0"), 26, 1, 2, 3, SubnetID(2)));
        subnet->setModificationTime(getTimestamp("dhcp4_subnet"));
        mgr.getPool()->createUpdateSubnet4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                           subnet);

        // Insert client classes into the database.
        auto expression = boost::make_shared<Expression>();
        ClientClassDefPtr client_class = boost::make_shared<ClientClassDef>("first-class", expression);
        client_class->setTest("substring(option[1].hex, 0, 8) == 'my-value'");
        client_class->setId(1);
        client_class->setModificationTime(getTimestamp("dhcp4_client_class"));

        // Add a standard option to the class.
        OptionPtr option = Option::create(Option::V4, DHO_BOOT_FILE_NAME);
        OptionDescriptorPtr desc = OptionDescriptor::create(option,
                                                            true,
                                                            false,
                                                            "bogus-file.txt");
        desc->space_name_ = DHCP4_OPTION_SPACE;
        desc->setModificationTime(getTimestamp("dhcp4_client_class"));
        client_class->getCfgOption()->add(*desc, desc->space_name_);

        // Add a custom option definition to the class.
        CfgOptionDefPtr cc_cfg_option_def(new CfgOptionDef());
        def.reset(new OptionDefinition("v4str", 201, "isc", "string"));
        def->setId(201);
        def->setModificationTime(getTimestamp("dhcp4_client_class"));
        cc_cfg_option_def->add(def);
        client_class->setCfgOptionDef(cc_cfg_option_def);

        // Add a custom option to the class.
        option = Option::create(Option::V4, 201);
        desc = OptionDescriptor::create(option, true, false, "custom-stuff");
        desc->space_name_ = "isc";
        desc->setModificationTime(getTimestamp("dhcp4_client_class"));
        client_class->getCfgOption()->add(*desc, desc->space_name_);

        mgr.getPool()->createUpdateClientClass4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                                client_class, "");

        client_class = boost::make_shared<ClientClassDef>("second-class", expression);
        client_class->setId(2);
        client_class->setModificationTime(getTimestamp("dhcp4_client_class"));
        mgr.getPool()->createUpdateClientClass4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                                client_class, "");
    }

    /// @brief Deletes specified global parameter from the configuration
    /// backend and generates audit entry.
    ///
    /// Note that the current Kea implementation does not track database
    /// identifiers of the global parameters. Therefore, the identifier to
    /// be used to create the audit entry for the deleted parameter must
    /// be explicitly specified.
    ///
    /// @param parameter_name Parameter name.
    /// @param id Parameter id.
    void remoteDeleteGlobalParameter(const std::string& parameter_name,
                                     const uint64_t id) {
        auto& mgr = ConfigBackendDHCPv4Mgr::instance();
        mgr.getPool()->deleteGlobalParameter4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                             parameter_name);
        addDeleteAuditEntry("dhcp4_global_parameter", id);
    }

    /// @brief Deletes specified option definition from the configuration
    /// backend and generates audit entry.
    ///
    /// @param code Option code.
    /// @param space Option space.
    void remoteDeleteOptionDef(const uint16_t code, const std::string& space) {
        auto& mgr = ConfigBackendDHCPv4Mgr::instance();

        auto option_def = mgr.getPool()->getOptionDef4(BackendSelector::UNSPEC(),
                                                       ServerSelector::ALL(),
                                                       code, space);

        if (option_def) {
            mgr.getPool()->deleteOptionDef4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                            code, space);
            addDeleteAuditEntry("dhcp4_option_def", option_def->getId());
        }
    }

    /// @brief Deletes specified global option from the configuration backend
    /// and generates audit entry.
    ///
    /// @param code Option code.
    /// @param space Option space.
    void remoteDeleteOption(const uint16_t code, const std::string& space) {
        auto& mgr = ConfigBackendDHCPv4Mgr::instance();

        auto option = mgr.getPool()->getOption4(BackendSelector::UNSPEC(),
                                                ServerSelector::ALL(),
                                                code, space);

        if (option) {
            mgr.getPool()->deleteOptionDef4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                            code, space);
            addDeleteAuditEntry("dhcp4_option_def", option->getId());
        }
    }

    /// @brief Deletes specified shared network from the configuration backend
    /// and generates audit entry.
    ///
    /// @param name Name of the shared network to be deleted.
    void remoteDeleteSharedNetwork(const std::string& name) {
        auto& mgr = ConfigBackendDHCPv4Mgr::instance();

        auto network = mgr.getPool()->getSharedNetwork4(BackendSelector::UNSPEC(),
                                                        ServerSelector::ALL(),
                                                        name);

        if (network) {
            mgr.getPool()->deleteSharedNetwork4(BackendSelector::UNSPEC(),
                                                ServerSelector::ALL(),
                                                name);
            addDeleteAuditEntry("dhcp4_shared_network", network->getId());
        }
    }

    /// @brief Deletes specified subnet from the configuration backend and
    /// generates audit entry.
    void remoteDeleteSubnet(const SubnetID& id) {
        auto& mgr = ConfigBackendDHCPv4Mgr::instance();

        mgr.getPool()->deleteSubnet4(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                     id);
        addDeleteAuditEntry("dhcp4_subnet", id);
    }

    /// @brief Deletes specified client class from the configuration backend
    /// and generates audit entry.
    ///
    /// @param name Name of the client class to be deleted.
    void remoteDeleteClientClass(const std::string& name) {
        auto& mgr = ConfigBackendDHCPv4Mgr::instance();

        auto client_class = mgr.getPool()->getClientClass4(BackendSelector::UNSPEC(),
                                                           ServerSelector::ALL(),
                                                           name);

        if (client_class) {
            mgr.getPool()->deleteClientClass4(BackendSelector::UNSPEC(),
                                              ServerSelector::ALL(),
                                              name);
            addDeleteAuditEntry("dhcp4_client_class", client_class->getId());
        }
    }

    /// @brief Tests the @c CBControlDHCPv4::databaseConfigApply method.
    ///
    /// This test inserts configuration elements of each type into the
    /// configuration database. Next, it calls the @c databaseConfigApply,
    /// which should merge each object from the database for which the
    /// CREATE or UPDATE audit entry is found. The test then verifies
    /// if the appropriate entries have been merged.
    ///
    /// @param lb_modification_time Lower bound modification time to be
    /// passed to the @c databaseConfigApply.
    void testDatabaseConfigApply(const boost::posix_time::ptime& lb_modification_time) {
        remoteStoreTestConfiguration();

        ASSERT_FALSE(audit_entries_.empty())
            << "Require at least one audit entry. The test is broken!";

        ASSERT_NO_THROW_LOG(ctl_.databaseConfigApply(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                            lb_modification_time, audit_entries_));

        // The updates should have been merged into current configuration.
        auto srv_cfg = CfgMgr::instance().getCurrentCfg();

        // If there is an audit entry for global parameter and the parameter
        // modification time is later than last audit revision time it should
        // be merged.
        if (hasConfigElement("dhcp4_global_parameter") &&
            (getTimestamp("dhcp4_global_parameter") > lb_modification_time)) {
            checkConfiguredGlobal(srv_cfg, "comment", Element::create("bar"));

        } else {
            // Otherwise it shouldn't exist.
            EXPECT_FALSE(srv_cfg->getConfiguredGlobals()->get("comment"));
        }

        // If there is an audit entry for option definition and the definition
        // modification time is later than last audit revision time it should
        // be merged.
        auto found_def = srv_cfg->getCfgOptionDef()->get("isc", "one");
        if (hasConfigElement("dhcp4_option_def") &&
            getTimestamp("dhcp4_option_def") > lb_modification_time) {
            ASSERT_TRUE(found_def);
            EXPECT_EQ(101, found_def->getCode());
            EXPECT_EQ(OptionDataType::OPT_UINT16_TYPE, found_def->getType());

        } else {
            EXPECT_FALSE(found_def);
        }

        // If there is an audit entry for an option and the option
        // modification time is later than last audit revision time it should
        // be merged.
        auto options = srv_cfg->getCfgOption();
        auto found_opt = options->get(DHCP4_OPTION_SPACE, DHO_HOST_NAME);
        if (hasConfigElement("dhcp4_options") &&
            (getTimestamp("dhcp4_options") > lb_modification_time)) {
            ASSERT_TRUE(found_opt.option_);
            EXPECT_EQ("new.example.com", found_opt.option_->toString());

        } else {
            EXPECT_FALSE(found_opt.option_);
        }

        // If there is an audit entry for a shared network and the network
        // modification time is later than last audit revision time it should
        // be merged.
        auto networks = srv_cfg->getCfgSharedNetworks4();
        auto found_network = networks->getByName("one");
        if (hasConfigElement("dhcp4_shared_network") &&
            (getTimestamp("dhcp4_shared_network") > lb_modification_time)) {
            ASSERT_TRUE(found_network);
            EXPECT_TRUE(found_network->hasFetchGlobalsFn());

        } else {
            EXPECT_FALSE(found_network);
        }

        // If there is an audit entry for a subnet and the subnet modification
        // time is later than last audit revision time it should be merged.
        auto subnets = srv_cfg->getCfgSubnets4();
        auto found_subnet = subnets->getBySubnetId(1);
        if (hasConfigElement("dhcp4_subnet") &&
            (getTimestamp("dhcp4_subnet") > lb_modification_time)) {
            ASSERT_TRUE(found_subnet);
            EXPECT_TRUE(found_subnet->hasFetchGlobalsFn());
            EXPECT_TRUE(boost::dynamic_pointer_cast<RandomAllocator>
                        (found_subnet->getAllocator(Lease::TYPE_V4)));

        } else {
            EXPECT_FALSE(found_subnet);
        }

        auto client_classes = srv_cfg->getClientClassDictionary();
        auto found_class = client_classes->findClass("first-class");
        if (hasConfigElement("dhcp4_client_class") &&
            (getTimestamp("dhcp4_client_class") > lb_modification_time)) {
            ASSERT_TRUE(found_class);
            ASSERT_TRUE(found_class->getMatchExpr());
            EXPECT_GT(found_class->getMatchExpr()->size(), 0);
            EXPECT_EQ("first-class", found_class->getName());

            // Check for the standard class option, make sure it has been "created".
            auto cfg_option_desc = found_class->getCfgOption();
            ASSERT_TRUE(cfg_option_desc);
            auto option_desc = cfg_option_desc->get(DHCP4_OPTION_SPACE, DHO_BOOT_FILE_NAME);
            auto option = option_desc.option_;
            ASSERT_TRUE(option);
            EXPECT_EQ(OptionBuffer(option_desc.formatted_value_.begin(),
                                   option_desc.formatted_value_.end()),
                      option->getData());

            // Check for the custom class option, make sure it has been "created".
            option_desc = cfg_option_desc->get("isc", 201);
            option = option_desc.option_;
            ASSERT_TRUE(option);
            EXPECT_EQ(OptionBuffer(option_desc.formatted_value_.begin(),
                                   option_desc.formatted_value_.end()),
                      option->getData());
        } else {
            EXPECT_FALSE(found_class);
        }
    }

    /// @brief Tests deletion of the configuration elements by the
    /// @c CBControlDHCPv4::databaseConfigApply method.
    ///
    /// This test inserts configuration elements of each type into the
    /// configuration database and calls the @c databaseConfigApply
    /// to fetch this configuration and merge into the local server
    /// configuration.
    ///
    /// Next, the test calls the specified callback function, i.e.
    /// @c db_modifications, which deletes selected configuration
    /// elements from the database and generates appropriate audit
    /// entries. Finally, it calls the @c databaseConfigApply again
    /// to process the audit entries and checks if the appropriate
    /// configuration elements are deleted from the local configuration
    ///
    /// @param lb_modification_time Lower bound modification time to be
    /// passed to the @c databaseConfigApply.
    /// @param db_modifications Pointer to the callback function which
    /// applies test specific modifications into the database.
    void testDatabaseConfigApplyDelete(const boost::posix_time::ptime& lb_modification_time,
                                       std::function<void()> db_modifications) {
        // Store initial configuration into the database.
        remoteStoreTestConfiguration();

        // Since we pass an empty audit collection the server treats this
        // as if the server is starting up and fetches the entire
        // configuration from the database.
        ctl_.databaseConfigApply(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                 ctl_.getInitialAuditRevisionTime(),
                                 AuditEntryCollection());
        // Commit the configuration so as it is moved from the staging
        // to current.
        CfgMgr::instance().commit();

        // Run user defined callback which should delete selected configuration
        // elements from the configuration backend. The appropriate DELETE
        // audit entries should now be stored in the audit_entries_ collection.
        if (db_modifications) {
            db_modifications();
        }

        // Process the DELETE audit entries.
        ctl_.databaseConfigApply(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                 lb_modification_time, audit_entries_);

        // All changes should have been applied in the current configuration.
        auto srv_cfg = CfgMgr::instance().getCurrentCfg();

        {
            SCOPED_TRACE("global parameters");
            // One of the global parameters should still be there.
            EXPECT_TRUE(srv_cfg->getConfiguredGlobals()->get("next-server"));
            if (deleteConfigElement("dhcp4_global_parameter", 1)) {
                EXPECT_FALSE(srv_cfg->getConfiguredGlobals()->get("comment"));

            } else {
                EXPECT_TRUE(srv_cfg->getConfiguredGlobals()->get("next-server"));
            }
        }

        {
            SCOPED_TRACE("option definitions");
            // One of the option definitions should still be there.
            EXPECT_TRUE(srv_cfg->getCfgOptionDef()->get("isc", "two"));
            auto found_def = srv_cfg->getCfgOptionDef()->get("isc", "one");
            if (deleteConfigElement("dhcp4_option_def", 1)) {
                EXPECT_FALSE(found_def);

            } else {
                EXPECT_TRUE(found_def);
            }
        }

        {
            SCOPED_TRACE("global options");
            // One of the options should still be there.
            EXPECT_TRUE(srv_cfg->getCfgOption()->get(DHCP4_OPTION_SPACE,
                                                     DHO_TFTP_SERVER_NAME).option_);
            auto found_opt = srv_cfg->getCfgOption()->get(DHCP4_OPTION_SPACE,
                                                          DHO_HOST_NAME);
            if (deleteConfigElement("dhcp4_options", 1)) {
                EXPECT_FALSE(found_opt.option_);

            } else {
                EXPECT_TRUE(found_opt.option_);
            }
        }

        {
            SCOPED_TRACE("shared networks");
            // One of the shared networks should still be there.
            EXPECT_TRUE(srv_cfg->getCfgSharedNetworks4()->getByName("two"));
            auto found_network = srv_cfg->getCfgSharedNetworks4()->getByName("one");
            if (deleteConfigElement("dhcp4_shared_network", 1)) {
                EXPECT_FALSE(found_network);

            } else {
                EXPECT_TRUE(found_network);
            }
        }

        {
            SCOPED_TRACE("subnets");
            // One of the subnets should still be there.
            EXPECT_TRUE(srv_cfg->getCfgSubnets4()->getBySubnetId(2));
            auto found_subnet = srv_cfg->getCfgSubnets4()->getBySubnetId(1);
            if (deleteConfigElement("dhcp4_subnet", 1)) {
                EXPECT_FALSE(found_subnet);

                // If the subnet has been deleted, make sure that
                // it was detached from the shared network it belonged
                // to, if the shared network still exists.
                auto found_network = srv_cfg->getCfgSharedNetworks4()->getByName("one");
                if (found_network) {
                    EXPECT_TRUE(found_network->getAllSubnets()->empty());
                }

            } else {
                EXPECT_TRUE(found_subnet);
            }
        }

        {
            SCOPED_TRACE("client classes");
            // One of the subnets should still be there.
            EXPECT_TRUE(srv_cfg->getClientClassDictionary()->findClass("second-class"));
            auto found_client_class = srv_cfg->getClientClassDictionary()->findClass("first-class");
            if (deleteConfigElement("dhcp4_client_class", 1)) {
                EXPECT_FALSE(found_client_class);

            } else {
                EXPECT_TRUE(found_client_class);
            }
        }
    }

    /// @brief Instance of the @c CBControlDHCPv4 used for testing.
    TestCBControlDHCPv4 ctl_;
};


// This test verifies that the configuration updates for all object
// types are merged into the current configuration.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyAll) {<--- syntax error

    addCreateAuditEntry("dhcp4_global_parameter", 1);
    addCreateAuditEntry("dhcp4_global_parameter", 2);
    addCreateAuditEntry("dhcp4_option_def", 1);
    addCreateAuditEntry("dhcp4_option_def", 2);
    addCreateAuditEntry("dhcp4_options", 1);
    addCreateAuditEntry("dhcp4_options", 2);
    addCreateAuditEntry("dhcp4_shared_network", 1);
    addCreateAuditEntry("dhcp4_shared_network", 2);
    addCreateAuditEntry("dhcp4_subnet", 1);
    addCreateAuditEntry("dhcp4_subnet", 2);
    addCreateAuditEntry("dhcp4_client_class", 1);
    addCreateAuditEntry("dhcp4_client_class", 2);

    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that multiple configuration elements are
// deleted from the local configuration as a result of being
// deleted from the database.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyDeleteAll) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteGlobalParameter("comment", 1);
        remoteDeleteOptionDef(101, "isc");
        remoteDeleteOption(DHO_HOST_NAME, DHCP4_OPTION_SPACE);
        remoteDeleteSharedNetwork("one");
        remoteDeleteSubnet(SubnetID(1));
        remoteDeleteClientClass("first-class");
    });
}

// This test verifies that an attempt to delete non-existing
// configuration element does not cause an error.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyDeleteNonExisting) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        // Add several audit entries instructing to delete the
        // non-existing configuration elements. The ids are set
        // to 3, but the only existing elements have ids of 1
        // and 2.
        addDeleteAuditEntry("dhcp4_global_parameter", 3);
        addDeleteAuditEntry("dhcp4_option_def", 3);
        addDeleteAuditEntry("dhcp4_options", 3);
        addDeleteAuditEntry("dhcp4_shared_network", 3);
        addDeleteAuditEntry("dhcp4_subnet", 3);
        addDeleteAuditEntry("dhcp4_client_class", 3);
    });
}

// This test verifies that only a global parameter is merged into
// the current configuration.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyGlobal) {
    addCreateAuditEntry("dhcp4_global_parameter", 1);
    addCreateAuditEntry("dhcp4_global_parameter", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the global parameter is deleted from
// the local configuration as a result of being deleted from the
// database.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyDeleteGlobal) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteGlobalParameter("comment", 1);
    });
}

// This test verifies that global parameter is not fetched from the
// database when the modification time is earlier than the last
// fetched audit entry.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyGlobalNotFetched) {
    addCreateAuditEntry("dhcp4_global_parameter", 1);
    addCreateAuditEntry("dhcp4_global_parameter", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only an option definition is merged into
// the current configuration.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyOptionDef) {
    addCreateAuditEntry("dhcp4_option_def", 1);
    addCreateAuditEntry("dhcp4_option_def", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the option definition is deleted from
// the local configuration as a result of being deleted from the
// database.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyDeleteOptionDef) {
    addDeleteAuditEntry("dhcp4_option_def", 1);
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteOptionDef(101, "isc");
    });
}

// This test verifies that option definition is not fetched from the
// database when the modification time is earlier than the last
// fetched audit entry.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyOptionDefNotFetched) {
    addCreateAuditEntry("dhcp4_option_def", 1);
    addCreateAuditEntry("dhcp4_option_def", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only a DHCPv4 option is merged into the
// current configuration.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyOption) {
    addCreateAuditEntry("dhcp4_options", 1);
    addCreateAuditEntry("dhcp4_options", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the global option is deleted from
// the local configuration as a result of being deleted from the
// database.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyDeleteOption) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteOption(DHO_HOST_NAME, DHCP4_OPTION_SPACE);
    });
}

// This test verifies that DHCPv4 option is not fetched from the
// database when the modification time is earlier than the last
// fetched audit entry.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyOptionNotFetched) {
    addCreateAuditEntry("dhcp4_options", 1);
    addCreateAuditEntry("dhcp4_options", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only a shared network is merged into the
// current configuration.
TEST_F(CBControlDHCPv4Test, databaseConfigApplySharedNetwork) {
    addCreateAuditEntry("dhcp4_shared_network", 1);
    addCreateAuditEntry("dhcp4_shared_network", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the shared network is deleted from
// the local configuration as a result of being deleted from the
// database.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyDeleteSharedNetwork) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteSharedNetwork("one");
    });
}

// This test verifies that shared network is not fetched from the
// database when the modification time is earlier than the last
// fetched audit entry.
TEST_F(CBControlDHCPv4Test, databaseConfigApplySharedNetworkNotFetched) {
    addCreateAuditEntry("dhcp4_shared_network", 1);
    addCreateAuditEntry("dhcp4_shared_network", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only a subnet is merged into the current
// configuration.
TEST_F(CBControlDHCPv4Test, databaseConfigApplySubnet) {
    addCreateAuditEntry("dhcp4_shared_network", 1);
    addCreateAuditEntry("dhcp4_shared_network", 2);
    addCreateAuditEntry("dhcp4_subnet", 1);
    addCreateAuditEntry("dhcp4_subnet", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the subnet is deleted from the local
// configuration as a result of being deleted from the database.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyDeleteSubnet) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteSubnet(SubnetID(1));
    });
}

// This test verifies that subnet is not fetched from the database
// when the modification time is earlier than the last fetched audit
// entry.
TEST_F(CBControlDHCPv4Test, databaseConfigApplySubnetNotFetched) {
    addCreateAuditEntry("dhcp4_subnet", 1);
    addCreateAuditEntry("dhcp4_subnet", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only client classes are merged into the current
// configuration.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyClientClasses) {
    addCreateAuditEntry("dhcp4_client_class", 1);
    addCreateAuditEntry("dhcp4_client_class", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that a client class is deleted from the local
// configuration as a result of being deleted from the database.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyDeleteClientClass) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteClientClass("first-class");
    });
}

// This test verifies that the configuration update calls the hook.
TEST_F(CBControlDHCPv4Test, databaseConfigApplyHook) {

    // Initialize Hooks Manager.
    HooksManager::loadLibraries(HookLibsCollection());

    // Install cb4_updated.
    EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
        "cb4_updated", cb4_updated_callout));

    // Create audit entries.
    addCreateAuditEntry("dhcp4_global_parameter", 1);
    addCreateAuditEntry("dhcp4_global_parameter", 2);
    addCreateAuditEntry("dhcp4_option_def", 1);
    addCreateAuditEntry("dhcp4_option_def", 2);
    addCreateAuditEntry("dhcp4_options", 1);
    addCreateAuditEntry("dhcp4_options", 2);
    addCreateAuditEntry("dhcp4_shared_network", 1);
    addCreateAuditEntry("dhcp4_shared_network", 2);
    addCreateAuditEntry("dhcp4_subnet", 1);
    addCreateAuditEntry("dhcp4_subnet", 2);

    // Run the test.
    testDatabaseConfigApply(getTimestamp(-5));

    // Checks the callout.
    EXPECT_EQ("cb4_updated", callback_name_);
    ASSERT_TRUE(callback_audit_entries_);
    EXPECT_TRUE(audit_entries_ == *callback_audit_entries_);
}

// This test verifies that it is possible to set ip-reservations-unique
// parameter via configuration backend and that it is successful when
// host database backend accepts the new setting.
TEST_F(CBControlDHCPv4Test, ipReservationsNonUniqueAccepted) {
    // Create host data source which accepts setting non-unique IP
    // reservations.
    MemHostDataSourcePtr hds(new MemHostDataSource());
    auto testFactory = [hds](const DatabaseConnection::ParameterMap&) {
        return (hds);
    };
    HostDataSourceFactory::registerFactory("test", testFactory);
    HostMgr::addBackend("type=test");

    // Insert ip-reservations-unique value set to false into the database.
    auto& mgr = ConfigBackendDHCPv4Mgr::instance();
    StampedValuePtr global_parameter = StampedValue::create("ip-reservations-unique",
                                                            Element::create(false));
    ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter4(BackendSelector::UNSPEC(),
                                                                ServerSelector::ALL(),
                                                                global_parameter));
    // Adding audit entry simulates the case when the server is already configured
    // and we're adding incremental changes. These changes should be applied to
    // the current configuration.
    addCreateAuditEntry("dhcp4_global_parameter", 1);

    // Apply the configuration.
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));
    // The new setting should be visible in both CfgDbAccess and HostMgr.
    EXPECT_FALSE(CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique());
    EXPECT_FALSE(HostMgr::instance().getIPReservationsUnique());
}

// This test verifies that the new setting of ip-reservations-unique is not
// accepted when one of the host database backends does not support it.
TEST_F(CBControlDHCPv4Test, ipReservationsNonUniqueRefused) {
    // Create host data source which does not accept setting IP reservations
    // non-unique setting.
    NonUniqueHostDataSourcePtr hds(new NonUniqueHostDataSource());
    auto testFactory = [hds](const DatabaseConnection::ParameterMap&) {
        return (hds);
    };
    HostDataSourceFactory::registerFactory("test", testFactory);
    HostMgr::addBackend("type=test");

    // Insert ip-reservations-unique value set to false into the database.
    auto& mgr = ConfigBackendDHCPv4Mgr::instance();
    StampedValuePtr global_parameter = StampedValue::create("ip-reservations-unique",
                                                            Element::create(false));
    ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter4(BackendSelector::UNSPEC(),
                                                                ServerSelector::ALL(),
                                                                global_parameter));
    // Adding audit entry simulates the case when the server is already configured
    // and we're adding incremental changes. These changes should be applied to
    // the current configuration.
    addCreateAuditEntry("dhcp4_global_parameter", 1);

    // Apply the configuration.
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));
    // The default setting should be applied, because the backend refused to
    // set it to false.
    EXPECT_TRUE(CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique());
    EXPECT_TRUE(HostMgr::instance().getIPReservationsUnique());
}

// This test verifies that the allocator type is inherited from the global to
// shared network to subnet level.
TEST_F(CBControlDHCPv4Test, allocatorInheritance) {
    remoteStoreTestConfiguration();

    // Set non-default global allocator.
    StampedValuePtr global_parameter = StampedValue::create("allocator",
                                                            Element::create("flq"));
    auto& mgr = ConfigBackendDHCPv4Mgr::instance();
    ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter4(BackendSelector::UNSPEC(),
                                                                ServerSelector::ALL(),
                                                                global_parameter));
    addCreateAuditEntry("dhcp4_global_parameter", 1);
    addCreateAuditEntry("dhcp4_shared_network", 1);
    addCreateAuditEntry("dhcp4_subnet", 2);

    // Merge the configuration including the allocator setting into the current
    // configuration.
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet that has no allocator specification. The global allocator should
    // be used for this subnet.
    auto srv_cfg = CfgMgr::instance().getCurrentCfg();
    auto subnet = srv_cfg->getCfgSubnets4()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    auto allocator = subnet->getAllocator(Lease::TYPE_V4);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("flq", allocator->getType());

    // Update the shared network but use a different allocator type for it.
    auto updated_network = boost::make_shared<SharedNetwork4>("one");
    updated_network->setId(1);
    updated_network->setModificationTime(getTimestamp("dhcp4_shared_network"));
    updated_network->setAllocatorType("random");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSharedNetwork4(BackendSelector::UNSPEC(),
                                                              ServerSelector::ALL(),
                                                              updated_network));


    // Include our subnet in this shared network.
    auto updated_subnet = boost::make_shared<Subnet4>(IOAddress("192.0.4.0"), 26, 1, 2, 3,
                                                      SubnetID(2));
    updated_subnet->setSharedNetworkName("one");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSubnet4(BackendSelector::UNSPEC(),
                                                       ServerSelector::ALL(),
                                                       updated_subnet));
    // Merge the updated configuration.
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet again. Expect that the subnet uses the shared network-level allocator.
    subnet = srv_cfg->getCfgSubnets4()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    allocator = subnet->getAllocator(Lease::TYPE_V4);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("random", allocator->getType());

    // Override the allocator at the subnet level.
    updated_subnet = boost::make_shared<Subnet4>(IOAddress("192.0.4.0"), 26, 1, 2, 3, SubnetID(2));
    updated_subnet->setModificationTime(getTimestamp("dhcp4_subnet"));
    updated_subnet->setAllocatorType("iterative");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSubnet4(BackendSelector::UNSPEC(),
                                                       ServerSelector::ALL(),
                                                       updated_subnet));

    addCreateAuditEntry("dhcp4_subnet", 2);
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet again and expect the subnet-level allocator.
    subnet = srv_cfg->getCfgSubnets4()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    allocator = subnet->getAllocator(Lease::TYPE_V4);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("iterative", allocator->getType());
}

// ************************ V6 tests *********************

/// @brief Naked @c CBControlDHCPv6 class exposing protected methods.
class TestCBControlDHCPv6 : public CBControlDHCPv6 {
public:
    /// @brief Constructor.
    TestCBControlDHCPv6() {
        CfgMgr::instance().setFamily(AF_INET6);
    }

    using CBControlDHCPv6::getInitialAuditRevisionTime;
    using CBControlDHCPv6::databaseConfigApply;
};

/// @brief Test fixture class for @c CBControlDHCPv6 unit tests.
class CBControlDHCPv6Test : public CBControlDHCPTest {
public:

    /// @brief Constructor.
    CBControlDHCPv6Test()
        : CBControlDHCPTest(), ctl_() {
        ConfigBackendDHCPv6Mgr::instance().registerBackendFactory("memfile",
            [](const DatabaseConnection::ParameterMap& params)
                -> ConfigBackendDHCPv6Ptr {
                    return (TestConfigBackendDHCPv6Ptr(new TestConfigBackendDHCPv6(params)));
             });
        ConfigBackendDHCPv6Mgr::instance().addBackend("type=memfile");

        // By default, set timestamps for all object types to -4. That leaves
        // us with the possibility to use index -5 (earlier) to use as lower
        // bound modification time so as all objects are fetched.
        setAllTimestamps(-4);
    }

    /// @brief Sets timestamps of all DHCPv6 specific object types.
    ///
    /// @param timestamp_index Index of the timestamp to be set.
    virtual void setAllTimestamps(const int timestamp_index) {
        setTimestamp("dhcp6_global_parameter", timestamp_index);
        setTimestamp("dhcp6_option_def", timestamp_index);
        setTimestamp("dhcp6_options", timestamp_index);
        setTimestamp("dhcp6_shared_network", timestamp_index);
        setTimestamp("dhcp6_subnet", timestamp_index);
        setTimestamp("dhcp6_client_class", timestamp_index);
    }

    /// @brief Creates test server configuration and stores it in a test
    /// configuration backend.
    ///
    /// There are pairs of configuration elements stored in the database.
    /// For example: two global parameters, two option definitions etc.
    /// Having two elements of each type in the database is useful in tests
    /// which verify that an element is deleted from the local configuration
    /// as a result of being deleted from the configuration backend. In that
    /// case the test verifies that one of the elements of the given type
    /// is deleted and one is left.
    void remoteStoreTestConfiguration() {
        auto& mgr = ConfigBackendDHCPv6Mgr::instance();

        // Insert global parameters into a database.
        StampedValuePtr global_parameter = StampedValue::create("comment", "bar");
        global_parameter->setModificationTime(getTimestamp("dhcp6_global_parameter"));
        ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter6(BackendSelector::UNSPEC(),
                                                                    ServerSelector::ALL(),
                                                                    global_parameter));

        global_parameter = StampedValue::create("data-directory", "teta");
        global_parameter->setModificationTime(getTimestamp("dhcp6_global_parameter"));
        ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter6(BackendSelector::UNSPEC(),
                                                                    ServerSelector::ALL(),
                                                                    global_parameter));

        // Insert option definitions into the database.
        OptionDefinitionPtr def(new OptionDefinition("one", 101, "isc", "uint16"));
        def->setId(1);
        def->setModificationTime(getTimestamp("dhcp6_option_def"));
        ASSERT_NO_THROW(mgr.getPool()->createUpdateOptionDef6(BackendSelector::UNSPEC(),
                                                              ServerSelector::ALL(),
                                                              def));
        def.reset(new OptionDefinition("two", 102, "isc", "uint16"));
        def->setId(2);
        def->setModificationTime(getTimestamp("dhcp6_option_def"));
        ASSERT_NO_THROW(mgr.getPool()->createUpdateOptionDef6(BackendSelector::UNSPEC(),
                                                              ServerSelector::ALL(),
                                                              def));

        // Insert global options into the database.
        OptionDescriptorPtr opt(new OptionDescriptor(createOption<OptionString>
                                                     (Option::V6, D6O_BOOTFILE_URL,
                                                      true, false, false,
                                                      "some.bootfile")));
        opt->setId(1);
        opt->space_name_ = DHCP6_OPTION_SPACE;
        opt->setModificationTime(getTimestamp("dhcp6_options"));
        mgr.getPool()->createUpdateOption6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                           opt);

        opt.reset(new OptionDescriptor(createOption<OptionString>
                                       (Option::V6, D6O_AFTR_NAME,
                                        true, true, true,
                                        "some.example.com")));
        opt->setId(2);
        opt->space_name_ = DHCP6_OPTION_SPACE;
        opt->setModificationTime(getTimestamp("dhcp6_options"));
        mgr.getPool()->createUpdateOption6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                           opt);

        // Insert shared networks into the database.
        SharedNetwork6Ptr network(new SharedNetwork6("one"));
        network->setId(1);
        network->setModificationTime(getTimestamp("dhcp6_shared_network"));
        mgr.getPool()->createUpdateSharedNetwork6(BackendSelector::UNSPEC(),
                                                  ServerSelector::ALL(),
                                                  network);

        network.reset(new SharedNetwork6("two"));
        network->setId(2);
        network->setModificationTime(getTimestamp("dhcp6_shared_network"));
        mgr.getPool()->createUpdateSharedNetwork6(BackendSelector::UNSPEC(),
                                                  ServerSelector::ALL(),
                                                  network);

        // Insert subnets into the database.
        Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 64, 1, 2, 3, 4, SubnetID(1)));
        subnet->setAllocatorType("random");
        subnet->setPdAllocatorType("random");
        subnet->setModificationTime(getTimestamp("dhcp6_subnet"));
        subnet->setSharedNetworkName("one");
        mgr.getPool()->createUpdateSubnet6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                           subnet);

        subnet.reset(new Subnet6(IOAddress("2001:db8:2::"), 64, 1, 2, 3, 4, SubnetID(2)));
        subnet->setModificationTime(getTimestamp("dhcp6_subnet"));
        mgr.getPool()->createUpdateSubnet6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                           subnet);

        // Insert client classes into the database.
        auto expression = boost::make_shared<Expression>();
        ClientClassDefPtr client_class = boost::make_shared<ClientClassDef>("first-class", expression);
        client_class->setTest("substring(option[1].hex, 0, 8) == 'my-value'");
        client_class->setId(1);
        client_class->setModificationTime(getTimestamp("dhcp6_client_class"));

        // Add an option to the class.
        OptionPtr option = Option::create(Option::V6, D6O_BOOTFILE_URL);
        OptionDescriptorPtr desc = OptionDescriptor::create(option, true,
                                                            false,
                                                            "client.boot.url");
        desc->space_name_ = DHCP6_OPTION_SPACE;
        desc->setModificationTime(getTimestamp("dhcp6_client_class"));
        client_class->getCfgOption()->add(*desc, desc->space_name_);

        mgr.getPool()->createUpdateClientClass6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                                client_class, "");

        client_class = boost::make_shared<ClientClassDef>("second-class", expression);
        client_class->setId(2);
        client_class->setModificationTime(getTimestamp("dhcp6_client_class"));
        mgr.getPool()->createUpdateClientClass6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                                client_class, "");
    }

    /// @brief Deletes specified global parameter from the configuration
    /// backend and generates audit entry.
    ///
    /// Note that the current Kea implementation does not track database
    /// identifiers of the global parameters. Therefore, the identifier to
    /// be used to create the audit entry for the deleted parameter must
    /// be explicitly specified.
    ///
    /// @param parameter_name Parameter name.
    /// @param id Parameter id.
    void remoteDeleteGlobalParameter(const std::string& parameter_name,
                                     const uint64_t id) {
        auto& mgr = ConfigBackendDHCPv6Mgr::instance();
        mgr.getPool()->deleteGlobalParameter6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                             parameter_name);
        addDeleteAuditEntry("dhcp6_global_parameter", id);
    }

    /// @brief Deletes specified option definition from the configuration
    /// backend and generates audit entry.
    ///
    /// @param code Option code.
    /// @param space Option space.
    void remoteDeleteOptionDef(const uint16_t code, const std::string& space) {
        auto& mgr = ConfigBackendDHCPv6Mgr::instance();

        auto option_def = mgr.getPool()->getOptionDef6(BackendSelector::UNSPEC(),
                                                       ServerSelector::ALL(),
                                                       code, space);

        if (option_def) {
            mgr.getPool()->deleteOptionDef6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                            code, space);
            addDeleteAuditEntry("dhcp6_option_def", option_def->getId());
        }
    }

    /// @brief Deletes specified global option from the configuration backend
    /// and generates audit entry.
    ///
    /// @param code Option code.
    /// @param space Option space.
    void remoteDeleteOption(const uint16_t code, const std::string& space) {
        auto& mgr = ConfigBackendDHCPv6Mgr::instance();

        auto option = mgr.getPool()->getOption6(BackendSelector::UNSPEC(),
                                                ServerSelector::ALL(),
                                                code, space);

        if (option) {
            mgr.getPool()->deleteOptionDef6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                            code, space);
            addDeleteAuditEntry("dhcp6_option_def", option->getId());
        }
    }

    /// @brief Deletes specified shared network from the configuration backend
    /// and generates audit entry.
    ///
    /// @param name Name of the shared network to be deleted.
    void remoteDeleteSharedNetwork(const std::string& name) {
        auto& mgr = ConfigBackendDHCPv6Mgr::instance();

        auto network = mgr.getPool()->getSharedNetwork6(BackendSelector::UNSPEC(),
                                                        ServerSelector::ALL(),
                                                        name);

        if (network) {
            mgr.getPool()->deleteSharedNetwork6(BackendSelector::UNSPEC(),
                                                ServerSelector::ALL(),
                                                name);
            addDeleteAuditEntry("dhcp6_shared_network", network->getId());
        }
    }

    /// @brief Deletes specified subnet from the configuration backend and
    /// generates audit entry.
    void remoteDeleteSubnet(const SubnetID& id) {
        auto& mgr = ConfigBackendDHCPv6Mgr::instance();

        mgr.getPool()->deleteSubnet6(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                     id);
        addDeleteAuditEntry("dhcp6_subnet", id);
    }

    /// @brief Deletes specified client class from the configuration backend
    /// and generates audit entry.
    ///
    /// @param name Name of the client class to be deleted.
    void remoteDeleteClientClass(const std::string& name) {
        auto& mgr = ConfigBackendDHCPv6Mgr::instance();

        auto client_class = mgr.getPool()->getClientClass6(BackendSelector::UNSPEC(),
                                                           ServerSelector::ALL(),
                                                           name);

        if (client_class) {
            mgr.getPool()->deleteClientClass6(BackendSelector::UNSPEC(),
                                              ServerSelector::ALL(),
                                              name);
            addDeleteAuditEntry("dhcp6_client_class", client_class->getId());
        }
    }

    /// @brief Tests the @c CBControlDHCPv6::databaseConfigApply method.
    ///
    /// This test inserts configuration elements of each type into the
    /// configuration database. Next, it calls the @c databaseConfigApply,
    /// which should merge each object from the database for which the
    /// CREATE or UPDATE audit entry is found. The test then verifies
    /// if the appropriate entries have been merged.
    ///
    /// @param lb_modification_time Lower bound modification time to be
    /// passed to the @c databaseConfigApply.
    void testDatabaseConfigApply(const boost::posix_time::ptime& lb_modification_time) {
        remoteStoreTestConfiguration();

        ASSERT_FALSE(audit_entries_.empty())
            << "Require at least one audit entry. The test is broken!";

        ctl_.databaseConfigApply(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                 lb_modification_time, audit_entries_);

        // The updates should have been merged into current configuration.
        auto srv_cfg = CfgMgr::instance().getCurrentCfg();

        // If there is an audit entry for global parameter and the parameter
        // modification time is later than last audit revision time it should
        // be merged.
        if (hasConfigElement("dhcp6_global_parameter") &&
            (getTimestamp("dhcp6_global_parameter") > lb_modification_time)) {
            checkConfiguredGlobal(srv_cfg, "comment", Element::create("bar"));

        } else {
            // Otherwise it shouldn't exist.
            EXPECT_FALSE(srv_cfg->getConfiguredGlobals()->get("comment"));
        }

        // If there is an audit entry for option definition and the definition
        // modification time is later than last audit revision time it should
        // be merged.
        auto found_def = srv_cfg->getCfgOptionDef()->get("isc", "one");
        if (hasConfigElement("dhcp6_option_def") &&
            getTimestamp("dhcp6_option_def") > lb_modification_time) {
            ASSERT_TRUE(found_def);
            EXPECT_EQ(101, found_def->getCode());
            EXPECT_EQ(OptionDataType::OPT_UINT16_TYPE, found_def->getType());

        } else {
            EXPECT_FALSE(found_def);
        }

        // If there is an audit entry for an option and the option
        // modification time is later than last audit revision time it should
        // be merged.
        auto options = srv_cfg->getCfgOption();
        auto found_opt = options->get(DHCP6_OPTION_SPACE, D6O_BOOTFILE_URL);
        if (hasConfigElement("dhcp6_options") &&
            (getTimestamp("dhcp6_options") > lb_modification_time)) {
            ASSERT_TRUE(found_opt.option_);
            EXPECT_EQ("some.bootfile", found_opt.option_->toString());

        } else {
            EXPECT_FALSE(found_opt.option_);
        }

        // If there is an audit entry for a shared network and the network
        // modification time is later than last audit revision time it should
        // be merged.
        auto networks = srv_cfg->getCfgSharedNetworks6();
        auto found_network = networks->getByName("one");
        if (hasConfigElement("dhcp6_shared_network") &&
            (getTimestamp("dhcp6_shared_network") > lb_modification_time)) {
            ASSERT_TRUE(found_network);
            EXPECT_TRUE(found_network->hasFetchGlobalsFn());

        } else {
            EXPECT_FALSE(found_network);
        }

        // If there is an audit entry for a subnet and the subnet modification
        // time is later than last audit revision time it should be merged.
        auto subnets = srv_cfg->getCfgSubnets6();
        auto found_subnet = subnets->getBySubnetId(1);
        if (hasConfigElement("dhcp6_subnet") &&
            (getTimestamp("dhcp6_subnet") > lb_modification_time)) {
            ASSERT_TRUE(found_subnet);
            EXPECT_TRUE(boost::dynamic_pointer_cast<RandomAllocator>
                        (found_subnet->getAllocator(Lease::TYPE_NA)));
            EXPECT_TRUE(boost::dynamic_pointer_cast<RandomAllocator>
                        (found_subnet->getAllocator(Lease::TYPE_PD)));
            EXPECT_TRUE(found_subnet->hasFetchGlobalsFn());

        } else {
            EXPECT_FALSE(found_subnet);
        }

        auto client_classes = srv_cfg->getClientClassDictionary();
        auto found_class = client_classes->findClass("first-class");
        if (hasConfigElement("dhcp6_client_class") &&
            (getTimestamp("dhcp6_client_class") > lb_modification_time)) {
            ASSERT_TRUE(found_class);
            ASSERT_TRUE(found_class->getMatchExpr());
            EXPECT_GT(found_class->getMatchExpr()->size(), 0);
            EXPECT_EQ("first-class", found_class->getName());

            // Check for class option, make sure it has been "created".
            auto cfg_option_desc = found_class->getCfgOption();
            ASSERT_TRUE(cfg_option_desc);
            auto option_desc = cfg_option_desc->get(DHCP6_OPTION_SPACE, D6O_BOOTFILE_URL);
            auto option = option_desc.option_;
            ASSERT_TRUE(option);
            EXPECT_EQ(OptionBuffer(option_desc.formatted_value_.begin(),
                                   option_desc.formatted_value_.end()),
                      option->getData());
        } else {
            EXPECT_FALSE(found_class);
        }
    }

    /// @brief Tests deletion of the configuration elements by the
    /// @c CBControlDHCPv6::databaseConfigApply method.
    ///
    /// This test inserts configuration elements of each type into the
    /// configuration database and calls the @c databaseConfigApply
    /// to fetch this configuration and merge into the local server
    /// configuration.
    ///
    /// Next, the test calls the specified callback function, i.e.
    /// @c db_modifications, which deletes selected configuration
    /// elements from the database and generates appropriate audit
    /// entries. Finally, it calls the @c databaseConfigApply again
    /// to process the audit entries and checks if the appropriate
    /// configuration elements are deleted from the local configuration
    ///
    /// @param lb_modification_time Lower bound modification time to be
    /// passed to the @c databaseConfigApply.
    /// @param db_modifications Pointer to the callback function which
    /// applies test specific modifications into the database.
    void testDatabaseConfigApplyDelete(const boost::posix_time::ptime& lb_modification_time,
                                       std::function<void()> db_modifications) {
        // Store initial configuration into the database.
        remoteStoreTestConfiguration();

        // Since we pass an empty audit collection the server treats this
        // as if the server is starting up and fetches the entire
        // configuration from the database.
        ctl_.databaseConfigApply(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                 ctl_.getInitialAuditRevisionTime(),
                                 AuditEntryCollection());
        // Commit the configuration so as it is moved from the staging
        // to current.
        CfgMgr::instance().commit();

        // Run user defined callback which should delete selected configuration
        // elements from the configuration backend. The appropriate DELETE
        // audit entries should now be stored in the audit_entries_ collection.
        if (db_modifications) {
            db_modifications();
        }

        // Process the DELETE audit entries.
        ctl_.databaseConfigApply(BackendSelector::UNSPEC(), ServerSelector::ALL(),
                                 lb_modification_time, audit_entries_);

        // All changes should have been applied in the current configuration.
        auto srv_cfg = CfgMgr::instance().getCurrentCfg();

        {
            SCOPED_TRACE("global parameters");
            // One of the global parameters should still be there.
            EXPECT_TRUE(srv_cfg->getConfiguredGlobals()->get("data-directory"));
            if (deleteConfigElement("dhcp6_global_parameter", 1)) {
                EXPECT_FALSE(srv_cfg->getConfiguredGlobals()->get("comment"));

            } else {
                EXPECT_TRUE(srv_cfg->getConfiguredGlobals()->get("comment"));
            }
        }

        {
            SCOPED_TRACE("option definitions");
            // One of the option definitions should still be there.
            EXPECT_TRUE(srv_cfg->getCfgOptionDef()->get("isc", "two"));
            auto found_def = srv_cfg->getCfgOptionDef()->get("isc", "one");
            if (deleteConfigElement("dhcp6_option_def", 1)) {
                EXPECT_FALSE(found_def);

            } else {
                EXPECT_TRUE(found_def);
            }
        }

        {
            SCOPED_TRACE("global options");
            // One of the options should still be there.
            EXPECT_TRUE(srv_cfg->getCfgOption()->get(DHCP6_OPTION_SPACE,
                                                     D6O_AFTR_NAME).option_);
            auto found_opt = srv_cfg->getCfgOption()->get(DHCP6_OPTION_SPACE,
                                                          D6O_AFTR_NAME);
            if (deleteConfigElement("dhcp6_options", 1)) {
                EXPECT_FALSE(found_opt.option_);

            } else {
                EXPECT_TRUE(found_opt.option_);
            }
        }

        {
            SCOPED_TRACE("shared networks");
            // One of the shared networks should still be there.
            EXPECT_TRUE(srv_cfg->getCfgSharedNetworks6()->getByName("two"));
            auto found_network = srv_cfg->getCfgSharedNetworks6()->getByName("one");
            if (deleteConfigElement("dhcp6_shared_network", 1)) {
                EXPECT_FALSE(found_network);

            } else {
                EXPECT_TRUE(found_network);
            }
        }

        {
            SCOPED_TRACE("subnets");
            // One of the subnets should still be there.
            EXPECT_TRUE(srv_cfg->getCfgSubnets6()->getBySubnetId(2));
            auto found_subnet = srv_cfg->getCfgSubnets6()->getBySubnetId(1);
            if (deleteConfigElement("dhcp6_subnet", 1)) {
                EXPECT_FALSE(found_subnet);
                // If the subnet has been deleted, make sure that
                // it was detached from the shared network it belonged
                // to, if the shared network still exists.
                auto found_network = srv_cfg->getCfgSharedNetworks6()->getByName("one");
                if (found_network) {
                    EXPECT_TRUE(found_network->getAllSubnets()->empty());
                }

            } else {
                EXPECT_TRUE(found_subnet);
            }
        }
    }

    /// @brief Instance of the @c CBControlDHCPv6 used for testing.
    TestCBControlDHCPv6 ctl_;
};


// This test verifies that the configuration updates for all object
// types are merged into the current configuration.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyAll) {

    addCreateAuditEntry("dhcp6_global_parameter", 1);
    addCreateAuditEntry("dhcp6_global_parameter", 2);
    addCreateAuditEntry("dhcp6_option_def", 1);
    addCreateAuditEntry("dhcp6_option_def", 2);
    addCreateAuditEntry("dhcp6_options", 1);
    addCreateAuditEntry("dhcp6_options", 2);
    addCreateAuditEntry("dhcp6_shared_network", 1);
    addCreateAuditEntry("dhcp6_shared_network", 2);
    addCreateAuditEntry("dhcp6_subnet", 1);
    addCreateAuditEntry("dhcp6_subnet", 2);
    addCreateAuditEntry("dhcp6_client_class", 1);
    addCreateAuditEntry("dhcp6_client_class", 2);

    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that multiple configuration elements are
// deleted from the local configuration as a result of being
// deleted from the database.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyDeleteAll) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteGlobalParameter("comment", 1);
        remoteDeleteOptionDef(101, "isc");
        remoteDeleteOption(D6O_BOOTFILE_URL, DHCP6_OPTION_SPACE);
        remoteDeleteSharedNetwork("one");
        remoteDeleteSubnet(SubnetID(1));
    });
}

// This test verifies that an attempt to delete non-existing
// configuration element does not cause an error.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyDeleteNonExisting) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        // Add several audit entries instructing to delete the
        // non-existing configuration elements. The ids are set
        // to 3, but the only existing elements have ids of 1
        // and 2.
        addDeleteAuditEntry("dhcp6_global_parameter", 3);
        addDeleteAuditEntry("dhcp6_option_def", 3);
        addDeleteAuditEntry("dhcp6_options", 3);
        addDeleteAuditEntry("dhcp6_shared_network", 3);
        addDeleteAuditEntry("dhcp6_subnet", 3);
    });
}

// This test verifies that only a global parameter is merged into
// the current configuration.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyGlobal) {
    addCreateAuditEntry("dhcp6_global_parameter", 1);
    addCreateAuditEntry("dhcp6_global_parameter", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the global parameter is deleted from
// the local configuration as a result of being deleted from the
// database.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyDeleteGlobal) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteGlobalParameter("comment", 1);
    });
}

// This test verifies that global parameter is not fetched from the
// database when the modification time is earlier than the last
// fetched audit entry.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyGlobalNotFetched) {
    addCreateAuditEntry("dhcp6_global_parameter", 1);
    addCreateAuditEntry("dhcp6_global_parameter", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only an option definition is merged into
// the current configuration.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyOptionDef) {
    addCreateAuditEntry("dhcp6_option_def", 1);
    addCreateAuditEntry("dhcp6_option_def", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the option definition is deleted from
// the local configuration as a result of being deleted from the
// database.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyDeleteOptionDef) {
    addDeleteAuditEntry("dhcp6_option_def", 1);
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteOptionDef(101, "isc");
    });
}

// This test verifies that option definition is not fetched from the
// database when the modification time is earlier than the last
// fetched audit entry.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyOptionDefNotFetched) {
    addCreateAuditEntry("dhcp6_option_def", 1);
    addCreateAuditEntry("dhcp6_option_def", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only a DHCPv6 option is merged into the
// current configuration.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyOption) {
    addCreateAuditEntry("dhcp6_options", 1);
    addCreateAuditEntry("dhcp6_options", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the global option is deleted from
// the local configuration as a result of being deleted from the
// database.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyDeleteOption) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteOption(D6O_BOOTFILE_URL, DHCP6_OPTION_SPACE);
    });
}

// This test verifies that DHCPv6 option is not fetched from the
// database when the modification time is earlier than the last
// fetched audit entry.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyOptionNotFetched) {
    addCreateAuditEntry("dhcp6_options", 1);
    addCreateAuditEntry("dhcp6_options", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only a shared network is merged into the
// current configuration.
TEST_F(CBControlDHCPv6Test, databaseConfigApplySharedNetwork) {
    addCreateAuditEntry("dhcp6_shared_network", 1);
    addCreateAuditEntry("dhcp6_shared_network", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the shared network is deleted from
// the local configuration as a result of being deleted from the
// database.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyDeleteSharedNetwork) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteSharedNetwork("one");
    });
}

// This test verifies that shared network is not fetched from the
// database when the modification time is earlier than the last
// fetched audit entry.
TEST_F(CBControlDHCPv6Test, databaseConfigApplySharedNetworkNotFetched) {
    addCreateAuditEntry("dhcp6_shared_network", 1);
    addCreateAuditEntry("dhcp6_shared_network", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only a subnet is merged into the current
// configuration.
TEST_F(CBControlDHCPv6Test, databaseConfigApplySubnet) {
    addCreateAuditEntry("dhcp6_shared_network", 1);
    addCreateAuditEntry("dhcp6_shared_network", 2);
    addCreateAuditEntry("dhcp6_subnet", 1);
    addCreateAuditEntry("dhcp6_subnet", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that the subnet is deleted from the local
// configuration as a result of being deleted from the database.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyDeleteSubnet) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteSubnet(SubnetID(1));
    });
}

// This test verifies that subnet is not fetched from the database
// when the modification time is earlier than the last fetched audit
// entry.
TEST_F(CBControlDHCPv6Test, databaseConfigApplySubnetNotFetched) {
    addCreateAuditEntry("dhcp6_subnet", 1);
    addCreateAuditEntry("dhcp6_subnet", 2);
    testDatabaseConfigApply(getTimestamp(-3));
}

// This test verifies that only client classes are merged into the current
// configuration.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyClientClasses) {
    addCreateAuditEntry("dhcp6_client_class", 1);
    addCreateAuditEntry("dhcp6_client_class", 2);
    testDatabaseConfigApply(getTimestamp(-5));
}

// This test verifies that a client class is deleted from the local
// configuration as a result of being deleted from the database.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyDeleteClientClass) {
    testDatabaseConfigApplyDelete(getTimestamp(-5), [this]() {
        remoteDeleteClientClass("first-class");
    });
}

// This test verifies that the configuration update calls the hook.
TEST_F(CBControlDHCPv6Test, databaseConfigApplyHook) {

    // Initialize Hooks Manager.
    HooksManager::loadLibraries(HookLibsCollection());

    // Install cb6_updated.
    EXPECT_NO_THROW(HooksManager::preCalloutsLibraryHandle().registerCallout(
        "cb6_updated", cb6_updated_callout));

    // Create audit entries.
    addCreateAuditEntry("dhcp6_global_parameter", 1);
    addCreateAuditEntry("dhcp6_global_parameter", 2);
    addCreateAuditEntry("dhcp6_option_def", 1);
    addCreateAuditEntry("dhcp6_option_def", 2);
    addCreateAuditEntry("dhcp6_options", 1);
    addCreateAuditEntry("dhcp6_options", 2);
    addCreateAuditEntry("dhcp6_shared_network", 1);
    addCreateAuditEntry("dhcp6_shared_network", 2);
    addCreateAuditEntry("dhcp6_subnet", 1);
    addCreateAuditEntry("dhcp6_subnet", 2);

    // Run the test.
    testDatabaseConfigApply(getTimestamp(-5));

    // Checks the callout.
    EXPECT_EQ("cb6_updated", callback_name_);
    ASSERT_TRUE(callback_audit_entries_);
    EXPECT_TRUE(audit_entries_ == *callback_audit_entries_);
}

// This test verifies that it is possible to set ip-reservations-unique
// parameter via configuration backend and that it is successful when
// host database backend accepts the new setting.
TEST_F(CBControlDHCPv6Test, ipReservationsNonUniqueAccepted) {
    // Create host data source which accepts setting non-unique IP
    // reservations.
    MemHostDataSourcePtr hds(new MemHostDataSource());
    auto testFactory = [hds](const DatabaseConnection::ParameterMap&) {
        return (hds);
    };
    HostDataSourceFactory::registerFactory("test", testFactory);
    HostMgr::addBackend("type=test");

    // Insert ip-reservations-unique value set to false into the database.
    auto& mgr = ConfigBackendDHCPv6Mgr::instance();
    StampedValuePtr global_parameter = StampedValue::create("ip-reservations-unique",
                                                            Element::create(false));
    ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter6(BackendSelector::UNSPEC(),
                                                                ServerSelector::ALL(),
                                                                global_parameter));
    // Adding audit entry simulates the case when the server is already configured
    // and we're adding incremental changes. These changes should be applied to
    // the current configuration.
    addCreateAuditEntry("dhcp6_global_parameter", 1);

    // Apply the configuration.
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));
    // The new setting should be visible in both CfgDbAccess and HostMgr.
    EXPECT_FALSE(CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique());
    EXPECT_FALSE(HostMgr::instance().getIPReservationsUnique());
}

// This test verifies that the new setting of ip-reservations-unique is not
// accepted when one of the host database backends does not support it.
TEST_F(CBControlDHCPv6Test, ipReservationsNonUniqueRefused) {
    // Create host data source which does not accept setting IP reservations
    // non-unique setting.
    NonUniqueHostDataSourcePtr hds(new NonUniqueHostDataSource());
    auto testFactory = [hds](const DatabaseConnection::ParameterMap&) {
        return (hds);
    };
    HostDataSourceFactory::registerFactory("test", testFactory);
    HostMgr::addBackend("type=test");

    // Insert ip-reservations-unique value set to false into the database.
    auto& mgr = ConfigBackendDHCPv6Mgr::instance();
    StampedValuePtr global_parameter = StampedValue::create("ip-reservations-unique",
                                                            Element::create(false));
    ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter6(BackendSelector::UNSPEC(),
                                                                ServerSelector::ALL(),
                                                                global_parameter));
    // Adding audit entry simulates the case when the server is already configured
    // and we're adding incremental changes. These changes should be applied to
    // the current configuration.
    addCreateAuditEntry("dhcp6_global_parameter", 1);

    // Apply the configuration.
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));
    // The default setting should be applied, because the backend refused to
    // set it to false.
    EXPECT_TRUE(CfgMgr::instance().getCurrentCfg()->getCfgDbAccess()->getIPReservationsUnique());
    EXPECT_TRUE(HostMgr::instance().getIPReservationsUnique());
}

// This test verifies that the allocator type is inherited from the global to
// shared network to subnet level.
TEST_F(CBControlDHCPv6Test, allocatorInheritance) {
    remoteStoreTestConfiguration();

    // Set non-default global allocator.
    StampedValuePtr global_parameter = StampedValue::create("allocator",
                                                            Element::create("random"));
    auto& mgr = ConfigBackendDHCPv6Mgr::instance();
    ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter6(BackendSelector::UNSPEC(),
                                                                ServerSelector::ALL(),
                                                                global_parameter));
    addCreateAuditEntry("dhcp6_global_parameter", 1);
    addCreateAuditEntry("dhcp6_shared_network", 1);
    addCreateAuditEntry("dhcp6_subnet", 2);

    // Merge the configuration including the allocator setting into the current
    // configuration.
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet that has no allocator specification. The global allocator should
    // be used for this subnet.
    auto srv_cfg = CfgMgr::instance().getCurrentCfg();
    auto subnet = srv_cfg->getCfgSubnets6()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    auto allocator = subnet->getAllocator(Lease::TYPE_NA);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("random", allocator->getType());

    // Update the shared network but use a different allocator type for it.
    auto updated_network = boost::make_shared<SharedNetwork6>("one");
    updated_network->setId(1);
    updated_network->setModificationTime(getTimestamp("dhcp6_shared_network"));
    updated_network->setAllocatorType("iterative");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSharedNetwork6(BackendSelector::UNSPEC(),
                                                              ServerSelector::ALL(),
                                                              updated_network));

    // Include our subnet in this shared network.
    auto updated_subnet = boost::make_shared<Subnet6>(IOAddress("2001:db8:2::"), 26, 1, 2, 3, 4,
                                                      SubnetID(2));
    updated_subnet->setSharedNetworkName("one");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSubnet6(BackendSelector::UNSPEC(),
                                                       ServerSelector::ALL(),
                                                       updated_subnet));
    // Merge the updated configuration.
    addCreateAuditEntry("dhcp6_shared_network", 1);
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet again. Expect that the subnet uses the shared network-level allocator.
    subnet = srv_cfg->getCfgSubnets6()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    allocator = subnet->getAllocator(Lease::TYPE_NA);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("iterative", allocator->getType());

    // Override the allocator at the subnet level.
    updated_subnet = boost::make_shared<Subnet6>(IOAddress("2001:db8:2::"), 26, 1, 2, 3, 4,
                                                 SubnetID(2));
    updated_subnet->setSharedNetworkName("one");
    updated_subnet->setModificationTime(getTimestamp("dhcp6_subnet"));
    updated_subnet->setAllocatorType("random");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSubnet6(BackendSelector::UNSPEC(),
                                                       ServerSelector::ALL(),
                                                       updated_subnet));

    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet again and expect the subnet-level allocator.
    subnet = srv_cfg->getCfgSubnets6()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    allocator = subnet->getAllocator(Lease::TYPE_NA);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("random", allocator->getType());
}

// This test verifies that the prefix delegation allocator type is inherited from the
// global to shared network to subnet level.
TEST_F(CBControlDHCPv6Test, pdAllocatorInheritance) {
    remoteStoreTestConfiguration();

    // Set non-default global allocator.
    StampedValuePtr global_parameter = StampedValue::create("pd-allocator",
                                                            Element::create("flq"));
    auto& mgr = ConfigBackendDHCPv6Mgr::instance();
    ASSERT_NO_THROW(mgr.getPool()->createUpdateGlobalParameter6(BackendSelector::UNSPEC(),
                                                                ServerSelector::ALL(),
                                                                global_parameter));
    addCreateAuditEntry("dhcp6_global_parameter", 1);
    addCreateAuditEntry("dhcp6_shared_network", 1);
    addCreateAuditEntry("dhcp6_subnet", 2);

    // Merge the configuration including the allocator setting into the current
    // configuration.
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet that has no allocator specification. The global allocator should
    // be used for this subnet.
    auto srv_cfg = CfgMgr::instance().getCurrentCfg();
    auto subnet = srv_cfg->getCfgSubnets6()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    auto allocator = subnet->getAllocator(Lease::TYPE_PD);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("flq", allocator->getType());

    // Update the shared network but use a different allocator type for it.
    auto updated_network = boost::make_shared<SharedNetwork6>("one");
    updated_network->setId(1);
    updated_network->setModificationTime(getTimestamp("dhcp6_shared_network"));
    updated_network->setPdAllocatorType("iterative");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSharedNetwork6(BackendSelector::UNSPEC(),
                                                              ServerSelector::ALL(),
                                                              updated_network));

    // Include our subnet in this shared network.
    auto updated_subnet = boost::make_shared<Subnet6>(IOAddress("2001:db8:2::"), 26, 1, 2, 3, 4,
                                                      SubnetID(2));
    updated_subnet->setSharedNetworkName("one");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSubnet6(BackendSelector::UNSPEC(),
                                                       ServerSelector::ALL(),
                                                       updated_subnet));
    // Merge the updated configuration.
    addCreateAuditEntry("dhcp6_shared_network", 1);
    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet again. Expect that the subnet uses the shared network-level allocator.
    subnet = srv_cfg->getCfgSubnets6()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    allocator = subnet->getAllocator(Lease::TYPE_PD);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("iterative", allocator->getType());

    // Override the allocator at the subnet level.
    updated_subnet = boost::make_shared<Subnet6>(IOAddress("2001:db8:2::"), 26, 1, 2, 3, 4,
                                                 SubnetID(2));
    updated_subnet->setSharedNetworkName("one");
    updated_subnet->setModificationTime(getTimestamp("dhcp6_subnet"));
    updated_subnet->setPdAllocatorType("random");
    ASSERT_NO_THROW(mgr.getPool()->createUpdateSubnet6(BackendSelector::UNSPEC(),
                                                       ServerSelector::ALL(),
                                                       updated_subnet));

    ASSERT_NO_THROW(ctl_.databaseConfigApply(BackendSelector::UNSPEC(),
                                             ServerSelector::ALL(),
                                             getTimestamp(-5),
                                             audit_entries_));

    // Get the subnet again and expect the subnet-level allocator.
    subnet = srv_cfg->getCfgSubnets6()->getBySubnetId(SubnetID(2));
    ASSERT_TRUE(subnet);
    allocator = subnet->getAllocator(Lease::TYPE_PD);
    ASSERT_TRUE(allocator);
    EXPECT_EQ("random", allocator->getType());
}


}