summaryrefslogtreecommitdiffstats
path: root/src/bin/netconf/tests/get_config_unittest.cc
blob: 8948c5ef8fc38b1784335aae69f898dddea252f8 (plain)
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
// Copyright (C) 2018-2022 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 <gtest/gtest.h>

#include <cc/command_interpreter.h>
#include <cc/data.h>
#include <netconf/netconf_cfg_mgr.h>
#include <netconf/parser_context.h>
#include <process/testutils/d_test_stubs.h>
#include <testutils/gtest_utils.h>
#include <testutils/user_context_utils.h>

#include <fstream>
#include <iostream>
#include <string>

#include "test_data_files_config.h"
#include "test_libraries.h"

using namespace isc::netconf;
using namespace isc::config;
using namespace isc::data;
using namespace isc::process;
using namespace isc::test;

namespace {

/// @name How to generate the testdata/get_config.json file
///
/// Define GENERATE_ACTION and recompile. Run netconf_unittests on
/// NetconfGetCfgTest redirecting the standard error to a temporary
/// file, e.g. by
/// @code
///    ./netconf_unittests --gtest_filter="NetconfGetCfg*" > /dev/null 2> u
/// @endcode
///
/// Update testdata/get_config.json using the temporary file content,
/// (removing head comment and restoring hook library path),
/// recompile without GENERATE_ACTION.

/// @brief the generate action
/// false means do nothing, true means unparse extracted configurations
#ifdef GENERATE_ACTION
const bool generate_action = true;
#else
const bool generate_action = false;
#endif

/// @brief Read a file into a string
string
readFile(const string& file_path) {
    ifstream ifs(file_path);
    if (!ifs.is_open()) {
        ADD_FAILURE() << "readFile cannot open " << file_path;
        isc_throw(isc::Unexpected, "readFile cannot open " << file_path);
    }
    string lines;
    string line;
    while (getline(ifs, line)) {
        lines += line + "\n";
    }
    ifs.close();
    return (lines);
}

/// @brief Runs parser in JSON mode
ElementPtr
parseJSON(const string& in, bool verbose = false) {
    try {
        ParserContext ctx;
        return (ctx.parseString(in, ParserContext::PARSER_JSON));
    } catch (exception const& ex) {
        if (verbose) {
            cout << "EXCEPTION: " << ex.what() << endl;
        }
        throw;
    }
}

/// @brief Runs parser in NETCONF mode
ElementPtr
parseNETCONF(const string& in, bool verbose = false) {
    try {
        ParserContext ctx;
        return (ctx.parseString(in, ParserContext::PARSER_NETCONF));
    } catch (exception const& ex) {
        if (verbose) {
            cout << "EXCEPTION: " << ex.what() << endl;
        }
        throw;
    }
}

/// @brief Replace the library path
void
pathReplacer(ConstElementPtr netconf_cfg) {
    ConstElementPtr hooks_libs = netconf_cfg->get("hooks-libraries");
    if (!hooks_libs || hooks_libs->empty()) {
        return;
    }
    ElementPtr first_lib = hooks_libs->getNonConst(0);
    string lib_path(BASIC_CALLOUT_LIBRARY);
    first_lib->set("library", Element::create(lib_path));
}

/// @brief Almost regular netconf CfgMgr with internal parse method exposed.
class NakedNetconfCfgMgr : public NetconfCfgMgr {
public:
    using NetconfCfgMgr::parse;
};  // NakedNetconfCfgMgr

}  // namespace

/// @brief Test fixture class
class NetconfGetCfgTest : public ConfigParseTest {
public:
    NetconfGetCfgTest()
    : rcode_(-1) {
        srv_.reset(new NakedNetconfCfgMgr());
        // Create fresh context.
        resetConfiguration();
    }

    ~NetconfGetCfgTest() {
        resetConfiguration();
    }

