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

#include <config.h>
#include <cc/data.h>
#include <cc/json_feed.h>
#include <gtest/gtest.h><--- 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.

using namespace isc::config;
using namespace isc::data;

namespace {

/// @brief Test fixture class for @ref JSONFeed class.
class JSONFeedTest : public ::testing::Test {
public:

    /// @brief Constructor.
    ///
    /// Initializes @ref json_map_ and @ref json_list_ which hold reference
    /// JSON structures.
    JSONFeedTest()
        : json_map_(), json_list_() {
        ElementPtr m = Element::fromJSON(createJSON());
        ElementPtr l = Element::createList();
        l->add(m);
        json_map_ = m;
        json_list_ = l;
    }

    /// @brief Creates a JSON map holding 20 elements.
    ///
    /// Each map value is a list of 20 elements.
    std::string createJSON() const {
        // Create a list of 20 elements.
        ElementPtr list_element = Element::createList();
        for (unsigned i = 0; i < 20; ++i) {
            std::ostringstream s;
            s << "list_element" << i;
            list_element->add(Element::create(s.str()));
        }

        // Create a map of 20 elements. Each map element holds a list
        // of 20 elements.
        ElementPtr map_element = Element::createMap();
        for (unsigned i = 0; i < 20; ++i) {
            std::ostringstream s;
            s << "map_element" << i;
            map_element->set(s.str(), list_element);
        }

        return (prettyPrint(map_element));
    }

    /// @brief Test that the JSONFeed correctly recognizes the beginning
    /// and the end of the JSON structure.
    ///
    /// @param input_json A string holding an input JSON structure.
    /// @param expected_output A structure holding expected output from the
    /// @ref JSONFeed::toElement.
    void testRead(const std::string& input_json,
                  const ConstElementPtr& expected_output) {
        JSONFeed feed;
        ASSERT_NO_THROW(feed.initModel());

        // Post the data into the feed in 10 bytes long chunks.
        size_t chunk = 10;

        for (size_t i = 0; i < input_json.size(); i += chunk) {
            bool done = false;
            // When we're near the end of the data stream, the chunk length may
            // vary.
            if (i + chunk >= input_json.size()) {
                chunk = input_json.size() - i;
                done = true;
            }
            // Feed the parser with a data chunk and parse it.
            feed.postBuffer(&input_json[i], chunk);
            feed.poll();
            if (!done) {
                ASSERT_TRUE(feed.needData());
            }
        }

        // Convert parsed/collected data in the feed into the structure of
        // elements.
        ConstElementPtr element_from_feed = feed.toElement();
        EXPECT_TRUE(element_from_feed->equals(*expected_output));
    }

    /// @brief Test that the JSONFeed correctly recognizes the beginning
    /// and the end of the JSON structure.
    ///
    /// @param input_json A string holding an input JSON structure.
    /// @param expected_output A string holding expected output from the
    /// @ref JSONFeed::getProcessedText.
    void testRead(const std::string& input_json,
                  const std::string& expected_output) {
        JSONFeed feed;
        ASSERT_NO_THROW(feed.initModel());

        // Post the data into the feed in 10 bytes long chunks.
        size_t chunk = 10;

        for (size_t i = 0; i < input_json.size(); i += chunk) {
            bool done = false;
            // When we're near the end of the data stream, the chunk length may
            // vary.
            if (i + chunk >= input_json.size()) {
                chunk = input_json.size() - i;
                done = true;
            }
            // Feed the parser with a data chunk and parse it.
            feed.postBuffer(&input_json[i], chunk);
            feed.poll();
            if (!done) {
                ASSERT_TRUE(feed.needData());
            }
        }

        EXPECT_EQ(expected_output, feed.getProcessedText());
    }

