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
// Copyright (C) 2015-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 <dhcpsrv/testutils/test_utils.h>
#include <exceptions/exceptions.h>
#include <dhcpsrv/host.h>
#include <mysql_host_data_source.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <dhcpsrv/testutils/generic_host_data_source_unittest.h>
#include <dhcpsrv/testutils/host_data_source_utils.h>
#include <dhcpsrv/host_mgr.h>
#include <dhcpsrv/host_data_source_factory.h>
#include <mysql/mysql_connection.h>
#include <mysql/testutils/mysql_schema.h>
#include <testutils/multi_threading_utils.h>
#include <util/multi_threading_mgr.h>

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

#include <algorithm><--- 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 <sstream><--- 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.
#include <utility><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

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

namespace {

class MySqlHostDataSourceTest : public GenericHostDataSourceTest {
public:
    /// @brief Clears the database and opens connection to it.
    void initializeTest() {
        // Ensure we have the proper schema with no transient data.
        createMySQLSchema();

        // Connect to the database
        try {
            HostMgr::create();
            HostMgr::addBackend(validMySQLConnectionString());
        } catch (...) {
            std::cerr << "*** ERROR: unable to open database. The test\n"
                         "*** environment is broken and must be fixed before\n"
                         "*** the MySQL tests will run correctly.\n"
                         "*** The reason for the problem is described in the\n"
                         "*** accompanying exception output.\n";
            throw;
        }

        hdsptr_ = HostMgr::instance().getHostDataSource();
        hdsptr_->setIPReservationsUnique(true);

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

    /// @brief Destroys the HDS and the schema.
    void destroyTest() {
        try {
            hdsptr_->rollback();
        } catch (...) {
            // Rollback may fail if backend is in read only mode. That's ok.
        }
        HostMgr::delAllBackends();
        hdsptr_.reset();
        // If data wipe enabled, delete transient data otherwise destroy the schema
        destroyMySQLSchema();
    }

    /// @brief Constructor
    ///
    /// Deletes everything from the database and opens it.
    MySqlHostDataSourceTest() {
        initializeTest();
    }

    /// @brief Destructor
    ///
    /// Rolls back all pending transactions.  The deletion of hdsptr_ will close
    /// the database.  Then reopen it and delete everything created by the test.
    virtual ~MySqlHostDataSourceTest() {
        destroyTest();
    }

    /// @brief Reopen the database
    ///
    /// Closes the database and re-open it.  Anything committed should be
    /// visible.
    ///
    /// Parameter is ignored for MySQL backend as the v4 and v6 hosts share
    /// the same database.
    void reopen(Universe) {
        HostMgr::create();
        HostMgr::addBackend(validMySQLConnectionString());
        hdsptr_ = HostMgr::instance().getHostDataSource();
    }

    /// @brief returns number of rows in a table
    ///
    /// Note: This method uses its own connection. It will not work if your test
    /// uses transactions.
    ///
    /// @param name of the table
    /// @return number of rows currently present in the table
    int countRowsInTable(const std::string& table) {
        string query = "SELECT * FROM " + table;

        DatabaseConnection::ParameterMap params;
        params["name"] = "keatest";
        params["user"] = "keatest";
        params["password"] = "keatest";

        MySqlConnection conn(params);
        conn.openDatabase();

        int status = MysqlQuery(conn.mysql_, query.c_str());
        if (status != 0) {
            isc_throw(DbOperationError, "Query failed: " << mysql_error(conn.mysql_));
        }

        MYSQL_RES * res = mysql_store_result(conn.mysql_);
        int numrows = static_cast<int>(mysql_num_rows(res));
        mysql_free_result(res);

        return (numrows);
    }

    /// @brief Returns number of IPv4 options currently stored in DB.
    virtual int countDBOptions4() {
        return (countRowsInTable("dhcp4_options"));
    }

    /// @brief Returns number of IPv6 options currently stored in DB.
    virtual int countDBOptions6() {
        return (countRowsInTable("dhcp6_options"));
    }

    /// @brief Returns number of IPv6 reservations currently stored in DB.
    virtual int countDBReservations6() {
        return (countRowsInTable("ipv6_reservations"));
    }

    /// @brief Initializer.
    MySqlHostDataSourceInit init_;
};

/// @brief Check that database can be opened
///
/// This test checks if the MySqlHostDataSource can be instantiated.  This happens
/// only if the database can be opened.  Note that this is not part of the
/// MySqlHostMgr test fixture set.  This test checks that the database can be
/// opened: the fixtures assume that and check basic operations.
TEST(MySqlHostDataSource, OpenDatabase) {<--- syntax error
    MySqlHostDataSourceInit init;
    // Schema needs to be created for the test to work.
    destroyMySQLSchema();
    createMySQLSchema();

    // Enter test mode to avoid ensureSchemaVersion to invoke kea-admin.
    DatabaseConnection::EnterTest et;

    // Check that host manager opens the database correctly and tidy up.  If it
    // fails, print the error message.
    try {
        HostMgr::create();
        EXPECT_NO_THROW(HostMgr::addBackend(validMySQLConnectionString()));
        HostMgr::delBackend("mysql");
    } catch (const isc::Exception& ex) {
        FAIL() << "*** ERROR: unable to open database, reason:\n"
               << "    " << ex.what() << "\n"
               << "*** The test environment is broken and must be fixed\n"
               << "*** before the MySQL tests will run correctly.\n";
    }

    // Check that host manager opens the database correctly with a longer
    // timeout.  If it fails, print the error message.
    try {
        string connection_string = validMySQLConnectionString() + string(" ") +
                                   string(VALID_TIMEOUT);
        HostMgr::create();
        EXPECT_NO_THROW(HostMgr::addBackend(connection_string));
        HostMgr::delBackend("mysql");
    } catch (const isc::Exception& ex) {
        FAIL() << "*** ERROR: unable to open database, reason:\n"
               << "    " << ex.what() << "\n"
               << "*** The test environment is broken and must be fixed\n"
               << "*** before the MySQL tests will run correctly.\n";
    }

    // Check that attempting to get an instance of the host data source when
    // none is set returns empty pointer.
    EXPECT_FALSE(HostMgr::instance().getHostDataSource());

    // Check that wrong specification of backend throws an exception.
    // (This is really a check on HostDataSourceFactory, but is convenient to
    // perform here.)
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        NULL, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
        InvalidParameter);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        INVALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
        InvalidType);

    // Check that invalid login data causes an exception.
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
        DbOpenError);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
        DbOpenError);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
        DbOpenError);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
        DbOpenError);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD, INVALID_TIMEOUT_1)),
        DbInvalidTimeout);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD, INVALID_TIMEOUT_2)),
        DbInvalidTimeout);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD,
        VALID_TIMEOUT, INVALID_READONLY_DB)), DbInvalidReadOnly);

    // Check for missing parameters
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
        NoDatabaseName);

    // Tidy up after the test
    destroyMySQLSchema();
}

/// @brief Check that database can be opened with Multi-Threading
///
/// This test checks if the MySqlHostDataSource can be instantiated.  This happens
/// only if the database can be opened.  Note that this is not part of the
/// MySqlHostMgr test fixture set.  This test checks that the database can be
/// opened: the fixtures assume that and check basic operations.
TEST(MySqlHostDataSource, OpenDatabaseMultiThreading) {
    MySqlHostDataSourceInit init;
    // Enable Multi-Threading.
    MultiThreadingTest mt(true);

    // Schema needs to be created for the test to work.
    destroyMySQLSchema();
    createMySQLSchema();

    // Enter test mode to avoid ensureSchemaVersion to invoke kea-admin.
    DatabaseConnection::EnterTest et;

    // Check that host manager opens the database correctly and tidy up.  If it
    // fails, print the error message.
    try {
        HostMgr::create();
        EXPECT_NO_THROW(HostMgr::addBackend(validMySQLConnectionString()));
        HostMgr::delBackend("mysql");
    } catch (const isc::Exception& ex) {
        FAIL() << "*** ERROR: unable to open database, reason:\n"
               << "    " << ex.what() << "\n"
               << "*** The test environment is broken and must be fixed\n"
               << "*** before the MySQL tests will run correctly.\n";
    }

    // Check that host manager opens the database correctly with a longer
    // timeout.  If it fails, print the error message.
    try {
        string connection_string = validMySQLConnectionString() + string(" ") +
                                   string(VALID_TIMEOUT);
        HostMgr::create();
        EXPECT_NO_THROW(HostMgr::addBackend(connection_string));
        HostMgr::delBackend("mysql");
    } catch (const isc::Exception& ex) {
        FAIL() << "*** ERROR: unable to open database, reason:\n"
               << "    " << ex.what() << "\n"
               << "*** The test environment is broken and must be fixed\n"
               << "*** before the MySQL tests will run correctly.\n";
    }

    // Check that attempting to get an instance of the host data source when
    // none is set returns empty pointer.
    EXPECT_FALSE(HostMgr::instance().getHostDataSource());

    // Check that wrong specification of backend throws an exception.
    // (This is really a check on HostDataSourceFactory, but is convenient to
    // perform here.)
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        NULL, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
        InvalidParameter);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        INVALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
        InvalidType);

    // Check that invalid login data causes an exception.
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, INVALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD)),
        DbOpenError);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
        DbOpenError);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
        DbOpenError);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, INVALID_PASSWORD)),
        DbOpenError);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD, INVALID_TIMEOUT_1)),
        DbInvalidTimeout);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD, INVALID_TIMEOUT_2)),
        DbInvalidTimeout);
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST, VALID_USER, VALID_PASSWORD,
        VALID_TIMEOUT, INVALID_READONLY_DB)), DbInvalidReadOnly);

    // Check for missing parameters
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, NULL, VALID_HOST, INVALID_USER, VALID_PASSWORD)),
        NoDatabaseName);

    // Tidy up after the test
    destroyMySQLSchema();
}