    /// @brief Parse and Execute configuration
    ///
    /// Parses a configuration and executes a configuration of the server.
    /// If the operation fails, the current test will register a failure.
    ///
    /// @param config Configuration to parse
    /// @param operation Operation being performed.  In the case of an error,
    ///        the error text will include the string "unable to <operation>.".
    ///
    /// @return true if the configuration succeeded, false if not.
    bool
    executeConfiguration(const string& config, const char* operation) {
        // try JSON parser
        ConstElementPtr json;
        try {
            json = parseJSON(config, true);
        } catch (exception const& ex) {
            ADD_FAILURE() << "invalid JSON for " << operation
                          << " failed with " << ex.what()
                          << " on\n" << config << "\n";
            return (false);
        }

        // try NETCONF parser
        try {
            json = parseNETCONF(config, true);
        } catch (...) {
            ADD_FAILURE() << "parsing failed for " << operation
                          << " on\n" << prettyPrint(json) << "\n";
            return (false);
        }

        // get Netconf element
        ConstElementPtr ca = json->get("Netconf");
        if (!ca) {
            ADD_FAILURE() << "cannot get Netconf for " << operation
                          << " on\n" << prettyPrint(json) << "\n";
            return (false);
        }

        // update hooks-libraries
        pathReplacer(ca);

        // try NETCONF configure
        ConstElementPtr status;
        try {
            status = srv_->parse(ca, true);
        } catch (exception const& ex) {
            ADD_FAILURE() << "configure for " << operation
                          << " failed with " << ex.what()
                          << " on\n" << prettyPrint(json) << "\n";
            return (false);
        }

        // The status object must not be NULL
        if (!status) {
            ADD_FAILURE() << "configure for " << operation
                          << " returned null on\n"
                          << prettyPrint(json) << "\n";
            return (false);
        }

        // Returned value should be 0 (configuration success)
        comment_ = parseAnswer(rcode_, status);
        if (rcode_ != 0) {
            string reason = "";
            if (comment_) {
                reason = string(" (") + comment_->stringValue() + string(")");
            }
            ADD_FAILURE() << "configure for " << operation
                          << " returned error code "
                          << rcode_ << reason << " on\n"
                          << prettyPrint(json) << "\n";
            return (false);
        }
        return (true);
    }

    /// @brief Reset configuration database.
    ///
    /// This function resets configuration data base by
    /// removing managed servers and hooks. Reset must
    /// be performed after each test to make sure that
    /// contents of the database do not affect result of
    /// subsequent tests.
    void resetConfiguration() {
        string config = "{ \"Netconf\": { } }";
        EXPECT_TRUE(executeConfiguration(config, "reset config"));
    }

    unique_ptr<NakedNetconfCfgMgr> srv_; ///< Netconf server under test
    int rcode_;                       ///< Return code from element parsing
    ConstElementPtr comment_;         ///< Reason for parse fail
};  // NetconfGetCfgTest

// Test a simple configuration.
TEST_F(NetconfGetCfgTest, simple) {

    // get the simple configuration
    string simple_file = string(CFG_EXAMPLES) + "/" + "simple-dhcp4.json";
    string config;
    ASSERT_NO_THROW_LOG(config = readFile(simple_file));

    // get the expected configuration
    string expected_file =
        string(NETCONF_TEST_DATA_DIR) + "/" + "get_config.json";
    string expected;
    ASSERT_NO_THROW_LOG(expected = readFile(expected_file));

    // execute the sample configuration
    ASSERT_TRUE(executeConfiguration(config, "simple config"));

    // unparse it
    NetconfConfigPtr context = srv_->getNetconfConfig();
    ConstElementPtr unparsed;
    ASSERT_NO_THROW_LOG(unparsed = context->toElement());

    // dump if wanted else check
    if (generate_action) {
        cerr << "// Generated Configuration (remove this line)\n";
        ASSERT_NO_THROW_LOG(expected = prettyPrint(unparsed));
        prettyPrint(unparsed, cerr, 0, 4);
        cerr << "\n";
    } else {
        // get the expected config using the netconf syntax parser
        ElementPtr jsond;
        ASSERT_NO_THROW_LOG(jsond = parseNETCONF(expected, true));
        // get the expected config using the generic JSON syntax parser
        ElementPtr jsonj;
        ASSERT_NO_THROW_LOG(jsonj = parseJSON(expected));
        // the generic JSON parser does not handle comments
        EXPECT_TRUE(isEquivalent(jsond, moveComments(jsonj)));
        // replace the path by its actual value
        ConstElementPtr ca;
        ASSERT_NO_THROW_LOG(ca = jsonj->get("Netconf"));
        ASSERT_TRUE(ca);
        pathReplacer(ca);
        // check that unparsed and updated expected values match
        EXPECT_TRUE(isEquivalent(unparsed, jsonj));
        // check on pretty prints too
        string current = prettyPrint(unparsed, 0, 4);
        string expected2 = prettyPrint(jsonj, 0, 4);
        EXPECT_EQ(expected2, current);
        if (expected2 != current) {
            expected = current + "\n";
        }
    }

    // execute the netconft configuration
    EXPECT_TRUE(executeConfiguration(expected, "unparsed config"));

    // is it a fixed point?
    NetconfConfigPtr context2 = srv_->getNetconfConfig();
    ConstElementPtr unparsed2;
    ASSERT_NO_THROW_LOG(unparsed2 = context2->toElement());
    ASSERT_TRUE(unparsed2);
    EXPECT_TRUE(isEquivalent(unparsed, unparsed2));
}