    /// @brief Test that the @ref JSONFeed signals an error when the input
    /// string holds invalid data.
    ///
    /// @param input_json A string holding an input JSON structure.
    /// @param err_msg A string holding an expected error message.
    void testInvalidRead(const std::string& input_json,
                         const std::string& err_msg) {
        JSONFeed feed;
        ASSERT_NO_THROW(feed.initModel());

        ASSERT_NO_THROW(feed.postBuffer(&input_json[0], input_json.size()));
        ASSERT_NO_THROW(feed.poll());

        EXPECT_FALSE(feed.needData());
        EXPECT_FALSE(feed.feedOk());

        EXPECT_EQ(err_msg, feed.getErrorMessage());
    }

    /// @brief JSON map holding a number of lists.
    ConstElementPtr json_map_;

    /// @brief JSON list holding a map of lists.
    ConstElementPtr json_list_;

};

// This test verifies that toElement should not be called before
// the feed detects the end of the data stream.
TEST_F(JSONFeedTest, toElementTooSoon) {<--- syntax error
    JSONFeed feed;
    ASSERT_NO_THROW(feed.initModel());
    std::string json = "{\n";
    feed.postBuffer(&json[0], json.size());
    feed.poll();
    EXPECT_TRUE(feed.needData());
    EXPECT_THROW(feed.toElement(), JSONFeedError);
}

// This test verifies that toElement checks JSON syntax as a side effect.
TEST_F(JSONFeedTest, badJSON) {
    JSONFeed feed;
    ASSERT_NO_THROW(feed.initModel());
    std::string json = "{\n]\n";
    feed.postBuffer(&json[0], json.size());
    feed.poll();
    EXPECT_FALSE(feed.needData());
    EXPECT_THROW(feed.toElement(), JSONFeedError);
}

// This test verifies that a JSON structure starting with '{' is accepted
// and parsed.
TEST_F(JSONFeedTest, startWithBrace) {
    std::string json = createJSON();
    testRead(json, json_map_);
}

// This test verifies that a JSON structure starting with '[' is accepted
// and parsed.
TEST_F(JSONFeedTest, startWithSquareBracket) {
    std::string json = createJSON();
    json = std::string("[") + json + std::string("]");
    testRead(json, json_list_);
}

// This test verifies that input JSON can be preceded with whitespaces.
TEST_F(JSONFeedTest, startWithWhitespace) {
    std::string json = createJSON();
    json = std::string("  \r\r\t  ") + json;
    testRead(json, json_map_);
}

// This test verifies that an empty map is accepted and parsed.
TEST_F(JSONFeedTest, emptyMap) {
    std::string json = "{}";
    testRead(json, Element::createMap());
}

// This test verifies that an empty list is accepted and parsed.
TEST_F(JSONFeedTest, emptyList) {
    std::string json = "[  ]";
    testRead(json, Element::createList());
}

// This test verifies that an error is signalled when a JSON structure
// is preceded by invalid character.
TEST_F(JSONFeedTest, unexpectedFirstCharacter) {
    std::string json = "a {}";
    std::string err_msg = "invalid first character a";
    testInvalidRead(json, err_msg);
}

// This test verifies that an error is signalled when a JSON structure
// is preceded by white spaces and an invalid character.
TEST_F(JSONFeedTest, unexpectedCharacter) {
    std::string json = " a {}";
    std::string err_msg = "invalid character a";
    testInvalidRead(json, err_msg);
}

// This test verifies that an error is signalled when the JSON structure
// begins by a string.
TEST_F(JSONFeedTest, stringFirst) {
    std::string json = "\"foo\"";
    std::string err_msg = "invalid first character \"";
    testInvalidRead(json, err_msg);
}

// This test verifies that an error is signalled when the JSON structure
// begins by white spaces followed by a string.
TEST_F(JSONFeedTest, stringBefore) {
    std::string json = " \"foo\"";
    std::string err_msg = "invalid character \"";
    testInvalidRead(json, err_msg);
}

// This test verifies that an error is signalled when a JSON structure
// lacks an opening brace character.
TEST_F(JSONFeedTest, noOpeningBrace) {
    std::string json = "\"x\": \"y\" }";
    std::string err_msg = "invalid first character \"";
    testInvalidRead(json, err_msg);
}

// This test verifies that an error is signalled when a JSON structure
// lacks an opening square bracket.
TEST_F(JSONFeedTest, noOpeningSquareBracket) {
    std::string json = "1, 2 ]";
    std::string err_msg = "invalid first character 1";
    testInvalidRead(json, err_msg);
}

// This test verifies that a string is correctly handled
TEST_F(JSONFeedTest, string) {
    std::string json = "{ \"braces\": \"}}}}\" }";
    ElementPtr expected = Element::createMap();
    expected->set("braces", Element::create("}}}}"));
    testRead(json, expected);
}

// This test verifies that a string with escapes is correctly handled
TEST_F(JSONFeedTest, escape) {
    std::string json = "{ \"escapes\": \"\\n\\t\\\"\\\\\" }";
    ElementPtr expected = Element::createMap();
    expected->set("escapes", Element::create("\n\t\"\\"));
    testRead(json, expected);
}

// This test verifies that white spaces before JSON are ignored.
TEST_F(JSONFeedTest, whiteSpaceBefore) {
    std::string json = " \n  [ ]\n";
    std::string expected = "[ ]";
    testRead(json, expected);
}

// This test verifies that bash style comments before JSON are ignored.
TEST_F(JSONFeedTest, bashCommentBefore) {
    std::string json = "# ahah\n  # foo\"bar\n{ }\n";
    std::string expected = "{ }";
    testRead(json, expected);
}

// This test verifies that C++ style comments before JSON are ignored.
TEST_F(JSONFeedTest, cppCommentBefore) {
    std::string json = "// ahah\n  // foo\"bar\n[ 12 ]\n";
    std::string expected = "[ 12 ]";
    testRead(json, expected);
}

// This test verifies that multi-line comments before JSON are ignored.
TEST_F(JSONFeedTest, multiLineCommentBefore) {
    std::string json = "/* ahah\n \"// foo*bar**/\n { \"foo\": \"bar\" }\n";
    std::string expected = "{ \"foo\": \"bar\" }";
    testRead(json, expected);
}

// This test verifies that an error is signalled when a slash does not
// begin a C++ or C style comment before JSON.
TEST_F(JSONFeedTest, badCommentBefore) {
    std::string json = "/# foo\n [ ]\n";
    std::string err_msg = "invalid characters /#";
    testInvalidRead(json, err_msg);
}

// This test verifies that bash style comments are ignored.
TEST_F(JSONFeedTest, bashComments) {
    std::string json = "{ # ahah\n \"foo\": # value?\n \"bar\" }";
    std::string expected = "{ \n \"foo\": \n \"bar\" }";
    testRead(json, expected);
}

// This test verifies that C++ style comments are ignored.
TEST_F(JSONFeedTest, cppComments) {
    std::string json = "[ // ahah\n \"foo\", /// value?\n \"bar\" ]";
    std::string expected = "[ \n \"foo\", \n \"bar\" ]";
    testRead(json, expected);
}

// This test verifies that multi-line comments are ignored.
TEST_F(JSONFeedTest, multiLineComments) {
    std::string json = "{ /* ahah\n \"// foo*bar**/\n \"foo\": \"bar\" }\n";
    std::string expected = "{ \n\n \"foo\": \"bar\" }";
    testRead(json, expected);
}

// This test verifies that an error is signalled a slash does not begin
// a C++ or C style comment.
TEST_F(JSONFeedTest, badComment) {
    std::string json = "[ /# foo\n ]\n";
    std::string err_msg = "invalid characters /#";
    testInvalidRead(json, err_msg);
}

// This test verifies that trailing garbage is ignored.
TEST_F(JSONFeedTest, trailing) {
    JSONFeed feed;
    ASSERT_NO_THROW(feed.initModel());
    std::string json = "[ 1, 2] 3, 4]";
    feed.postBuffer(&json[0], json.size());
    feed.poll();
    EXPECT_FALSE(feed.needData());
    EXPECT_TRUE(feed.feedOk());
    std::string expected = "[ 1, 2]";
    EXPECT_EQ(expected, feed.getProcessedText());
}

// Example from DHCPv4 unit tests.
TEST_F(JSONFeedTest, bashComment4) {
    JSONFeed feed;
    ASSERT_NO_THROW(feed.initModel());
    std::string json = "{ \"Dhcp4\": { \"interfaces-config\": {"
        "  \"interfaces\": [ \"*\" ]"
        "},\n"
        "# this is a comment\n"
        "\"rebind-timer\": 2000, \n"
        "# lots of comments here\n"
        "# and here\n"
        "\"renew-timer\": 1000, \n"
        "\"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ],"
        "    \"subnet\": \"192.0.2.0/24\", "
        "    \"id\": 1, "
        "    \"interface\": \"eth0\""
        " } ],"
        "\"valid-lifetime\": 4000 } }";
    feed.postBuffer(&json[0], json.size());
    feed.poll();
    EXPECT_FALSE(feed.needData());
    EXPECT_TRUE(feed.feedOk());
    EXPECT_NO_THROW(feed.toElement());
}

// Example from DHCPv4 unit tests.
TEST_F(JSONFeedTest, bashCommentsInline4) {
    JSONFeed feed;
    ASSERT_NO_THROW(feed.initModel());
    std::string json = "{ \"Dhcp4\": { \"interfaces-config\": {"
        "  \"interfaces\": [ \"*\" ]"
        "},\n"
        "\"rebind-timer\": 2000, # everything after # is ignored\n"
        "\"renew-timer\": 1000, # this will be ignored, too\n"
        "\"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ],"
        "    \"subnet\": \"192.0.2.0/24\", "
        "    \"id\": 1, "
        "    \"interface\": \"eth0\""
        " } ],"
        "\"valid-lifetime\": 4000 } }";
    feed.postBuffer(&json[0], json.size());
    feed.poll();
    EXPECT_FALSE(feed.needData());
    EXPECT_TRUE(feed.feedOk());
    EXPECT_NO_THROW(feed.toElement());
}

// Example from DHCPv6 unit tests.
TEST_F(JSONFeedTest, cppComments6) {
    JSONFeed feed;
    ASSERT_NO_THROW(feed.initModel());
    std::string json = "{ \"Dhcp6\": { \"interfaces-config\": {"
        "  \"interfaces\": [ \"*\" ]"
        "},\n"
        "\"preferred-lifetime\": 3000, // this is a comment \n"
        "\"rebind-timer\": 2000, // everything after // is ignored\n"
        "\"renew-timer\": 1000, // this will be ignored, too\n"
        "\"subnet6\": [ { "
        "    \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ],"
        "    \"subnet\": \"2001:db8:1::/48\", "
        "    \"id\": 1, "
        "    \"interface\": \"eth0\""
        " } ],"
        "\"valid-lifetime\": 4000 } }";
    feed.postBuffer(&json[0], json.size());
    feed.poll();
    EXPECT_FALSE(feed.needData());
    EXPECT_TRUE(feed.feedOk());
    EXPECT_NO_THROW(feed.toElement());
}

// Example from DHCPv6 unit tests.
TEST_F(JSONFeedTest, multilineComments6) {
    JSONFeed feed;
    ASSERT_NO_THROW(feed.initModel());
    std::string json = "{ \"Dhcp6\": { \"interfaces-config\": {"
        "  \"interfaces\": [ \"*\" ]"
        "},\n"
        "\"preferred-lifetime\": 3000, /* this is a C style comment\n"
        "that\n can \n span \n multiple \n lines */ \n"
        "\"rebind-timer\": 2000,\n"
        "\"renew-timer\": 1000, \n"
        "\"subnet6\": [ { "
        "    \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ],"
        "    \"subnet\": \"2001:db8:1::/48\", "
        "    \"id\": 1, "
        "    \"interface\": \"eth0\""
        " } ],"
        "\"valid-lifetime\": 4000 } }";
    feed.postBuffer(&json[0], json.size());
    feed.poll();
    EXPECT_FALSE(feed.needData());
    EXPECT_TRUE(feed.feedOk());
    EXPECT_NO_THROW(feed.toElement());
}

} // end of anonymous namespace.