/// @brief Flag used to detect calls to db_lost_callback function
bool callback_called = false;

/// @brief Callback function used in open database testing
bool db_lost_callback(ReconnectCtlPtr /* db_conn_retry */) {
    return (callback_called = true);
}

/// @brief Make sure open failures do NOT invoke db lost callback
/// The db lost callback should only be invoked after successfully
/// opening the DB and then subsequently losing it. Failing to
/// open should be handled directly by the application layer.
/// There is simply no good way to break the connection in a
/// unit test environment.  So testing the callback invocation
/// in a unit test is next to impossible. That has to be done
/// as a system test.
TEST(MySqlHostDataSource, NoCallbackOnOpenFail) {
    MySqlHostDataSourceInit init;
    // Schema needs to be created for the test to work.
    destroyMySQLSchema();
    createMySQLSchema();

    callback_called = false;
    DatabaseConnection::db_lost_callback_ = db_lost_callback;
    HostMgr::create();
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
                 DbOpenError);

    EXPECT_FALSE(callback_called);
    destroyMySQLSchema();
}

/// @brief Make sure open failures do NOT invoke db lost callback
/// The db lost callback should only be invoked after successfully
/// opening the DB and then subsequently losing it. Failing to
/// open should be handled directly by the application layer.
/// There is simply no good way to break the connection in a
/// unit test environment.  So testing the callback invocation
/// in a unit test is next to impossible. That has to be done
/// as a system test.
TEST(MySqlHostDataSource, NoCallbackOnOpenFailMultiThreading) {
    MySqlHostDataSourceInit init;
    // Enable Multi-Threading.
    MultiThreadingTest mt(true);

    // Schema needs to be created for the test to work.
    destroyMySQLSchema();
    createMySQLSchema();

    callback_called = false;
    DatabaseConnection::db_lost_callback_ = db_lost_callback;
    HostMgr::create();
    EXPECT_THROW(HostMgr::addBackend(connectionString(
        MYSQL_VALID_TYPE, VALID_NAME, INVALID_HOST, VALID_USER, VALID_PASSWORD)),
                 DbOpenError);

    EXPECT_FALSE(callback_called);
    destroyMySQLSchema();
}

/// @brief Check conversion functions
///
/// The server works using cltt and valid_filetime.  In the database, the
/// information is stored as expire_time and valid-lifetime, which are
/// related by
///
/// expire_time = cltt + valid_lifetime
///
/// This test checks that the conversion is correct.  It does not check that the
/// data is entered into the database correctly, only that the MYSQL_TIME
/// structure used for the entry is correctly set up.
TEST(MySqlConnection, checkTimeConversion) {
    const time_t cltt = time(NULL);
    const uint32_t valid_lft = 86400;       // 1 day
    struct tm tm_expire;
    MYSQL_TIME mysql_expire;

    // Work out what the broken-down time will be for one day
    // after the current time.
    time_t expire_time = cltt + valid_lft;
    (void) localtime_r(&expire_time, &tm_expire);

    // Convert to the database time
    MySqlConnection::convertToDatabaseTime(cltt, valid_lft, mysql_expire);

    // Are the times the same?
    EXPECT_EQ(tm_expire.tm_year + 1900, mysql_expire.year);
    EXPECT_EQ(tm_expire.tm_mon + 1,  mysql_expire.month);
    EXPECT_EQ(tm_expire.tm_mday, mysql_expire.day);
    EXPECT_EQ(tm_expire.tm_hour, mysql_expire.hour);
    EXPECT_EQ(tm_expire.tm_min, mysql_expire.minute);
    EXPECT_EQ(tm_expire.tm_sec, mysql_expire.second);
    EXPECT_EQ(0, mysql_expire.second_part);
    EXPECT_EQ(0, mysql_expire.neg);

    // Convert back
    time_t converted_cltt = 0;
    MySqlConnection::convertFromDatabaseTime(mysql_expire, valid_lft, converted_cltt);
    EXPECT_EQ(cltt, converted_cltt);
}

/// @brief This test verifies that database backend can operate in Read-Only mode.
TEST_F(MySqlHostDataSourceTest, testReadOnlyDatabase) {
    testReadOnlyDatabase(MYSQL_VALID_TYPE);
}

