dhcp_parsers_unittest.cc 56 KB
Newer Older
1
// Copyright (C) 2012-2014 Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include <config.h>
#include <config/ccsession.h>
17
#include <cc/data.h>
18 19 20
#include <dhcp/option.h>
#include <dhcp/option_custom.h>
#include <dhcp/option_int.h>
21
#include <dhcpsrv/cfgmgr.h>
22 23
#include <dhcpsrv/subnet.h>
#include <dhcpsrv/dhcp_parsers.h>
Stephen Morris's avatar
Stephen Morris committed
24
#include <dhcpsrv/tests/test_libraries.h>
25
#include <exceptions/exceptions.h>
26
#include <hooks/hooks_manager.h>
27 28 29

#include <gtest/gtest.h>
#include <boost/foreach.hpp>
30
#include <boost/pointer_cast.hpp>
31 32 33 34 35 36 37

#include <map>
#include <string>

using namespace std;
using namespace isc;
using namespace isc::config;
38 39 40
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::hooks;
41 42 43 44 45 46 47 48 49

namespace {

/// @brief DHCP Parser test fixture class
class DhcpParserTest : public ::testing::Test {
public:
    /// @brief Constructor
    ///
    DhcpParserTest() {
50
        CfgMgr::instance().deleteActiveIfaces();
51 52 53 54 55
    }
};


/// @brief Check BooleanParser basic functionality.
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
/// Verifies that the parser:
/// 1. Does not allow empty for storage.
/// 2. Rejects a non-boolean element.
/// 3. Builds with a valid true value.
/// 4. Bbuils with a valid false value.
/// 5. Updates storage upon commit.
TEST_F(DhcpParserTest, booleanParserTest) {

    const std::string name = "boolParm";

    // Verify that parser does not allow empty for storage.
    BooleanStoragePtr bs;
    EXPECT_THROW(BooleanParser(name, bs), isc::dhcp::DhcpConfigError);

    // Construct parser for testing.
    BooleanStoragePtr storage(new BooleanStorage());
    BooleanParser parser(name, storage);

    // Verify that parser with rejects a non-boolean element.
    ElementPtr wrong_element = Element::create("I am a string");
    EXPECT_THROW(parser.build(wrong_element), isc::BadValue);

    // Verify that parser will build with a valid true value.
    bool test_value = true;
    ElementPtr element = Element::create(test_value);
    ASSERT_NO_THROW(parser.build(element));

    // Verify that commit updates storage.
85
    bool actual_value = !test_value;
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    parser.commit();
    EXPECT_NO_THROW((actual_value = storage->getParam(name)));
    EXPECT_EQ(test_value, actual_value);

    // Verify that parser will build with a valid false value.
    test_value = false;
    element->setValue(test_value);
    EXPECT_NO_THROW(parser.build(element));

    // Verify that commit updates storage.
    actual_value = ~test_value;
    parser.commit();
    EXPECT_NO_THROW((actual_value = storage->getParam(name)));
    EXPECT_EQ(test_value, actual_value);
}

/// @brief Check StringParser basic functionality
103
///
104 105
/// Verifies that the parser:
/// 1. Does not allow empty for storage.
106
/// 2. Builds with a nont string value.
107 108 109 110 111 112 113 114 115 116 117 118 119 120
/// 3. Builds with a string value.
/// 4. Updates storage upon commit.
TEST_F(DhcpParserTest, stringParserTest) {

    const std::string name = "strParm";

    // Verify that parser does not allow empty for storage.
    StringStoragePtr bs;
    EXPECT_THROW(StringParser(name, bs), isc::dhcp::DhcpConfigError);

    // Construct parser for testing.
    StringStoragePtr storage(new StringStorage());
    StringParser parser(name, storage);

121 122 123
    // Verify that parser with accepts a non-string element.
    ElementPtr element = Element::create(9999);
    EXPECT_NO_THROW(parser.build(element));
124

125 126 127 128 129 130
    // Verify that commit updates storage.
    parser.commit();
    std::string actual_value;
    EXPECT_NO_THROW((actual_value = storage->getParam(name)));
    EXPECT_EQ("9999", actual_value);

131 132
    // Verify that parser will build with a string value.
    const std::string test_value = "test value";
133
    element = Element::create(test_value);
134 135 136 137 138 139 140 141 142
    ASSERT_NO_THROW(parser.build(element));

    // Verify that commit updates storage.
    parser.commit();
    EXPECT_NO_THROW((actual_value = storage->getParam(name)));
    EXPECT_EQ(test_value, actual_value);
}

/// @brief Check Uint32Parser basic functionality
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
/// Verifies that the parser:
/// 1. Does not allow empty for storage.
/// 2. Rejects a non-integer element.
/// 3. Rejects a negative value.
/// 4. Rejects too large a value.
/// 5. Builds with value of zero.
/// 6. Builds with a value greater than zero.
/// 7. Updates storage upon commit.
TEST_F(DhcpParserTest, uint32ParserTest) {

    const std::string name = "intParm";

    // Verify that parser does not allow empty for storage.
    Uint32StoragePtr bs;
    EXPECT_THROW(Uint32Parser(name, bs), isc::dhcp::DhcpConfigError);

    // Construct parser for testing.
    Uint32StoragePtr storage(new Uint32Storage());
    Uint32Parser parser(name, storage);

    // Verify that parser with rejects a non-interger element.
    ElementPtr wrong_element = Element::create("I am a string");
    EXPECT_THROW(parser.build(wrong_element), isc::BadValue);

    // Verify that parser with rejects a negative value.
    ElementPtr int_element = Element::create(-1);
    EXPECT_THROW(parser.build(int_element), isc::BadValue);

172 173
    // Verify that parser with rejects too large a value provided we are on
    // 64-bit platform.
174 175 176 177 178
    if (sizeof(long) > sizeof(uint32_t)) {
        long max = (long)(std::numeric_limits<uint32_t>::max()) + 1;
        int_element->setValue(max);
        EXPECT_THROW(parser.build(int_element), isc::BadValue);
    }
179 180 181 182 183 184

    // Verify that parser will build with value of zero.
    int test_value = 0;
    int_element->setValue((long)test_value);
    ASSERT_NO_THROW(parser.build(int_element));

185 186 187 188 189 190
    // Verify that commit updates storage.
    parser.commit();
    uint32_t actual_value = 0;
    EXPECT_NO_THROW((actual_value = storage->getParam(name)));
    EXPECT_EQ(test_value, actual_value);

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    // Verify that parser will build with a valid positive value.
    test_value = 77;
    int_element->setValue((long)test_value);
    ASSERT_NO_THROW(parser.build(int_element));

    // Verify that commit updates storage.
    parser.commit();
    EXPECT_NO_THROW((actual_value = storage->getParam(name)));
    EXPECT_EQ(test_value, actual_value);
}

/// @brief Check InterfaceListParser  basic functionality
///
/// Verifies that the parser:
/// 1. Does not allow empty for storage.
206 207
/// 2. Does not allow name other than "interfaces"
/// 3. Parses list of interfaces and adds them to CfgMgr
208 209
/// 4. Parses wildcard interface name and sets a CfgMgr flag which indicates
/// that server will listen on all interfaces.
210 211
TEST_F(DhcpParserTest, interfaceListParserTest) {

212
    const std::string name = "interfaces";
213 214 215 216

    // Verify that parser constructor fails if parameter name isn't "interface"
    EXPECT_THROW(InterfaceListConfigParser("bogus_name"), isc::BadValue);

217 218
    boost::scoped_ptr<InterfaceListConfigParser>
        parser(new InterfaceListConfigParser(name));
219 220 221
    ElementPtr list_element = Element::createList();
    list_element->add(Element::create("eth0"));
    list_element->add(Element::create("eth1"));
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

    // Make sure there are no interfaces added yet.
    ASSERT_FALSE(CfgMgr::instance().isActiveIface("eth0"));
    ASSERT_FALSE(CfgMgr::instance().isActiveIface("eth1"));

    // This should parse the configuration and add eth0 and eth1 to the list
    // of interfaces that server should listen on.
    parser->build(list_element);
    parser->commit();

    // Use CfgMgr instance to check if eth0 and eth1 was added, and that
    // eth2 was not added.
    CfgMgr& cfg_mgr = CfgMgr::instance();
    EXPECT_TRUE(cfg_mgr.isActiveIface("eth0"));
    EXPECT_TRUE(cfg_mgr.isActiveIface("eth1"));
    EXPECT_FALSE(cfg_mgr.isActiveIface("eth2"));

    // Add keyword all to the configuration. This should activate all
    // interfaces, including eth2, even though it has not been explicitly
    // added.
242
    list_element->add(Element::create("*"));
243 244 245 246 247 248 249 250 251

    // Reset parser's state.
    parser.reset(new InterfaceListConfigParser(name));
    parser->build(list_element);
    parser->commit();

    EXPECT_TRUE(cfg_mgr.isActiveIface("eth0"));
    EXPECT_TRUE(cfg_mgr.isActiveIface("eth1"));
    EXPECT_TRUE(cfg_mgr.isActiveIface("eth2"));
252 253
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
254 255 256 257 258 259 260 261 262 263
// Checks whether option space can be detected as vendor-id
TEST_F(DhcpParserTest, vendorOptionSpace) {
    EXPECT_EQ(0, SubnetConfigParser::optionSpaceToVendorId(""));
    EXPECT_EQ(0, SubnetConfigParser::optionSpaceToVendorId("dhcp4"));
    EXPECT_EQ(0, SubnetConfigParser::optionSpaceToVendorId("vendor-"));
    EXPECT_EQ(1, SubnetConfigParser::optionSpaceToVendorId("vendor-1"));
    EXPECT_EQ(4491, SubnetConfigParser::optionSpaceToVendorId("vendor-4491"));
    EXPECT_EQ(12345678, SubnetConfigParser::optionSpaceToVendorId("vendor-12345678"));
}

264
/// @brief Test Implementation of abstract OptionDataParser class. Allows
265
/// testing basic option parsing.
266 267 268
class UtestOptionDataParser : public OptionDataParser {
public:

269 270
    UtestOptionDataParser(const std::string&,
        OptionStoragePtr options, ParserContextPtr global_context)
271 272 273 274 275 276 277 278 279 280 281 282 283
        :OptionDataParser("", options, global_context) {
    }

    static OptionDataParser* factory(const std::string& param_name,
        OptionStoragePtr options, ParserContextPtr global_context) {
        return (new UtestOptionDataParser(param_name, options, global_context));
    }

protected:
    // Dummy out last two params since test derivation doesn't use them.
    virtual OptionDefinitionPtr findServerSpaceOptionDefinition (
                std::string&, uint32_t) {
        OptionDefinitionPtr def;
284
        // always return empty
285 286 287 288
        return (def);
    }
};

289
/// @brief Test Fixture class which provides basic structure for testing
290 291 292 293 294 295 296 297 298
/// configuration parsing.  This is essentially the same structure provided
/// by dhcp servers.
class ParseConfigTest : public ::testing::Test {
public:
    /// @brief Constructor
    ParseConfigTest() {
        reset_context();
    }

299 300 301 302
    ~ParseConfigTest() {
        reset_context();
    }

303
    /// @brief Parses a configuration.
304 305
    ///
    /// Parse the given configuration, populating the context storage with
306 307
    /// the parsed elements.
    ///
308 309 310
    /// @param config_set is the set of elements to parse.
    /// @return returns an ConstElementPtr containing the numeric result
    /// code and outcome comment.
311
    isc::data::ConstElementPtr parseElementSet(isc::data::ConstElementPtr
312 313 314 315 316 317 318 319 320 321 322 323 324 325
                                           config_set) {
        // Answer will hold the result.
        ConstElementPtr answer;
        if (!config_set) {
            answer = isc::config::createAnswer(1,
                                 string("Can't parse NULL config"));
            return (answer);
        }

        // option parsing must be done last, so save it if we hit if first
        ParserPtr option_parser;

        ConfigPair config_pair;
        try {
326
            // Iterate over the config elements.
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
            const std::map<std::string, ConstElementPtr>& values_map =
                                                      config_set->mapValue();
            BOOST_FOREACH(config_pair, values_map) {
                // Create the parser based on element name.
                ParserPtr parser(createConfigParser(config_pair.first));
                // Options must be parsed last
                if (config_pair.first == "option-data") {
                    option_parser = parser;
                } else {
                    // Anything else  we can call build straight away.
                    parser->build(config_pair.second);
                    parser->commit();
                }
            }

            // The option values parser is the next one to be run.
343
            std::map<std::string, ConstElementPtr>::const_iterator
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
                                option_config = values_map.find("option-data");
            if (option_config != values_map.end()) {
                option_parser->build(option_config->second);
                option_parser->commit();
            }

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

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

        return (answer);
    }

    /// @brief Create an element parser based on the element name.
    ///
366 367 368 369 370
    /// Creates a parser for the appropriate element and stores a pointer to it
    /// in the appropriate class variable.
    ///
    /// Note that the method currently it only supports option-defs, option-data
    /// and hooks-libraries.
371 372
    ///
    /// @param config_id is the name of the configuration element.
373 374 375
    ///
    /// @return returns a shared pointer to DhcpConfigParser.
    ///
376
    /// @throw throws NotImplemented if element name isn't supported.
377 378
    ParserPtr createConfigParser(const std::string& config_id) {
        ParserPtr parser;
379
        if (config_id.compare("option-data") == 0) {
380 381
            parser.reset(new OptionDataListParser(config_id,
                                              parser_context_->options_,
382 383 384
                                              parser_context_,
                                              UtestOptionDataParser::factory));

385
        } else if (config_id.compare("option-def") == 0) {
386
            parser.reset(new OptionDefListParser(config_id,
387
                                                 parser_context_));
388 389 390 391 392

        } else if (config_id.compare("hooks-libraries") == 0) {
            parser.reset(new HooksLibrariesParser(config_id));
            hooks_libraries_parser_ =
                boost::dynamic_pointer_cast<HooksLibrariesParser>(parser);
393 394
        } else if (config_id.compare("dhcp-ddns") == 0) {
            parser.reset(new D2ClientConfigParser(config_id));
395 396 397 398 399 400 401 402 403
        } else {
            isc_throw(NotImplemented,
                "Parser error: configuration parameter not supported: "
                << config_id);
        }

        return (parser);
    }

404 405
    /// @brief Convenience method for parsing a configuration
    ///
406
    /// Given a configuration string, convert it into Elements
407
    /// and parse them.
408 409
    /// @param config is the configuration string to parse
    ///
410
    /// @return retuns 0 if the configuration parsed successfully,
411
    /// non-zero otherwise failure.
412
    int parseConfiguration(const std::string& config) {
413 414 415 416 417 418 419
        int rcode_ = 1;
        // Turn config into elements.
        // Test json just to make sure its valid.
        ElementPtr json = Element::fromJSON(config);
        EXPECT_TRUE(json);
        if (json) {
            ConstElementPtr status = parseElementSet(json);
420 421
            ConstElementPtr comment = parseAnswer(rcode_, status);
            error_text_ = comment->stringValue();
422 423 424 425 426
        }

        return (rcode_);
    }

427
    /// @brief Find an option definition for a given space and code within
428 429 430 431 432
    /// the parser context.
    /// @param space is the space name of the desired option.
    /// @param code is the numeric "type" of the desired option.
    /// @return returns an OptionDefinitionPtr which points to the found
    /// definition or is empty.
433
    /// ASSERT_ tests don't work inside functions that return values
434 435 436
    OptionDefinitionPtr getOptionDef(std::string space, uint32_t code)
    {
        OptionDefinitionPtr def;
437
        OptionDefContainerPtr defs =
438 439 440 441 442 443 444 445 446 447 448 449 450
                            parser_context_->option_defs_->getItems(space);
        // Should always be able to get definitions list even if it is empty.
        EXPECT_TRUE(defs);
        if (defs) {
            // Attempt to find desired definiton.
            const OptionDefContainerTypeIndex& idx = defs->get<1>();
            const OptionDefContainerTypeRange& range = idx.equal_range(code);
            int cnt = std::distance(range.first, range.second);
            EXPECT_EQ(1, cnt);
            if (cnt == 1) {
                def = *(idx.begin());
            }
        }
451
        return (def);
452 453
    }

454
    /// @brief Find an option for a given space and code within the parser
455 456 457 458 459
    /// context.
    /// @param space is the space name of the desired option.
    /// @param code is the numeric "type" of the desired option.
    /// @return returns an OptionPtr which points to the found
    /// option or is empty.
460
    /// ASSERT_ tests don't work inside functions that return values
461 462 463
    OptionPtr getOptionPtr(std::string space, uint32_t code)
    {
        OptionPtr option_ptr;
464
        Subnet::OptionContainerPtr options =
465 466 467 468 469 470
                            parser_context_->options_->getItems(space);
        // Should always be able to get options list even if it is empty.
        EXPECT_TRUE(options);
        if (options) {
            // Attempt to find desired option.
            const Subnet::OptionContainerTypeIndex& idx = options->get<1>();
471
            const Subnet::OptionContainerTypeRange& range =
472 473 474 475
                                                        idx.equal_range(code);
            int cnt = std::distance(range.first, range.second);
            EXPECT_EQ(1, cnt);
            if (cnt == 1) {
476 477
                Subnet::OptionDescriptor desc = *(idx.begin());
                option_ptr = desc.option;
478 479 480 481
                EXPECT_TRUE(option_ptr);
            }
        }

482
        return (option_ptr);
483 484
    }

485
    /// @brief Wipes the contents of the context to allowing another parsing
486 487 488
    /// during a given test if needed.
    void reset_context(){
        // Note set context universe to V6 as it has to be something.
489 490 491
        CfgMgr::instance().deleteSubnets4();
        CfgMgr::instance().deleteSubnets6();
        CfgMgr::instance().deleteOptionDefs();
492
        parser_context_.reset(new ParserContext(Option::V6));
493 494 495

        // Ensure no hooks libraries are loaded.
        HooksManager::unloadLibraries();
496 497 498 499

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

502 503 504 505 506
    /// @brief Parsers used in the parsing of the configuration
    ///
    /// Allows the tests to interrogate the state of the parsers (if required).
    boost::shared_ptr<HooksLibrariesParser> hooks_libraries_parser_;

507 508
    /// @brief Parser context - provides storage for options and definitions
    ParserContextPtr parser_context_;
509 510 511

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

/// @brief Check Basic parsing of option definitions.
515
///
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
/// Note that this tests basic operation of the OptionDefinitionListParser and
/// OptionDefinitionParser.  It uses a simple configuration consisting of one
/// one definition and verifies that it is parsed and committed to storage
/// correctly.
TEST_F(ParseConfigTest, basicOptionDefTest) {

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

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

539

540
    // Verify that the option definition can be retrieved.
541
    OptionDefinitionPtr def = getOptionDef("isc", 100);
542 543 544 545 546 547 548 549 550 551 552
    ASSERT_TRUE(def);

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

/// @brief Check Basic parsing of options.
553
///
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
/// Note that this tests basic operation of the OptionDataListParser and
/// OptionDataParser.  It uses a simple configuration consisting of one
/// one definition and matching option data.  It verifies that the option
/// is parsed and committed to storage correctly.
TEST_F(ParseConfigTest, basicOptionDataTest) {

    // Configuration string.
    std::string config =
        "{ \"option-def\": [ {"
        "      \"name\": \"foo\","
        "      \"code\": 100,"
        "      \"type\": \"ipv4-address\","
        "      \"array\": False,"
        "      \"record-types\": \"\","
        "      \"space\": \"isc\","
        "      \"encapsulate\": \"\""
        " } ], "
        " \"option-data\": [ {"
        "    \"name\": \"foo\","
        "    \"space\": \"isc\","
        "    \"code\": 100,"
575
        "    \"data\": \"192.0.2.0\","
576 577 578 579 580 581 582 583 584 585 586 587 588 589
        "    \"csv-format\": True"
        " } ]"
        "}";

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

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

    // Verify that the option definition is correct.
    std::string val = "type=100, len=4, data fields:\n "
590
                      " #0 192.0.2.0 ( ipv4-address ) \n";
591 592 593 594 595 596

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

};  // Anonymous namespace

Stephen Morris's avatar
Stephen Morris committed
597 598
/// These tests check basic operation of the HooksLibrariesParser.

599 600
// hooks-libraries that do not contain anything.
TEST_F(ParseConfigTest, noHooksLibrariesTest) {
Stephen Morris's avatar
Stephen Morris committed
601

602 603
    // Configuration with hooks-libraries not present.
    string config = "{ \"hooks-libraries\": [] }";
Stephen Morris's avatar
Stephen Morris committed
604 605 606

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
607 608 609 610 611 612 613 614 615 616 617 618
    ASSERT_TRUE(rcode == 0) << error_text_;

    // Check that the parser recorded no change to the current state
    // (as the test starts with no hooks libraries loaded).
    std::vector<std::string> libraries;
    bool changed;
    hooks_libraries_parser_->getLibraries(libraries, changed);
    EXPECT_TRUE(libraries.empty());
    EXPECT_FALSE(changed);

    // Load a single library and repeat the parse.
    vector<string> basic_library;
619
    basic_library.push_back(string(CALLOUT_LIBRARY_1));
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    HooksManager::loadLibraries(basic_library);

    rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;

    // This time the change should have been recorded.
    hooks_libraries_parser_->getLibraries(libraries, changed);
    EXPECT_TRUE(libraries.empty());
    EXPECT_TRUE(changed);

    // But repeating it again and we are back to no change.
    rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;
    hooks_libraries_parser_->getLibraries(libraries, changed);
    EXPECT_TRUE(libraries.empty());
    EXPECT_FALSE(changed);
Stephen Morris's avatar
Stephen Morris committed
636 637 638 639

}


640
TEST_F(ParseConfigTest, validHooksLibrariesTest) {
Stephen Morris's avatar
Stephen Morris committed
641

642
    // Configuration string.  This contains a set of valid libraries.
Stephen Morris's avatar
Stephen Morris committed
643 644 645 646 647
    const std::string quote("\"");
    const std::string comma(", ");

    const std::string config =
        std::string("{ ") +
648
            std::string("\"hooks-libraries\": [") +
649 650
                quote + std::string(CALLOUT_LIBRARY_1) + quote + comma +
                quote + std::string(CALLOUT_LIBRARY_2)  + quote +
Stephen Morris's avatar
Stephen Morris committed
651 652 653 654 655
            std::string("]") +
        std::string("}");

    // Verify that the configuration string parses.
    int rcode = parseConfiguration(config);
656
    ASSERT_TRUE(rcode == 0) << error_text_;
Stephen Morris's avatar
Stephen Morris committed
657

658 659 660 661 662 663 664
    // Check that the parser holds two libraries and the configuration is
    // recorded as having changed.
    std::vector<std::string> libraries;
    bool changed;
    hooks_libraries_parser_->getLibraries(libraries, changed);
    EXPECT_EQ(2, libraries.size());
    EXPECT_TRUE(changed);
Stephen Morris's avatar
Stephen Morris committed
665 666 667 668

    // The expected libraries should be the list of libraries specified
    // in the given order.
    std::vector<std::string> expected;
669 670
    expected.push_back(CALLOUT_LIBRARY_1);
    expected.push_back(CALLOUT_LIBRARY_2);
671 672 673 674 675
    EXPECT_TRUE(expected == libraries);

    // Parse the string again.
    rcode = parseConfiguration(config);
    ASSERT_TRUE(rcode == 0) << error_text_;
Stephen Morris's avatar
Stephen Morris committed
676

677 678 679 680
    // The list has not changed, and this is what we should see.
    hooks_libraries_parser_->getLibraries(libraries, changed);
    EXPECT_EQ(2, libraries.size());
    EXPECT_FALSE(changed);
Stephen Morris's avatar
Stephen Morris committed
681 682
}

683
// Check with a set of libraries, some of which are invalid.
Stephen Morris's avatar
Stephen Morris committed
684 685
TEST_F(ParseConfigTest, invalidHooksLibrariesTest) {

686
    /// @todo Initialize global library context to null
Stephen Morris's avatar
Stephen Morris committed
687 688 689 690 691 692 693 694

    // Configuration string.  This contains an invalid library which should
    // trigger an error in the "build" stage.
    const std::string quote("\"");
    const std::string comma(", ");

    const std::string config =
        std::string("{ ") +
695
            std::string("\"hooks-libraries\": [") +
696
                quote + std::string(CALLOUT_LIBRARY_1) + quote + comma +
Stephen Morris's avatar
Stephen Morris committed
697
                quote + std::string(NOT_PRESENT_LIBRARY) + quote + comma +
698
                quote + std::string(CALLOUT_LIBRARY_2)  + quote +
Stephen Morris's avatar
Stephen Morris committed
699 700 701
            std::string("]") +
        std::string("}");

702 703
    // Verify that the configuration fails to parse. (Syntactically it's OK,
    // but the library is invalid).
Stephen Morris's avatar
Stephen Morris committed
704
    int rcode = parseConfiguration(config);
705
    ASSERT_FALSE(rcode == 0) << error_text_;
Stephen Morris's avatar
Stephen Morris committed
706

707 708 709
    // Check that the message contains the library in error.
    EXPECT_FALSE(error_text_.find(NOT_PRESENT_LIBRARY) == string::npos) <<
        "Error text returned from parse failure is " << error_text_;
Stephen Morris's avatar
Stephen Morris committed
710
}
711

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

715
    // Configuration string containing valid values.
716 717 718 719
    std::string config_str =
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
720
        "     \"server-ip\" : \"192.0.2.0\", "
721
        "     \"server-port\" : 3432, "
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\", "
        "     \"always-include-fqdn\" : true, "
        "     \"override-no-update\" : true, "
        "     \"override-client-update\" : true, "
        "     \"replace-client-name\" : true, "
        "     \"generated-prefix\" : \"test.prefix\", "
        "     \"qualifying-suffix\" : \"test.suffix.\" "
        "    }"
        "}";

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

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

    // Verify that the configuration values are as expected.
    EXPECT_TRUE(d2_client_config->getEnableUpdates());
745
    EXPECT_EQ("192.0.2.0", d2_client_config->getServerIp().toText());
746
    EXPECT_EQ(3432, d2_client_config->getServerPort());
747 748 749 750 751 752 753 754
    EXPECT_EQ(dhcp_ddns::NCR_UDP, d2_client_config->getNcrProtocol());
    EXPECT_EQ(dhcp_ddns::FMT_JSON, d2_client_config->getNcrFormat());
    EXPECT_TRUE(d2_client_config->getAlwaysIncludeFqdn());
    EXPECT_TRUE(d2_client_config->getOverrideNoUpdate());
    EXPECT_TRUE(d2_client_config->getOverrideClientUpdate());
    EXPECT_TRUE(d2_client_config->getReplaceClientName());
    EXPECT_EQ("test.prefix", d2_client_config->getGeneratedPrefix());
    EXPECT_EQ("test.suffix.", d2_client_config->getQualifyingSuffix());
755 756

    // Another valid Configuration string.
757
    // This one is disabled, has IPV6 server ip, control flags false,
758 759 760 761
    // empty prefix/suffix
    std::string config_str2 =
        "{ \"dhcp-ddns\" :"
        "    {"
762
        "     \"enable-updates\" : false, "
763
        "     \"server-ip\" : \"2001:db8::\", "
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        "     \"server-port\" : 43567, "
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\", "
        "     \"always-include-fqdn\" : false, "
        "     \"override-no-update\" : false, "
        "     \"override-client-update\" : false, "
        "     \"replace-client-name\" : false, "
        "     \"generated-prefix\" : \"\", "
        "     \"qualifying-suffix\" : \"\" "
        "    }"
        "}";

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

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

    // Verify that the configuration values are as expected.
786
    EXPECT_FALSE(d2_client_config->getEnableUpdates());
787
    EXPECT_EQ("2001:db8::", d2_client_config->getServerIp().toText());
788 789 790 791 792 793 794 795 796
    EXPECT_EQ(43567, d2_client_config->getServerPort());
    EXPECT_EQ(dhcp_ddns::NCR_UDP, d2_client_config->getNcrProtocol());
    EXPECT_EQ(dhcp_ddns::FMT_JSON, d2_client_config->getNcrFormat());
    EXPECT_FALSE(d2_client_config->getAlwaysIncludeFqdn());
    EXPECT_FALSE(d2_client_config->getOverrideNoUpdate());
    EXPECT_FALSE(d2_client_config->getOverrideClientUpdate());
    EXPECT_FALSE(d2_client_config->getReplaceClientName());
    EXPECT_EQ("", d2_client_config->getGeneratedPrefix());
    EXPECT_EQ("", d2_client_config->getQualifyingSuffix());
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
}

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

    // Configuration string.  This contains a set of valid libraries.
    std::string config_str =
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : false"
        "    }"
        "}";

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

    // Verify that DHCP-DDNS is disabled.
816
    EXPECT_FALSE(CfgMgr::instance().ddnsEnabled());
817 818 819 820 821 822 823 824

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

825 826 827 828 829 830
/// @brief Checks that given a partial configuration, parser supplies
/// default values
TEST_F(ParseConfigTest, parserDefaultsD2Config) {

    // Configuration string.  This contains a set of valid libraries.
    std::string config_str =
831 832 833 834
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true"
        "    }"
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
        "}";

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

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

    // Make sure fetched config is correct.
    D2ClientConfigPtr d2_client_config;
    ASSERT_NO_THROW(d2_client_config = CfgMgr::instance().getD2ClientConfig());
    EXPECT_TRUE(d2_client_config);
    EXPECT_TRUE(d2_client_config->getEnableUpdates());
    EXPECT_EQ(D2ClientConfig::DFT_SERVER_IP,
              d2_client_config->getServerIp().toText());
    EXPECT_EQ(D2ClientConfig::DFT_SERVER_PORT,
              d2_client_config->getServerPort());
    EXPECT_EQ(dhcp_ddns::stringToNcrProtocol(D2ClientConfig::DFT_NCR_PROTOCOL),
              d2_client_config->getNcrProtocol());
    EXPECT_EQ(dhcp_ddns::stringToNcrFormat(D2ClientConfig::DFT_NCR_FORMAT),
              d2_client_config->getNcrFormat());
857 858
    EXPECT_EQ(D2ClientConfig::DFT_ALWAYS_INCLUDE_FQDN,
              d2_client_config->getAlwaysIncludeFqdn());
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
    EXPECT_EQ(D2ClientConfig::DFT_OVERRIDE_NO_UPDATE,
              d2_client_config->getOverrideNoUpdate());
    EXPECT_EQ(D2ClientConfig::DFT_OVERRIDE_CLIENT_UPDATE,
              d2_client_config->getOverrideClientUpdate());
    EXPECT_EQ(D2ClientConfig::DFT_REPLACE_CLIENT_NAME,
              d2_client_config->getReplaceClientName());
    EXPECT_EQ(D2ClientConfig::DFT_GENERATED_PREFIX,
              d2_client_config->getGeneratedPrefix());
    EXPECT_EQ(D2ClientConfig::DFT_QUALIFYING_SUFFIX,
              d2_client_config->getQualifyingSuffix());
}


/// @brief Check various invalid D2 client configurations.
TEST_F(ParseConfigTest, invalidD2Config) {
    std::string invalid_configs[] = {
        // Must supply at lease enable-updates
876 877 878 879 880 881 882 883
        "{ \"dhcp-ddns\" :"
        "    {"
        "    }"
        "}",
        // Invalid server ip value
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
884
        "     \"server-ip\" : \"x192.0.2.0\", "
885
        "     \"server-port\" : 53001, "
886 887 888 889 890 891 892 893 894 895 896 897 898 899
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\", "
        "     \"always-include-fqdn\" : true, "
        "     \"override-no-update\" : true, "
        "     \"override-client-update\" : true, "
        "     \"replace-client-name\" : true, "
        "     \"generated-prefix\" : \"test.prefix\", "
        "     \"qualifying-suffix\" : \"test.suffix.\" "
        "    }"
        "}",
        // Unknown protocol
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
900
        "     \"server-ip\" : \"192.0.2.0\", "
901
        "     \"server-port\" : 53001, "
902 903 904 905 906 907 908 909 910 911 912 913 914 915
        "     \"ncr-protocol\" : \"Bogus\", "
        "     \"ncr-format\" : \"JSON\", "
        "     \"always-include-fqdn\" : true, "
        "     \"override-no-update\" : true, "
        "     \"override-client-update\" : true, "
        "     \"replace-client-name\" : true, "
        "     \"generated-prefix\" : \"test.prefix\", "
        "     \"qualifying-suffix\" : \"test.suffix.\" "
        "    }"
        "}",
        // Unsupported protocol
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
916
        "     \"server-ip\" : \"192.0.2.0\", "
917
        "     \"server-port\" : 53001, "
918 919 920 921 922 923 924 925 926 927 928 929 930 931
        "     \"ncr-protocol\" : \"TCP\", "
        "     \"ncr-format\" : \"JSON\", "
        "     \"always-include-fqdn\" : true, "
        "     \"override-no-update\" : true, "
        "     \"override-client-update\" : true, "
        "     \"replace-client-name\" : true, "
        "     \"generated-prefix\" : \"test.prefix\", "
        "     \"qualifying-suffix\" : \"test.suffix.\" "
        "    }"
        "}",
        // Unknown format
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
932
        "     \"server-ip\" : \"192.0.2.0\", "
933
        "     \"server-port\" : 53001, "
934 935 936 937 938 939 940 941 942 943
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"Bogus\", "
        "     \"always-include-fqdn\" : true, "
        "     \"override-no-update\" : true, "
        "     \"override-client-update\" : true, "
        "     \"replace-client-name\" : true, "
        "     \"generated-prefix\" : \"test.prefix\", "
        "     \"qualifying-suffix\" : \"test.suffix.\" "
        "    }"
        "}",
944
        // Invalid Port
945 946 947
        "{ \"dhcp-ddns\" :"
        "    {"
        "     \"enable-updates\" : true, "
948
        "     \"server-ip\" : \"192.0.2.0\", "
949
        "     \"server-port\" : \"bogus\", "
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
        "     \"ncr-protocol\" : \"UDP\", "
        "     \"ncr-format\" : \"JSON\", "
        "     \"always-include-fqdn\" : true, "
        "     \"override-no-update\" : true, "
        "     \"override-client-update\" : true, "
        "     \"replace-client-name\" : true, "
        "     \"generated-prefix\" : \"test.prefix\", "
        "     \"qualifying-suffix\" : \"test.suffix.\" "
        "    }"
        "}",
        // stop
        ""
    };

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

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

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

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

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
/// @brief DHCP Configuration Parser Context test fixture.
class ParserContextTest : public ::testing::Test {
public:
    /// @brief Constructor
    ParserContextTest() { }

    /// @brief Check that the storages of the specific type hold the
    /// same value.
    ///
    /// This function assumes that the ref_values storage holds exactly
    /// one parameter called 'foo'.
    ///
    /// @param ref_values A storage holding reference value. In the typical
    /// case it is a storage held in the original context, which is assigned
    /// to another context.
    /// @param values A storage holding value to be checked.
    /// @tparam ContainerType A type of the storage.
    /// @tparam ValueType A type of the value in the container.
    template<typename ContainerType, typename ValueType>
    void checkValueEq(const boost::shared_ptr<ContainerType>& ref_values,
                      const boost::shared_ptr<ContainerType>& values) {
1009 1010
        ASSERT_NO_THROW(values->getParam("foo"));
        EXPECT_EQ(ref_values->getParam("foo"), values->getParam("foo"));
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
    /// @brief Check that the storages of the specific type hold the same
    /// position.
    ///
    /// This function assumes that the @c ref_values storage holds exactly
    /// one parameter called 'foo'.
    ///
    /// @param ref_values A storage holding reference position. In the typical
    /// case it is a storage held in the original context, which is assigned
    /// to another context.
    /// @param values A storage holding position to be checked.
    /// @tparam ContainerType A type of the storage.
    /// @tparam ValueType A type of the value in the container.
    template<typename ContainerType, typename ValueType>
    void checkPositionEq(const boost::shared_ptr<ContainerType>& ref_values,
                         const boost::shared_ptr<ContainerType>& values) {
        // Verify that the position is correct.
        EXPECT_EQ(ref_values->getPosition("foo").line_,
                  values->getPosition("foo").line_);

        EXPECT_EQ(ref_values->getPosition("foo").pos_,
                  values->getPosition("foo").pos_);

        EXPECT_EQ(ref_values->getPosition("foo").file_,
                  values->getPosition("foo").file_);
    }

1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
    /// @brief Check that the storages of the specific type hold different
    /// value.
    ///
    /// This function assumes that the ref_values storage holds exactly
    /// one parameter called 'foo'.
    ///
    /// @param ref_values A storage holding reference value. In the typical
    /// case it is a storage held in the original context, which is assigned
    /// to another context.
    /// @param values A storage holding value to be checked.
    /// @tparam ContainerType A type of the storage.
    /// @tparam ValueType A type of the value in the container.
    template<typename ContainerType, typename ValueType>
    void checkValueNeq(const boost::shared_ptr<ContainerType>& ref_values,
                       const boost::shared_ptr<ContainerType>& values) {
1054 1055
        ASSERT_NO_THROW(values->getParam("foo"));
        EXPECT_NE(ref_values->getParam("foo"), values->getParam("foo"));
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
    /// @brief Check that the storages of the specific type hold fifferent
    /// position.
    ///
    /// This function assumes that the ref_values storage holds exactly
    /// one parameter called 'foo'.
    ///
    /// @param ref_values A storage holding reference position. In the typical
    /// case it is a storage held in the original context, which is assigned
    /// to another context.
    /// @param values A storage holding position to be checked.
    /// @tparam ContainerType A type of the storage.
    /// @tparam ValueType A type of the value in the container.
    template<typename ContainerType, typename ValueType>
    void checkPositionNeq(const boost::shared_ptr<ContainerType>& ref_values,
                          const boost::shared_ptr<ContainerType>& values) {
        // At least one of the position fields must be different.
        EXPECT_TRUE((ref_values->getPosition("foo").line_ !=
                     values->getPosition("foo").line_) ||
                    (ref_values->getPosition("foo").pos_ !=
                     values->getPosition("foo").pos_) ||
                    (ref_values->getPosition("foo").pos_ !=
                     values->getPosition("foo").pos_));
    }

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
    /// @brief Check that option definition storage in the context holds
    /// one option definition of the specified type.
    ///
    /// @param ctx A pointer to a context.
    /// @param opt_type Expected option type.
    void checkOptionDefinitionType(const ParserContext& ctx,
                                   const uint16_t opt_type) {
        OptionDefContainerPtr opt_defs =
            ctx.option_defs_->getItems("option-space");
        ASSERT_TRUE(opt_defs);
        OptionDefContainerTypeIndex& idx = opt_defs->get<1>();
        OptionDefContainerTypeRange range = idx.equal_range(opt_type);
        EXPECT_EQ(1, std::distance(range.first, range.second));
    }

    /// @brief Check that option storage in the context holds one option
    /// of the specified type.
    ///
    /// @param ctx A pointer to a context.
    /// @param opt_type Expected option type.
    void checkOptionType(const ParserContext& ctx, const uint16_t opt_type) {
        Subnet::OptionContainerPtr options =
            ctx.options_->getItems("option-space");
        ASSERT_TRUE(options);
        Subnet::OptionContainerTypeIndex& idx = options->get<1>();
        Subnet::OptionContainerTypeRange range = idx.equal_range(opt_type);
        ASSERT_EQ(1, std::distance(range.first, range.second));
    }

    /// @brief Test copy constructor or assignment operator when values
    /// being copied are NULL.
    ///
    /// @param copy Indicates that copy constructor should be tested
    /// (if true), or assignment operator (if false).
    void testCopyAssignmentNull(const bool copy) {
        ParserContext ctx(Option::V6);
        // Release all pointers in the context.
        ctx.boolean_values_.reset();
        ctx.uint32_values_.reset();
        ctx.string_values_.reset();
        ctx.options_.reset();
        ctx.option_defs_.reset();
        ctx.hooks_libraries_.reset();

        // Even if the fields of the context are NULL, it should get
        // copied.
        ParserContextPtr ctx_new(new ParserContext(Option::V6));
        if (copy) {
            ASSERT_NO_THROW(ctx_new.reset(new ParserContext(ctx)));
        } else {
            *ctx_new = ctx;
        }

        // The resulting context has its fields equal to NULL.
        EXPECT_FALSE(ctx_new->boolean_values_);
        EXPECT_FALSE(ctx_new->uint32_values_);
        EXPECT_FALSE(ctx_new->string_values_);
        EXPECT_FALSE(ctx_new->options_);
        EXPECT_FALSE(ctx_new->option_defs_);
        EXPECT_FALSE(ctx_new->hooks_libraries_);

    }

    /// @brief Test copy constructor or assignment operator.
    ///
    /// @param copy Indicates that copy constructor should be tested (if true),
    /// or assignment operator (if false).
    void testCopyAssignment(const bool copy) {
        // Create new context. It will be later copied/assigned to another
        // context.
        ParserContext ctx(Option::V6);

        // Set boolean parameter 'foo'.
        ASSERT_TRUE(ctx.boolean_values_);
1156 1157
        ctx.boolean_values_->setParam("foo", true,
                                      Element::Position("kea.conf", 123, 234));
1158 1159 1160

        // Set uint32 parameter 'foo'.
        ASSERT_TRUE(ctx.uint32_values_);
1161 1162
        ctx.uint32_values_->setParam("foo", 123,
                                     Element::Position("kea.conf", 123, 234));
1163 1164 1165

        // Ser string parameter 'foo'.
        ASSERT_TRUE(ctx.string_values_);
1166 1167
        ctx.string_values_->setParam("foo", "some string",
                                     Element::Position("kea.conf", 123, 234));
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

        // Add new option, with option code 10, to the context.
        ASSERT_TRUE(ctx.options_);
        OptionPtr opt1(new Option(Option::V6, 10));
        Subnet::OptionDescriptor desc1(opt1, false);
        std::string option_space = "option-space";
        ASSERT_TRUE(desc1.option);
        ctx.options_->addItem(desc1, option_space);

        // Add new option definition, with option code 123.
        OptionDefinitionPtr def1(new OptionDefinition("option-foo", 123,
                                                      "string"));
        ctx.option_defs_->addItem(def1, option_space);

        // Allocate container for hooks libraries and add one library name.
        ctx.hooks_libraries_.reset(new std::vector<std::string>());
        ctx.hooks_libraries_->push_back("library1");

        // We will use ctx_new to assign another context to it or copy
        // construct.
        ParserContextPtr ctx_new(new ParserContext(Option::V4));;
        if (copy) {
            ctx_new.reset(new ParserContext(ctx));
        } else {
            *ctx_new = ctx;
        }

        // New context has the same boolean value.
        ASSERT_TRUE(ctx_new->boolean_values_);
        {
            SCOPED_TRACE("Check that boolean values are equal in both"
                         " contexts");
            checkValueEq<BooleanStorage, bool>(ctx.boolean_values_,
                                               ctx_new->boolean_values_);
        }

1204 1205 1206 1207 1208 1209 1210 1211
        // New context has the same boolean value position.
        {
            SCOPED_TRACE("Check that positions of boolean values are equal"
                         " in both contexts");
            checkPositionEq<BooleanStorage, bool>(ctx.boolean_values_,
                                                  ctx_new->boolean_values_);
        }

1212 1213 1214 1215 1216 1217 1218 1219 1220
        // New context has the same uint32 value.
        ASSERT_TRUE(ctx_new->uint32_values_);
        {
            SCOPED_TRACE("Check that uint32_t values are equal in both"
                         " contexts");
            checkValueEq<Uint32Storage, uint32_t>(ctx.uint32_values_,
                                                  ctx_new->uint32_values_);
        }

1221 1222 1223 1224 1225 1226 1227 1228
        // New context has the same uint32 value position.
        {
            SCOPED_TRACE("Check that positions of uint32_t values are equal"
                         " in both contexts");
            checkPositionEq<Uint32Storage, uint32_t>(ctx.uint32_values_,
                                                     ctx_new->uint32_values_);
        }

1229 1230 1231 1232 1233 1234 1235 1236
        // New context has the same string value.
        ASSERT_TRUE(ctx_new->string_values_);
        {
            SCOPED_TRACE("Check that string values are equal in both contexts");
            checkValueEq<StringStorage, std::string>(ctx.string_values_,
                                                     ctx_new->string_values_);
        }

1237 1238 1239 1240 1241 1242 1243 1244
        // New context has the same string value position.
        {
            SCOPED_TRACE("Check that position of string values are equal"
                         " in both contexts");
            checkPositionEq<StringStorage, std::string>(ctx.string_values_,
                                                        ctx_new->string_values_);
        }

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
        // New context has the same option.
        ASSERT_TRUE(ctx_new->options_);
        {
            SCOPED_TRACE("Check that the option values are equal in both"
                         " contexts");
            checkOptionType(*ctx_new, 10);
        }

        // New context has the same option definition.
        ASSERT_TRUE(ctx_new->option_defs_);
        {
            SCOPED_TRACE("check that the option definition is equal in both"
                         " contexts");
            checkOptionDefinitionType(*ctx_new, 123);
        }

        // New context has the same hooks library.
        ASSERT_TRUE(ctx_new->hooks_libraries_);
        {
            ASSERT_EQ(1, ctx_new->hooks_libraries_->size());
            EXPECT_EQ("library1", (*ctx_new->hooks_libraries_)[0]);
        }

        // New context has the same universe.
        EXPECT_EQ(ctx.universe_, ctx_new->universe_);

        // Change the value of the boolean parameter. This should not affect the
        // corresponding value in the new context.
        {
1274 1275 1276 1277 1278
            SCOPED_TRACE("Check that boolean value and position isn't changed"
                         " when original value and position is changed");
            ctx.boolean_values_->setParam("foo", false,
                                          Element::Position("kea.conf",
                                                            12, 10));
1279 1280
            checkValueNeq<BooleanStorage, bool>(ctx.boolean_values_,
                                                ctx_new->boolean_values_);
1281 1282 1283

            checkPositionNeq<BooleanStorage, bool>(ctx.boolean_values_,
                                                   ctx_new->boolean_values_);
1284 1285 1286 1287 1288
        }

        // Change the value of the uint32_t parameter. This should not affect
        // the corresponding value in the new context.
        {
1289 1290 1291 1292 1293
            SCOPED_TRACE("Check that uint32_t value and position isn't changed"
                         " when original value and position is changed");