/// @brief This test verifies that database backend can operate in Read-Only mode.
TEST_F(MySqlHostDataSourceTest, testReadOnlyDatabaseMultiThreading) {
    MultiThreadingTest mt(true);
    testReadOnlyDatabase(MYSQL_VALID_TYPE);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by IPv4
/// address. Host uses hw address as identifier.
TEST_F(MySqlHostDataSourceTest, basic4HWAddr) {
    testBasic4(Host::IDENT_HWADDR);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by IPv4
/// address. Host uses hw address as identifier.
TEST_F(MySqlHostDataSourceTest, basic4HWAddrMultiThreading) {
    MultiThreadingTest mt(true);
    testBasic4(Host::IDENT_HWADDR);
}

/// @brief Verifies that IPv4 host reservation with options can have the global
/// subnet id value
TEST_F(MySqlHostDataSourceTest, globalSubnetId4) {
    testGlobalSubnetId4();
}

/// @brief Verifies that IPv4 host reservation with options can have the global
/// subnet id value
TEST_F(MySqlHostDataSourceTest, globalSubnetId4MultiThreading) {
    MultiThreadingTest mt(true);
    testGlobalSubnetId4();
}

/// @brief Verifies that IPv6 host reservation with options can have the global
/// subnet id value
TEST_F(MySqlHostDataSourceTest, globalSubnetId6) {
    testGlobalSubnetId6();
}

/// @brief Verifies that IPv6 host reservation with options can have the global
/// subnet id value
TEST_F(MySqlHostDataSourceTest, globalSubnetId6MultiThreading) {
    MultiThreadingTest mt(true);
    testGlobalSubnetId6();
}

/// @brief Verifies that IPv4 host reservation with options can have a max value
/// for dhcp4_subnet id
TEST_F(MySqlHostDataSourceTest, maxSubnetId4) {
    testMaxSubnetId4();
}

/// @brief Verifies that IPv4 host reservation with options can have a max value
/// for dhcp4_subnet id
TEST_F(MySqlHostDataSourceTest, maxSubnetId4MultiThreading) {
    MultiThreadingTest mt(true);
    testMaxSubnetId4();
}

/// @brief Verifies that IPv6 host reservation with options can have a max value
/// for dhcp6_subnet id
TEST_F(MySqlHostDataSourceTest, maxSubnetId6) {
    testMaxSubnetId6();
}

/// @brief Verifies that IPv6 host reservation with options can have a max value
/// for dhcp6_subnet id
TEST_F(MySqlHostDataSourceTest, maxSubnetId6MultiThreading) {
    MultiThreadingTest mt(true);
    testMaxSubnetId6();
}

/// @brief Verifies that IPv4 host reservations in the same subnet can be retrieved
TEST_F(MySqlHostDataSourceTest, getAll4BySubnet) {
    testGetAll4();
}

/// @brief Verifies that IPv4 host reservations in the same subnet can be retrieved
TEST_F(MySqlHostDataSourceTest, getAll4BySubnetMultiThreading) {
    MultiThreadingTest mt(true);
    testGetAll4();
}

/// @brief Verifies that IPv6 host reservations in the same subnet can be retrieved
TEST_F(MySqlHostDataSourceTest, getAll6BySubnet) {
    testGetAll6();
}

/// @brief Verifies that IPv6 host reservations in the same subnet can be retrieved
TEST_F(MySqlHostDataSourceTest, getAll6BySubnetMultiThreading) {
    MultiThreadingTest mt(true);
    testGetAll6();
}

/// @brief Verifies that host reservations with the same hostname can be retrieved
TEST_F(MySqlHostDataSourceTest, getAllbyHostname) {
    testGetAllbyHostname();
}

/// @brief Verifies that host reservations with the same hostname can be retrieved
TEST_F(MySqlHostDataSourceTest, getAllbyHostnameMultiThreading) {
    MultiThreadingTest mt(true);
    testGetAllbyHostname();
}

/// @brief Verifies that IPv4 host reservations with the same hostname and in
/// the same subnet can be retrieved
TEST_F(MySqlHostDataSourceTest, getAllbyHostnameSubnet4) {
    testGetAllbyHostnameSubnet4();
}

/// @brief Verifies that IPv4 host reservations with the same hostname and in
/// the same subnet can be retrieved
TEST_F(MySqlHostDataSourceTest, getAllbyHostnameSubnet4MultiThreading) {
    MultiThreadingTest mt(true);
    testGetAllbyHostnameSubnet4();
}

/// @brief Verifies that IPv6 host reservations with the same hostname and in
/// the same subnet can be retrieved
TEST_F(MySqlHostDataSourceTest, getAllbyHostnameSubnet6) {
    testGetAllbyHostnameSubnet6();
}

/// @brief Verifies that IPv6 host reservations with the same hostname and in
/// the same subnet can be retrieved
TEST_F(MySqlHostDataSourceTest, getAllbyHostnameSubnet6MultiThreading) {
    MultiThreadingTest mt(true);
    testGetAllbyHostnameSubnet6();
}

/// @brief Verifies that IPv4 host reservations in the same subnet can be retrieved
/// by pages.
TEST_F(MySqlHostDataSourceTest, getPage4) {
    testGetPage4();
}

/// @brief Verifies that IPv4 host reservations in the same subnet can be retrieved
/// by pages.
TEST_F(MySqlHostDataSourceTest, getPage4MultiThreading) {
    MultiThreadingTest mt(true);
    testGetPage4();
}

/// @brief Verifies that IPv6 host reservations in the same subnet can be retrieved
/// by pages.
TEST_F(MySqlHostDataSourceTest, getPage6) {
    testGetPage6();
}

/// @brief Verifies that IPv6 host reservations in the same subnet can be retrieved
/// by pages.
TEST_F(MySqlHostDataSourceTest, getPage6MultiThreading) {
    MultiThreadingTest mt(true);
    testGetPage6();
}

/// @brief Verifies that IPv4 host reservations in the same subnet can be retrieved
/// by pages without truncation from the limit.
TEST_F(MySqlHostDataSourceTest, getPageLimit4) {
    testGetPageLimit4(Host::IDENT_DUID);
}

/// @brief Verifies that IPv4 host reservations in the same subnet can be retrieved
/// by pages without truncation from the limit.
TEST_F(MySqlHostDataSourceTest, getPageLimit4MultiThreading) {
    MultiThreadingTest mt(true);
    testGetPageLimit4(Host::IDENT_DUID);
}

/// @brief Verifies that IPv6 host reservations in the same subnet can be retrieved
/// by pages without truncation from the limit.
TEST_F(MySqlHostDataSourceTest, getPageLimit6) {
    testGetPageLimit6(Host::IDENT_HWADDR);
}

/// @brief Verifies that IPv6 host reservations in the same subnet can be retrieved
/// by pages without truncation from the limit.
TEST_F(MySqlHostDataSourceTest, getPageLimit6MultiThreading) {
    MultiThreadingTest mt(true);
    testGetPageLimit6(Host::IDENT_HWADDR);
}

/// @brief Verifies that IPv4 host reservations in the same subnet can be retrieved
/// by pages even with multiple subnets.
TEST_F(MySqlHostDataSourceTest, getPage4Subnets) {
    testGetPage4Subnets();
}

/// @brief Verifies that IPv4 host reservations in the same subnet can be retrieved
/// by pages even with multiple subnets.
TEST_F(MySqlHostDataSourceTest, getPage4SubnetsMultiThreading) {
    MultiThreadingTest mt(true);
    testGetPage4Subnets();
}

/// @brief Verifies that IPv6 host reservations in the same subnet can be retrieved
/// by pages even with multiple subnets.
TEST_F(MySqlHostDataSourceTest, getPage6Subnets) {
    testGetPage6Subnets();
}

/// @brief Verifies that IPv6 host reservations in the same subnet can be retrieved
/// by pages even with multiple subnets.
TEST_F(MySqlHostDataSourceTest, getPage6SubnetsMultiThreading) {
    MultiThreadingTest mt(true);
    testGetPage6Subnets();
}

// Verifies that all IPv4 host reservations can be retrieved by pages.
TEST_F(MySqlHostDataSourceTest, getPage4All) {
    testGetPage4All();
}

// Verifies that all IPv4 host reservations can be retrieved by pages.
TEST_F(MySqlHostDataSourceTest, getPage4AllMultiThreading) {
    MultiThreadingTest mt(true);
    testGetPage4All();
}

// Verifies that all IPv6 host reservations can be retrieved by pages.
TEST_F(MySqlHostDataSourceTest, getPage6All) {
    testGetPage6All();
}

// Verifies that all IPv6 host reservations can be retrieved by pages.
TEST_F(MySqlHostDataSourceTest, getPage6AllMultiThreading) {
    MultiThreadingTest mt(true);
    testGetPage6All();
}

/// @brief Test verifies if a host reservation can be added and later retrieved by IPv4
/// address. Host uses client-id (DUID) as identifier.
TEST_F(MySqlHostDataSourceTest, basic4ClientId) {
    testBasic4(Host::IDENT_DUID);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by IPv4
/// address. Host uses client-id (DUID) as identifier.
TEST_F(MySqlHostDataSourceTest, basic4ClientIdMultiThreading) {
    MultiThreadingTest mt(true);
    testBasic4(Host::IDENT_DUID);
}

/// @brief Test verifies that multiple hosts can be added and later retrieved by their
/// reserved IPv4 address. This test uses HW addresses as identifiers.
TEST_F(MySqlHostDataSourceTest, getByIPv4HWaddr) {
    testGetByIPv4(Host::IDENT_HWADDR);
}

/// @brief Test verifies that multiple hosts can be added and later retrieved by their
/// reserved IPv4 address. This test uses HW addresses as identifiers.
TEST_F(MySqlHostDataSourceTest, getByIPv4HWaddrMultiThreading) {
    MultiThreadingTest mt(true);
    testGetByIPv4(Host::IDENT_HWADDR);
}

/// @brief Test verifies that multiple hosts can be added and later retrieved by their
/// reserved IPv4 address. This test uses client-id (DUID) as identifiers.
TEST_F(MySqlHostDataSourceTest, getByIPv4ClientId) {
    testGetByIPv4(Host::IDENT_DUID);
}

/// @brief Test verifies that multiple hosts can be added and later retrieved by their
/// reserved IPv4 address. This test uses client-id (DUID) as identifiers.
TEST_F(MySqlHostDataSourceTest, getByIPv4ClientIdMultiThreading) {
    MultiThreadingTest mt(true);
    testGetByIPv4(Host::IDENT_DUID);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// hardware address.
TEST_F(MySqlHostDataSourceTest, get4ByHWaddr) {
    testGet4ByIdentifier(Host::IDENT_HWADDR);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// hardware address.
TEST_F(MySqlHostDataSourceTest, get4ByHWaddrMultiThreading) {
    MultiThreadingTest mt(true);
    testGet4ByIdentifier(Host::IDENT_HWADDR);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// DUID.
TEST_F(MySqlHostDataSourceTest, get4ByDUID) {
    testGet4ByIdentifier(Host::IDENT_DUID);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// DUID.
TEST_F(MySqlHostDataSourceTest, get4ByDUIDMultiThreading) {
    MultiThreadingTest mt(true);
    testGet4ByIdentifier(Host::IDENT_DUID);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// circuit id.
TEST_F(MySqlHostDataSourceTest, get4ByCircuitId) {
    testGet4ByIdentifier(Host::IDENT_CIRCUIT_ID);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// circuit id.
TEST_F(MySqlHostDataSourceTest, get4ByCircuitIdMultiThreading) {
    MultiThreadingTest mt(true);
    testGet4ByIdentifier(Host::IDENT_CIRCUIT_ID);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// client-id.
TEST_F(MySqlHostDataSourceTest, get4ByClientId) {
    testGet4ByIdentifier(Host::IDENT_CLIENT_ID);
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// client-id.
TEST_F(MySqlHostDataSourceTest, get4ByClientIdMultiThreading) {
    MultiThreadingTest mt(true);
    testGet4ByIdentifier(Host::IDENT_CLIENT_ID);
}

/// @brief Test verifies if hardware address and client identifier are not confused.
TEST_F(MySqlHostDataSourceTest, hwaddrNotClientId1) {
    testHWAddrNotClientId();
}

/// @brief Test verifies if hardware address and client identifier are not confused.
TEST_F(MySqlHostDataSourceTest, hwaddrNotClientId1MultiThreading) {
    MultiThreadingTest mt(true);
    testHWAddrNotClientId();
}

/// @brief Test verifies if hardware address and client identifier are not confused.
TEST_F(MySqlHostDataSourceTest, hwaddrNotClientId2) {
    testClientIdNotHWAddr();
}

/// @brief Test verifies if hardware address and client identifier are not confused.
TEST_F(MySqlHostDataSourceTest, hwaddrNotClientId2MultiThreading) {
    MultiThreadingTest mt(true);
    testClientIdNotHWAddr();
}

/// @brief Test verifies if a host with FQDN hostname can be stored and later retrieved.
TEST_F(MySqlHostDataSourceTest, hostnameFQDN) {
    testHostname("foo.example.org", 1);
}

/// @brief Test verifies if a host with FQDN hostname can be stored and later retrieved.
TEST_F(MySqlHostDataSourceTest, hostnameFQDNMultiThreading) {
    MultiThreadingTest mt(true);
    testHostname("foo.example.org", 1);
}

/// @brief Test verifies if 100 hosts with unique FQDN hostnames can be stored and later
/// retrieved.
TEST_F(MySqlHostDataSourceTest, hostnameFQDN100) {
    testHostname("foo.example.org", 100);
}

/// @brief Test verifies if 100 hosts with unique FQDN hostnames can be stored and later
/// retrieved.
TEST_F(MySqlHostDataSourceTest, hostnameFQDN100MultiThreading) {
    MultiThreadingTest mt(true);
    testHostname("foo.example.org", 100);
}

/// @brief Test verifies if a host without any hostname specified can be stored and later
/// retrieved.
TEST_F(MySqlHostDataSourceTest, noHostname) {
    testHostname("", 1);
}

/// @brief Test verifies if a host without any hostname specified can be stored and later
/// retrieved.
TEST_F(MySqlHostDataSourceTest, noHostnameMultiThreading) {
    MultiThreadingTest mt(true);
    testHostname("", 1);
}

/// @brief Test verifies if a host with user context can be stored and later retrieved.
TEST_F(MySqlHostDataSourceTest, usercontext) {
    string comment = "{ \"comment\": \"a host reservation\" }";
    testUserContext(Element::fromJSON(comment));
}

/// @brief Test verifies if a host with user context can be stored and later retrieved.
TEST_F(MySqlHostDataSourceTest, usercontextMultiThreading) {
    MultiThreadingTest mt(true);
    string comment = "{ \"comment\": \"a host reservation\" }";
    testUserContext(Element::fromJSON(comment));
}

/// @brief Test insert and retrieve a v6 host with prefix exclude option.
TEST_F(MySqlHostDataSourceTest, prefixExclude) {
    testPrefixExclude("2001:db8::", "2001:db8:0:1::");
}

/// @brief Test verifies if the hardware or client-id query can match hardware address.
TEST_F(MySqlHostDataSourceTest, DISABLED_hwaddrOrClientId1) {
    /// @todo: The logic behind ::get4(subnet_id, hwaddr, duid) call needs to
    /// be discussed.
    ///
    /// @todo: Add host reservation with hardware address X, try to retrieve
    /// host for hardware address X or client identifier Y, verify that the
    /// reservation is returned.
}

/// @brief Test verifies if the hardware or client-id query can match hardware address.
TEST_F(MySqlHostDataSourceTest, DISABLED_hwaddrOrClientId1MultiThreading) {
    MultiThreadingTest mt(true);
    /// @todo: The logic behind ::get4(subnet_id, hwaddr, duid) call needs to
    /// be discussed.
    ///
    /// @todo: Add host reservation with hardware address X, try to retrieve
    /// host for hardware address X or client identifier Y, verify that the
    /// reservation is returned.
}

/// @brief Test verifies if the hardware or client-id query can match client-id.
TEST_F(MySqlHostDataSourceTest, DISABLED_hwaddrOrClientId2) {
    /// @todo: The logic behind ::get4(subnet_id, hwaddr, duid) call needs to
    /// be discussed.
    ///
    /// @todo: Add host reservation with client identifier Y, try to retrieve
    /// host for hardware address X or client identifier Y, verify that the
    /// reservation is returned.
}

/// @brief Test verifies if the hardware or client-id query can match client-id.
TEST_F(MySqlHostDataSourceTest, DISABLED_hwaddrOrClientId2MultiThreading) {
    MultiThreadingTest mt(true);
    /// @todo: The logic behind ::get4(subnet_id, hwaddr, duid) call needs to
    /// be discussed.
    ///
    /// @todo: Add host reservation with client identifier Y, try to retrieve
    /// host for hardware address X or client identifier Y, verify that the
    /// reservation is returned.
}

/// @brief Test verifies that host with IPv6 address and DUID can be added and
/// later retrieved by IPv6 address.
TEST_F(MySqlHostDataSourceTest, get6AddrWithDuid) {
    testGetByIPv6(Host::IDENT_DUID, false);
}

/// @brief Test verifies that host with IPv6 address and DUID can be added and
/// later retrieved by IPv6 address.
TEST_F(MySqlHostDataSourceTest, get6AddrWithDuidMultiThreading) {
    MultiThreadingTest mt(true);
    testGetByIPv6(Host::IDENT_DUID, false);
}

/// @brief Test verifies that host with IPv6 address and HWAddr can be added and
/// later retrieved by IPv6 address.
TEST_F(MySqlHostDataSourceTest, get6AddrWithHWAddr) {
    testGetByIPv6(Host::IDENT_HWADDR, false);
}

/// @brief Test verifies that host with IPv6 address and HWAddr can be added and
/// later retrieved by IPv6 address.
TEST_F(MySqlHostDataSourceTest, get6AddrWithHWAddrMultiThreading) {
    MultiThreadingTest mt(true);
    testGetByIPv6(Host::IDENT_HWADDR, false);
}

/// @brief Test verifies that host with IPv6 prefix and DUID can be added and
/// later retrieved by IPv6 prefix.
TEST_F(MySqlHostDataSourceTest, get6PrefixWithDuid) {
    testGetByIPv6(Host::IDENT_DUID, true);
}

/// @brief Test verifies that host with IPv6 prefix and DUID can be added and
/// later retrieved by IPv6 prefix.
TEST_F(MySqlHostDataSourceTest, get6PrefixWithDuidMultiThreading) {
    MultiThreadingTest mt(true);
    testGetByIPv6(Host::IDENT_DUID, true);
}

/// @brief Test verifies that host with IPv6 prefix and HWAddr can be added and
/// later retrieved by IPv6 prefix.
TEST_F(MySqlHostDataSourceTest, get6PrefixWithHWaddr) {
    testGetByIPv6(Host::IDENT_HWADDR, true);
}

/// @brief Test verifies that host with IPv6 prefix and HWAddr can be added and
/// later retrieved by IPv6 prefix.
TEST_F(MySqlHostDataSourceTest, get6PrefixWithHWaddrMultiThreading) {
    MultiThreadingTest mt(true);
    testGetByIPv6(Host::IDENT_HWADDR, true);
}

/// @brief Test verifies that host with IPv6 prefix reservation can be retrieved
/// by subnet id and prefix value.
TEST_F(MySqlHostDataSourceTest, get6SubnetPrefix) {
    testGetBySubnetIPv6();
}

/// @brief Test verifies that host with IPv6 prefix reservation can be retrieved
/// by subnet id and prefix value.
TEST_F(MySqlHostDataSourceTest, get6SubnetPrefixMultiThreading) {
    MultiThreadingTest mt(true);
    testGetBySubnetIPv6();
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// hardware address.
TEST_F(MySqlHostDataSourceTest, get6ByHWaddr) {
    testGet6ByHWAddr();
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// hardware address.
TEST_F(MySqlHostDataSourceTest, get6ByHWaddrMultiThreading) {
    MultiThreadingTest mt(true);
    testGet6ByHWAddr();
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// client identifier.
TEST_F(MySqlHostDataSourceTest, get6ByClientId) {
    testGet6ByClientId();
}

/// @brief Test verifies if a host reservation can be added and later retrieved by
/// client identifier.
TEST_F(MySqlHostDataSourceTest, get6ByClientIdMultiThreading) {
    MultiThreadingTest mt(true);
    testGet6ByClientId();
}

/// @brief Test verifies if a host reservation can be stored with both IPv6 address and
/// prefix.
TEST_F(MySqlHostDataSourceTest, addr6AndPrefix) {
    testAddr6AndPrefix();
}

/// @brief Test verifies if a host reservation can be stored with both IPv6 address and
/// prefix.
TEST_F(MySqlHostDataSourceTest, addr6AndPrefixMultiThreading) {
    MultiThreadingTest mt(true);
    testAddr6AndPrefix();
}

/// @brief Tests if host with multiple IPv6 reservations can be added and then
/// retrieved correctly. Test checks reservations comparing.
TEST_F(MySqlHostDataSourceTest, multipleReservations) {
    testMultipleReservations();
}

/// @brief Tests if host with multiple IPv6 reservations can be added and then
/// retrieved correctly. Test checks reservations comparing.
TEST_F(MySqlHostDataSourceTest, multipleReservationsMultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleReservations();
}

/// @brief Tests if compareIPv6Reservations() method treats same pool of reservations
/// but added in different order as equal.
TEST_F(MySqlHostDataSourceTest, multipleReservationsDifferentOrder) {
    testMultipleReservationsDifferentOrder();
}

/// @brief Tests if compareIPv6Reservations() method treats same pool of reservations
/// but added in different order as equal.
TEST_F(MySqlHostDataSourceTest, multipleReservationsDifferentOrderMultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleReservationsDifferentOrder();
}

/// @brief Test that multiple client classes for IPv4 can be inserted and
/// retrieved for a given host reservation.
TEST_F(MySqlHostDataSourceTest, multipleClientClasses4) {
    testMultipleClientClasses4();
}

/// @brief Test that multiple client classes for IPv4 can be inserted and
/// retrieved for a given host reservation.
TEST_F(MySqlHostDataSourceTest, multipleClientClasses4MultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleClientClasses4();
}

/// @brief Test that multiple client classes for IPv6 can be inserted and
/// retrieved for a given host reservation.
TEST_F(MySqlHostDataSourceTest, multipleClientClasses6) {
    testMultipleClientClasses6();
}

/// @brief Test that multiple client classes for IPv6 can be inserted and
/// retrieved for a given host reservation.
TEST_F(MySqlHostDataSourceTest, multipleClientClasses6MultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleClientClasses6();
}

/// @brief Test that multiple client classes for both IPv4 and IPv6 can
/// be inserted and retrieved for a given host reservation.
TEST_F(MySqlHostDataSourceTest, multipleClientClassesBoth) {
    testMultipleClientClassesBoth();
}

/// @brief Test that multiple client classes for both IPv4 and IPv6 can
/// be inserted and retrieved for a given host reservation.
TEST_F(MySqlHostDataSourceTest, multipleClientClassesBothMultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleClientClassesBoth();
}

/// @brief Test if the same host can have reservations in different subnets (with the
/// same hardware address). The test logic is as follows:
/// Insert 10 host reservations for a given physical host (the same
/// hardware address), but for different subnets (different subnet-ids).
/// Make sure that getAll() returns them all correctly.
TEST_F(MySqlHostDataSourceTest, multipleSubnetsHWAddr) {
    testMultipleSubnets(10, Host::IDENT_HWADDR);
}

/// @brief Test if the same host can have reservations in different subnets (with the
/// same hardware address). The test logic is as follows:
/// Insert 10 host reservations for a given physical host (the same
/// hardware address), but for different subnets (different subnet-ids).
/// Make sure that getAll() returns them all correctly.
TEST_F(MySqlHostDataSourceTest, multipleSubnetsHWAddrMultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleSubnets(10, Host::IDENT_HWADDR);
}

/// @brief Test if the same host can have reservations in different subnets (with the
/// same client identifier). The test logic is as follows:
///
/// Insert 10 host reservations for a given physical host (the same
/// client-identifier), but for different subnets (different subnet-ids).
/// Make sure that getAll() returns them correctly.
TEST_F(MySqlHostDataSourceTest, multipleSubnetsClientId) {
    testMultipleSubnets(10, Host::IDENT_DUID);
}

/// @brief Test if the same host can have reservations in different subnets (with the
/// same client identifier). The test logic is as follows:
///
/// Insert 10 host reservations for a given physical host (the same
/// client-identifier), but for different subnets (different subnet-ids).
/// Make sure that getAll() returns them correctly.
TEST_F(MySqlHostDataSourceTest, multipleSubnetsClientIdMultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleSubnets(10, Host::IDENT_DUID);
}

/// @brief Test if host reservations made for different IPv6 subnets are handled correctly.
/// The test logic is as follows:
///
/// Insert 10 host reservations for different subnets. Make sure that
/// get6(subnet-id, ...) calls return correct reservation.
TEST_F(MySqlHostDataSourceTest, subnetId6) {
    testSubnetId6(10, Host::IDENT_HWADDR);
}

/// @brief Test if host reservations made for different IPv6 subnets are handled correctly.
/// The test logic is as follows:
///
/// Insert 10 host reservations for different subnets. Make sure that
/// get6(subnet-id, ...) calls return correct reservation.
TEST_F(MySqlHostDataSourceTest, subnetId6MultiThreading) {
    MultiThreadingTest mt(true);
    testSubnetId6(10, Host::IDENT_HWADDR);
}

/// @brief Test if the duplicate host instances can't be inserted. The test logic is as
/// follows: try to add multiple instances of the same host reservation and
/// verify that the second and following attempts will throw exceptions.
/// Hosts with same DUID.
TEST_F(MySqlHostDataSourceTest, addDuplicate6WithDUID) {
    testAddDuplicate6WithSameDUID();
}

/// @brief Test if the duplicate host instances can't be inserted. The test logic is as
/// follows: try to add multiple instances of the same host reservation and
/// verify that the second and following attempts will throw exceptions.
/// Hosts with same DUID.
TEST_F(MySqlHostDataSourceTest, addDuplicate6WithDUIDMultiThreading) {
    MultiThreadingTest mt(true);
    testAddDuplicate6WithSameDUID();
}

/// @brief Test if the duplicate host instances can't be inserted. The test logic is as
/// follows: try to add multiple instances of the same host reservation and
/// verify that the second and following attempts will throw exceptions.
/// Hosts with same HWAddr.
TEST_F(MySqlHostDataSourceTest, addDuplicate6WithHWAddr) {
    testAddDuplicate6WithSameHWAddr();
}

/// @brief Test if the duplicate host instances can't be inserted. The test logic is as
/// follows: try to add multiple instances of the same host reservation and
/// verify that the second and following attempts will throw exceptions.
/// Hosts with same HWAddr.
TEST_F(MySqlHostDataSourceTest, addDuplicate6WithHWAddrMultiThreading) {
    MultiThreadingTest mt(true);
    testAddDuplicate6WithSameHWAddr();
}

/// @brief Test if the same IPv6 reservation can't be inserted multiple times.
TEST_F(MySqlHostDataSourceTest, addDuplicateIPv6) {
    testAddDuplicateIPv6();
}

/// @brief Test if the same IPv6 reservation can't be inserted multiple times.
TEST_F(MySqlHostDataSourceTest, addDuplicateIPv6MultiThreading) {
    MultiThreadingTest mt(true);
    testAddDuplicateIPv6();
}

/// @brief Test if the host reservation for the same IPv6 address can be inserted
/// multiple times when allowed by the configuration and when the host identifier
/// is different.
TEST_F(MySqlHostDataSourceTest, allowDuplicateIPv6) {
    testAllowDuplicateIPv6();
}

/// @brief Test if the host reservation for the same IPv6 address can be inserted
/// multiple times when allowed by the configuration and when the host identifier
/// is different.
TEST_F(MySqlHostDataSourceTest, allowDuplicateIPv6MultiThreading) {
    MultiThreadingTest mt(true);
    testAllowDuplicateIPv6();
}

/// @brief Test if the duplicate IPv4 host instances can't be inserted. The test logic is as
/// follows: try to add multiple instances of the same host reservation and
/// verify that the second and following attempts will throw exceptions.
TEST_F(MySqlHostDataSourceTest, addDuplicateIPv4) {
    testAddDuplicateIPv4();
}

/// @brief Test if the duplicate IPv4 host instances can't be inserted. The test logic is as
/// follows: try to add multiple instances of the same host reservation and
/// verify that the second and following attempts will throw exceptions.
TEST_F(MySqlHostDataSourceTest, addDuplicateIPv4MultiThreading) {
    MultiThreadingTest mt(true);
    testAddDuplicateIPv4();
}

/// @brief Test if the host reservation for the same IPv4 address can be inserted
/// multiple times when allowed by the configuration and when the host identifier
/// is different.
TEST_F(MySqlHostDataSourceTest, allowDuplicateIPv4) {
    testAllowDuplicateIPv4();
}

/// @brief Test if the host reservation for the same IPv4 address can be inserted
/// multiple times when allowed by the configuration and when the host identifier
/// is different.
TEST_F(MySqlHostDataSourceTest, allowDuplicateIPv4MultiThreading) {
    MultiThreadingTest mt(true);
    testAllowDuplicateIPv4();
}

/// @brief This test verifies that DHCPv4 options can be inserted in a binary format
/// and retrieved from the MySQL host database.
TEST_F(MySqlHostDataSourceTest, optionsReservations4) {
    string comment = "{ \"comment\": \"a host reservation\" }";
    testOptionsReservations4(false, Element::fromJSON(comment));
}

/// @brief This test verifies that DHCPv4 options can be inserted in a binary format
/// and retrieved from the MySQL host database.
TEST_F(MySqlHostDataSourceTest, optionsReservations4MultiThreading) {
    MultiThreadingTest mt(true);
    string comment = "{ \"comment\": \"a host reservation\" }";
    testOptionsReservations4(false, Element::fromJSON(comment));
}

/// @brief This test verifies that DHCPv6 options can be inserted in a binary format
/// and retrieved from the MySQL host database.
TEST_F(MySqlHostDataSourceTest, optionsReservations6) {
    string comment = "{ \"comment\": \"a host reservation\" }";
    testOptionsReservations6(false, Element::fromJSON(comment));
}

/// @brief This test verifies that DHCPv6 options can be inserted in a binary format
/// and retrieved from the MySQL host database.
TEST_F(MySqlHostDataSourceTest, optionsReservations6MultiThreading) {
    MultiThreadingTest mt(true);
    string comment = "{ \"comment\": \"a host reservation\" }";
    testOptionsReservations6(false, Element::fromJSON(comment));
}

/// @brief This test verifies that DHCPv4 and DHCPv6 options can be inserted in a
/// binary format and retrieved with a single query to the database.
TEST_F(MySqlHostDataSourceTest, optionsReservations46) {
    testOptionsReservations46(false);
}

/// @brief This test verifies that DHCPv4 and DHCPv6 options can be inserted in a
/// binary format and retrieved with a single query to the database.
TEST_F(MySqlHostDataSourceTest, optionsReservations46MultiThreading) {
    MultiThreadingTest mt(true);
    testOptionsReservations46(false);
}

/// @brief This test verifies that DHCPv4 options can be inserted in a textual format
/// and retrieved from the MySQL host database.
TEST_F(MySqlHostDataSourceTest, formattedOptionsReservations4) {
    string comment = "{ \"comment\": \"a host reservation\" }";
    testOptionsReservations4(true, Element::fromJSON(comment));
}

/// @brief This test verifies that DHCPv4 options can be inserted in a textual format
/// and retrieved from the MySQL host database.
TEST_F(MySqlHostDataSourceTest, formattedOptionsReservations4MultiThreading) {
    MultiThreadingTest mt(true);
    string comment = "{ \"comment\": \"a host reservation\" }";
    testOptionsReservations4(true, Element::fromJSON(comment));
}

/// @brief This test verifies that DHCPv6 options can be inserted in a textual format
/// and retrieved from the MySQL host database.
TEST_F(MySqlHostDataSourceTest, formattedOptionsReservations6) {
    string comment = "{ \"comment\": \"a host reservation\" }";
    testOptionsReservations6(true, Element::fromJSON(comment));
}

/// @brief This test verifies that DHCPv6 options can be inserted in a textual format
/// and retrieved from the MySQL host database.
TEST_F(MySqlHostDataSourceTest, formattedOptionsReservations6MultiThreading) {
    MultiThreadingTest mt(true);
    string comment = "{ \"comment\": \"a host reservation\" }";
    testOptionsReservations6(true, Element::fromJSON(comment));
}

/// @brief This test verifies that DHCPv4 and DHCPv6 options can be inserted in a
/// textual format and retrieved with a single query to the database.
TEST_F(MySqlHostDataSourceTest, formattedOptionsReservations46) {
    testOptionsReservations46(true);
}

/// @brief This test verifies that DHCPv4 and DHCPv6 options can be inserted in a
/// textual format and retrieved with a single query to the database.
TEST_F(MySqlHostDataSourceTest, formattedOptionsReservations46MultiThreading) {
    MultiThreadingTest mt(true);
    testOptionsReservations46(true);
}

/// @brief This test checks transactional insertion of the host information
/// into the database. The failure to insert host information at
/// any stage should cause the whole transaction to be rolled back.
TEST_F(MySqlHostDataSourceTest, testAddRollback) {
    // Make sure we have the pointer to the host data source.
    ASSERT_TRUE(hdsptr_);

    // To test the transaction rollback mechanism we need to cause the
    // insertion of host information to fail at some stage. The 'hosts'
    // table should be updated correctly but the failure should occur
    // when inserting reservations or options. The simplest way to
    // achieve that is to simply drop one of the tables. To do so, we
    // connect to the database and issue a DROP query.
    DatabaseConnection::ParameterMap params;
    params["name"] = "keatest";
    params["user"] = "keatest";
    params["password"] = "keatest";
    MySqlConnection conn(params);
    ASSERT_NO_THROW(conn.openDatabase());

    int status = MysqlQuery(conn.mysql_,
                            "DROP TABLE IF EXISTS ipv6_reservations");
    ASSERT_EQ(0, status) << mysql_error(conn.mysql_);

    // Create a host with a reservation.
    HostPtr host = HostDataSourceUtils::initializeHost6("2001:db8:1::1",
                                        Host::IDENT_HWADDR, false);
    // Let's assign some DHCPv4 subnet to the host, because we will use the
    // DHCPv4 subnet to try to retrieve the host after failed insertion.
    host->setIPv4SubnetID(SubnetID(4));

    // There is no ipv6_reservations table, so the insertion should fail.
    ASSERT_THROW(hdsptr_->add(host), DbOperationError);

    // Even though we have created a DHCPv6 host, we can't use get6()
    // method to retrieve the host from the database, because the
    // query would expect that the ipv6_reservations table is present.
    // Therefore, the query would fail. Instead, we use the get4 method
    // which uses the same client identifier, but doesn't attempt to
    // retrieve the data from ipv6_reservations table. The query should
    // pass but return no host because the (insert) transaction is expected
    // to be rolled back.
    ConstHostPtr from_hds = hdsptr_->get4(host->getIPv4SubnetID(),
                                          host->getIdentifierType(),
                                          &host->getIdentifier()[0],
                                          host->getIdentifier().size());
    EXPECT_FALSE(from_hds);
}

/// @brief This test checks transactional insertion of the host information
/// into the database. The failure to insert host information at
/// any stage should cause the whole transaction to be rolled back.
TEST_F(MySqlHostDataSourceTest, testAddRollbackMultiThreading) {
    MultiThreadingTest mt(true);
    // Make sure we have the pointer to the host data source.
    ASSERT_TRUE(hdsptr_);

    // To test the transaction rollback mechanism we need to cause the
    // insertion of host information to fail at some stage. The 'hosts'
    // table should be updated correctly but the failure should occur
    // when inserting reservations or options. The simplest way to
    // achieve that is to simply drop one of the tables. To do so, we
    // connect to the database and issue a DROP query.
    DatabaseConnection::ParameterMap params;
    params["name"] = "keatest";
    params["user"] = "keatest";
    params["password"] = "keatest";
    MySqlConnection conn(params);
    ASSERT_NO_THROW(conn.openDatabase());

    int status = MysqlQuery(conn.mysql_,
                            "DROP TABLE IF EXISTS ipv6_reservations");
    ASSERT_EQ(0, status) << mysql_error(conn.mysql_);

    // Create a host with a reservation.
    HostPtr host = HostDataSourceUtils::initializeHost6("2001:db8:1::1",
                                        Host::IDENT_HWADDR, false);
    // Let's assign some DHCPv4 subnet to the host, because we will use the
    // DHCPv4 subnet to try to retrieve the host after failed insertion.
    host->setIPv4SubnetID(SubnetID(4));

    // There is no ipv6_reservations table, so the insertion should fail.
    ASSERT_THROW(hdsptr_->add(host), DbOperationError);

    // Even though we have created a DHCPv6 host, we can't use get6()
    // method to retrieve the host from the database, because the
    // query would expect that the ipv6_reservations table is present.
    // Therefore, the query would fail. Instead, we use the get4 method
    // which uses the same client identifier, but doesn't attempt to
    // retrieve the data from ipv6_reservations table. The query should
    // pass but return no host because the (insert) transaction is expected
    // to be rolled back.
    ConstHostPtr from_hds = hdsptr_->get4(host->getIPv4SubnetID(),
                                          host->getIdentifierType(),
                                          &host->getIdentifier()[0],
                                          host->getIdentifier().size());
    EXPECT_FALSE(from_hds);
}

/// @brief This test checks that siaddr, sname, file fields can be retrieved
/// from a database for a host.
TEST_F(MySqlHostDataSourceTest, messageFields) {
    testMessageFields4();
}

/// @brief This test checks that siaddr, sname, file fields can be retrieved
/// from a database for a host.
TEST_F(MySqlHostDataSourceTest, messageFieldsMultiThreading) {
    MultiThreadingTest mt(true);
    testMessageFields4();
}

/// @brief Check that delete(subnet-id, addr4) works.
TEST_F(MySqlHostDataSourceTest, deleteByAddr4) {
    testDeleteByAddr4();
}

/// @brief Check that delete(subnet-id, addr4) works.
TEST_F(MySqlHostDataSourceTest, deleteByAddr4MultiThreading) {
    MultiThreadingTest mt(true);
    testDeleteByAddr4();
}

/// @brief Check that delete(subnet4-id, identifier-type, identifier) works.
TEST_F(MySqlHostDataSourceTest, deleteById4) {
    testDeleteById4();
}

/// @brief Check that delete(subnet4-id, identifier-type, identifier) works.
TEST_F(MySqlHostDataSourceTest, deleteById4MultiThreading) {
    MultiThreadingTest mt(true);
    testDeleteById4();
}

/// @brief Check that delete(subnet4-id, identifier-type, identifier) works,
/// even when options are present.
TEST_F(MySqlHostDataSourceTest, deleteById4Options) {
    testDeleteById4Options();
}

/// @brief Check that delete(subnet4-id, identifier-type, identifier) works,
/// even when options are present.
TEST_F(MySqlHostDataSourceTest, deleteById4OptionsMultiThreading) {
    MultiThreadingTest mt(true);
    testDeleteById4Options();
}

/// @brief Check that delete(subnet6-id, identifier-type, identifier) works.
TEST_F(MySqlHostDataSourceTest, deleteById6) {
    testDeleteById6();
}

/// @brief Check that delete(subnet6-id, identifier-type, identifier) works.
TEST_F(MySqlHostDataSourceTest, deleteById6MultiThreading) {
    MultiThreadingTest mt(true);
    testDeleteById6();
}

/// @brief Check that delete(subnet6-id, identifier-type, identifier) works,
/// even when options are present.
TEST_F(MySqlHostDataSourceTest, deleteById6Options) {
    testDeleteById6Options();
}

/// @brief Check that delete(subnet6-id, identifier-type, identifier) works,
/// even when options are present.
TEST_F(MySqlHostDataSourceTest, deleteById6OptionsMultiThreading) {
    MultiThreadingTest mt(true);
    testDeleteById6Options();
}

// This test verifies that all reservations can be deleted from database
// by providing subnet ID and one address.
TEST_F(MySqlHostDataSourceTest, del2) {
    testDelete2ForIPv6();
}

// This test verifies that all reservations can be deleted from database
// by providing subnet ID and one address.
TEST_F(MySqlHostDataSourceTest, del2MultiThreading) {
    MultiThreadingTest mt(true);
    testDelete2ForIPv6();
}

// This test verifies that address and PD reservations can be deleted from database
// by providing subnet ID and the address.
TEST_F(MySqlHostDataSourceTest, delBoth) {
    testDelete2ForIPv6();
}

// This test verifies that address and PD reservations can be deleted from database
// by providing subnet ID and the address.
TEST_F(MySqlHostDataSourceTest, delBothMultiThreading) {
    MultiThreadingTest mt(true);
    testDelete2ForIPv6();
}

/// @brief Tests that multiple reservations without IPv4 addresses can be
/// specified within a subnet.
TEST_F(MySqlHostDataSourceTest, testMultipleHostsNoAddress4) {
    testMultipleHostsNoAddress4();
}

/// @brief Tests that multiple reservations without IPv4 addresses can be
/// specified within a subnet.
TEST_F(MySqlHostDataSourceTest, testMultipleHostsNoAddress4MultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleHostsNoAddress4();
}

/// @brief Tests that multiple hosts can be specified within an IPv6 subnet.
TEST_F(MySqlHostDataSourceTest, testMultipleHosts6) {
    testMultipleHosts6();
}

/// @brief Tests that multiple hosts can be specified within an IPv6 subnet.
TEST_F(MySqlHostDataSourceTest, testMultipleHosts6MultiThreading) {
    MultiThreadingTest mt(true);
    testMultipleHosts6();
}

/// @brief Tests that hosts can be updated.
TEST_F(MySqlHostDataSourceTest, update) {
    testUpdate();
}

/// @brief Tests that hosts can be updated.
TEST_F(MySqlHostDataSourceTest, updateMultiThreading) {
    MultiThreadingTest mt(true);
    testUpdate();
}

/// @brief Test fixture class for validating @c HostMgr using
/// MySQL as alternate host data source.
class MySQLHostMgrTest : public HostMgrTest {
protected:

    /// @brief Build MySQL schema for a test.
    virtual void SetUp();

    /// @brief Rollback and drop MySQL schema after the test.
    virtual void TearDown();

    /// @brief Initializer.
    MySqlHostDataSourceInit init_;
};

void
MySQLHostMgrTest::SetUp() {
    HostMgrTest::SetUp();

    // Ensure we have the proper schema with no transient data.
    db::test::createMySQLSchema();

    // Connect to the database
    try {
        HostMgr::addBackend(db::test::validMySQLConnectionString());
    } catch (...) {
        std::cerr << "*** ERROR: unable to open database. The test\n"
            "*** environment is broken and must be fixed before\n"
            "*** the MySQL tests will run correctly.\n"
            "*** The reason for the problem is described in the\n"
            "*** accompanying exception output.\n";
        throw;
    }
}

void
MySQLHostMgrTest::TearDown() {
    try {
        HostMgr::instance().getHostDataSource()->rollback();
    } catch(...) {
        // we don't care if we aren't in a transaction.
    }

    HostMgr::delBackend("mysql");
    // If data wipe enabled, delete transient data otherwise destroy the schema
    db::test::destroyMySQLSchema();
}

/// @brief Test fixture class for validating @c HostMgr using
/// MySQL as alternate host data source and MySQL connectivity loss.
class MySQLHostMgrDbLostCallbackTest : public HostMgrDbLostCallbackTest {
public:
    virtual void destroySchema() {
        // If data wipe enabled, delete transient data otherwise destroy the schema
        db::test::destroyMySQLSchema();
    }

    virtual void createSchema() {
        // Ensure we have the proper schema with no transient data.
        db::test::createMySQLSchema();
    }

    virtual std::string validConnectString() {
        return (db::test::validMySQLConnectionString());
    }

    virtual std::string invalidConnectString() {
        return (connectionString(MYSQL_VALID_TYPE, INVALID_NAME, VALID_HOST,
                                 VALID_USER, VALID_PASSWORD));
    }

    /// @brief Initializer.
    MySqlHostDataSourceInit init_;
};

// This test verifies that reservations for a particular client can
// be retrieved from the configuration file and a database simultaneously.
TEST_F(MySQLHostMgrTest, getAll) {
    testGetAll(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that reservations for a particular subnet can
// be retrieved from the configuration file and a database simultaneously.
TEST_F(MySQLHostMgrTest, getAll4BySubnet) {
    testGetAll4BySubnet(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that reservations for a particular subnet can
// be retrieved from the configuration file and a database simultaneously.
TEST_F(MySQLHostMgrTest, getAll6BySubnet) {
    testGetAll6BySubnet(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that HostMgr returns all reservations for the specified
// IPv4 subnet and reserved address.
TEST_F(MySQLHostMgrTest, getAll4BySubnetIP) {
    testGetAll4BySubnetIP(*getCfgHosts(), *getCfgHosts());
}

// This test verifies that HostMgr returns all reservations for the specified
// IPv6 subnet and reserved address.
TEST_F(MySQLHostMgrTest, getAll6BySubnetIP) {
    testGetAll6BySubnetIP(*getCfgHosts(), *getCfgHosts());
}

// This test verifies that HostMgr returns all reservations for the
// IPv6 reserved address.
TEST_F(MySQLHostMgrTest, getAll6ByIP) {
    testGetAll6ByIP(*getCfgHosts(), *getCfgHosts());
}

// This test verifies that HostMgr returns all reservations for the
// IPv6 reserved prefix.
TEST_F(MySQLHostMgrTest, getAll6ByIpPrefix) {
    testGetAll6ByIpPrefix(*getCfgHosts(), *getCfgHosts());
}

// This test verifies that reservations for a particular hostname can be
// retrieved from the configuration file and a database simultaneously.
TEST_F(MySQLHostMgrTest, getAllbyHostname) {
    testGetAllbyHostname(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that reservations for a particular hostname and
// DHCPv4 subnet can be retrieved from the configuration file and a
// database simultaneously.
TEST_F(MySQLHostMgrTest, getAllbyHostnameSubnet4) {
    testGetAllbyHostnameSubnet4(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that reservations for a particular hostname and
// DHCPv6 subnet can be retrieved from the configuration file and a
// database simultaneously.
TEST_F(MySQLHostMgrTest, getAllbyHostnameSubnet6) {
    testGetAllbyHostnameSubnet6(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that reservations for a particular subnet can
// be retrieved by pages from the configuration file and a database
// simultaneously.
TEST_F(MySQLHostMgrTest, getPage4) {
    testGetPage4(true);
}

// This test verifies that all v4 reservations be retrieved by pages
// from the configuration file and a database simultaneously.
TEST_F(MySQLHostMgrTest, getPage4All) {
    testGetPage4All(true);
}

// This test verifies that reservations for a particular subnet can
// be retrieved by pages from the configuration file and a database
// simultaneously.
TEST_F(MySQLHostMgrTest, getPage6) {
    testGetPage6(true);
}

// This test verifies that all v6 reservations be retrieved by pages
// from the configuration file and a database simultaneously.
TEST_F(MySQLHostMgrTest, getPage6All) {
    testGetPage6All(true);
}

// This test verifies that IPv4 reservations for a particular client can
// be retrieved from the configuration file and a database simultaneously.
TEST_F(MySQLHostMgrTest, getAll4) {
    testGetAll4(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that the IPv4 reservation can be retrieved from a
// database.
TEST_F(MySQLHostMgrTest, get4) {
    testGet4(HostMgr::instance());
}

// This test verifies that the IPv6 reservation can be retrieved from a
// database.
TEST_F(MySQLHostMgrTest, get6) {
    testGet6(HostMgr::instance());
}

// This test verifies that the IPv6 prefix reservation can be retrieved
// from a configuration file and a database.
TEST_F(MySQLHostMgrTest, get6ByPrefix) {
    testGet6ByPrefix(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that the reservations can be added to a configuration
// file and a database.
TEST_F(MySQLHostMgrTest, add) {
    testAdd(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that the reservations can be deleted from a configuration
// file and a database by subnet ID and address.
TEST_F(MySQLHostMgrTest, del) {
    testDeleteByIDAndAddress(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that the reservation can be deleted from database
// by providing subnet ID and address, and other reservations in the subnet
// remain undeleted.
TEST_F(MySQLHostMgrTest, delOneHost) {
    testDeleteOneHostByIDAndAddress(HostMgr::instance());
}

// This test verifies that the IPv4 reservations can be deleted from a
// configuration file and a database by subnet ID and identifier.
TEST_F(MySQLHostMgrTest, del4) {
    testDelete4ByIDAndIdentifier(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that the IPv6 reservations can be deleted from a
// configuration file and a database by subnet ID and identifier.
TEST_F(MySQLHostMgrTest, del6) {
    testDelete6ByIDAndIdentifier(*getCfgHosts(), HostMgr::instance());
}

// This test verifies that it is possible to control whether the reserved
// IP addresses are unique or non unique via the HostMgr.
TEST_F(MySQLHostMgrTest, setIPReservationsUnique) {
    EXPECT_TRUE(HostMgr::instance().setIPReservationsUnique(true));
    EXPECT_TRUE(HostMgr::instance().setIPReservationsUnique(false));
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testRetryOpenDbLostAndRecoveredCallback) {
    MultiThreadingTest mt(false);
    testRetryOpenDbLostAndRecoveredCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testRetryOpenDbLostAndRecoveredCallbackMultiThreading) {
    MultiThreadingTest mt(true);
    testRetryOpenDbLostAndRecoveredCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testRetryOpenDbLostAndFailedCallback) {
    MultiThreadingTest mt(false);
    testRetryOpenDbLostAndFailedCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testRetryOpenDbLostAndFailedCallbackMultiThreading) {
    MultiThreadingTest mt(true);
    testRetryOpenDbLostAndFailedCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testRetryOpenDbLostAndRecoveredAfterTimeoutCallback) {
    MultiThreadingTest mt(false);
    testRetryOpenDbLostAndRecoveredAfterTimeoutCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testRetryOpenDbLostAndRecoveredAfterTimeoutCallbackMultiThreading) {
    MultiThreadingTest mt(true);
    testRetryOpenDbLostAndRecoveredAfterTimeoutCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testRetryOpenDbLostAndFailedAfterTimeoutCallback) {
    MultiThreadingTest mt(false);
    testRetryOpenDbLostAndFailedAfterTimeoutCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testRetryOpenDbLostAndFailedAfterTimeoutCallbackMultiThreading) {
    MultiThreadingTest mt(true);
    testRetryOpenDbLostAndFailedAfterTimeoutCallback();
}

/// @brief Verifies that db lost callback is not invoked on an open failure
TEST_F(MySQLHostMgrDbLostCallbackTest, testNoCallbackOnOpenFailure) {
    MultiThreadingTest mt(false);
    testNoCallbackOnOpenFailure();
}

/// @brief Verifies that db lost callback is not invoked on an open failure
TEST_F(MySQLHostMgrDbLostCallbackTest, testNoCallbackOnOpenFailureMultiThreading) {
    MultiThreadingTest mt(true);
    testNoCallbackOnOpenFailure();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testDbLostAndRecoveredCallback) {
    MultiThreadingTest mt(false);
    testDbLostAndRecoveredCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testDbLostAndRecoveredCallbackMultiThreading) {
    MultiThreadingTest mt(true);
    testDbLostAndRecoveredCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testDbLostAndFailedCallback) {
    MultiThreadingTest mt(false);
    testDbLostAndFailedCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testDbLostAndFailedCallbackMultiThreading) {
    MultiThreadingTest mt(true);
    testDbLostAndFailedCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testDbLostAndRecoveredAfterTimeoutCallback) {
    MultiThreadingTest mt(false);
    testDbLostAndRecoveredAfterTimeoutCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testDbLostAndRecoveredAfterTimeoutCallbackMultiThreading) {
    MultiThreadingTest mt(true);
    testDbLostAndRecoveredAfterTimeoutCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testDbLostAndFailedAfterTimeoutCallback) {
    MultiThreadingTest mt(false);
    testDbLostAndFailedAfterTimeoutCallback();
}

/// @brief Verifies that loss of connectivity to MySQL is handled correctly.
TEST_F(MySQLHostMgrDbLostCallbackTest, testDbLostAndFailedAfterTimeoutCallbackMultiThreading) {
    MultiThreadingTest mt(true);
    testDbLostAndFailedAfterTimeoutCallback();
}

/// @brief Test fixture class for testing @ref CfgDbAccessTest using MySQL
/// backend.
class CfgMySqlHbDbAccessTest : public ::testing::Test {
public:

    /// @brief Constructor.
    CfgMySqlHbDbAccessTest() {
        // Ensure we have the proper schema with no transient data.
        db::test::createMySQLSchema();
        HostMgr::create();
    }

    /// @brief Destructor.
    virtual ~CfgMySqlHbDbAccessTest() {
        // If data wipe enabled, delete transient data otherwise destroy the schema
        db::test::destroyMySQLSchema();
        HostMgr::create();
    }

    /// @brief Initializer.
    MySqlHostDataSourceInit init_;
};

// Tests that memfile lease manager and MySQL host data source can be created from a
// specified configuration.
TEST_F(CfgMySqlHbDbAccessTest, createManagers) {
    CfgDbAccess cfg;
    ASSERT_NO_THROW(cfg.setLeaseDbAccessString("type=memfile persist=false universe=4"));
    ASSERT_NO_THROW(cfg.setHostDbAccessString(db::test::validMySQLConnectionString()));
    ASSERT_NO_THROW(cfg.createManagers());

    ASSERT_NO_THROW({
        const HostDataSourcePtr& host_data_source =
            HostMgr::instance().getHostDataSource();
        ASSERT_TRUE(host_data_source);
        EXPECT_EQ("mysql", host_data_source->getType());
    });

    // Because of the lazy initialization of the HostMgr instance, it is
    // possible that the first call to the instance() function tosses
    // existing connection to the database created by the call to
    // createManagers(). Let's make sure that this doesn't happen.
    ASSERT_NO_THROW(HostMgr::instance());

    ASSERT_NO_THROW({
        const HostDataSourcePtr& host_data_source =
            HostMgr::instance().getHostDataSource();
        ASSERT_TRUE(host_data_source);
        EXPECT_EQ("mysql", host_data_source->getType());
    });

    EXPECT_TRUE(HostMgr::instance().getIPReservationsUnique());
}

// Tests that the createManagers function utilizes the setting in the
// CfgDbAccess class which controls whether the IP reservations must
// be unique or can be non-unique.
TEST_F(CfgMySqlHbDbAccessTest, createManagersIPResrvUnique) {
    CfgDbAccess cfg;

    cfg.setIPReservationsUnique(false);
    ASSERT_NO_THROW(cfg.setLeaseDbAccessString("type=memfile persist=false universe=6"));
    ASSERT_NO_THROW(cfg.setHostDbAccessString(db::test::validMySQLConnectionString()));
    ASSERT_NO_THROW(cfg.createManagers());

    ASSERT_NO_THROW({
        const HostDataSourcePtr& host_data_source =
            HostMgr::instance().getHostDataSource();
        ASSERT_TRUE(host_data_source);
        EXPECT_EQ("mysql", host_data_source->getType());
    });

    // Because of the lazy initialization of the HostMgr instance, it is
    // possible that the first call to the instance() function tosses
    // existing connection to the database created by the call to
    // createManagers(). Let's make sure that this doesn't happen.
    ASSERT_NO_THROW(HostMgr::instance());

    ASSERT_NO_THROW({
        const HostDataSourcePtr& host_data_source =
            HostMgr::instance().getHostDataSource();
        ASSERT_TRUE(host_data_source);
        EXPECT_EQ("mysql", host_data_source->getType());
    });

    EXPECT_FALSE(HostMgr::instance().getIPReservationsUnique());
}

}  // namespace