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
// Copyright (C) 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/.

/// @file This file contains tests which exercise the PerfMonConfig class.

#include <config.h>
#include <perfmon_config.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <dhcp/dhcp6.h>
#include <testutils/gtest_utils.h>

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

using namespace std;
using namespace isc;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::perfmon;

namespace {

/// @brief Test fixture for testing PerfMonConfig parsing of the
/// hook library's 'parameters' element.
class PerfMonConfigTest : public ::testing::Test {
public:
    /// @brief Constructor.
    explicit PerfMonConfigTest(uint16_t family) : family_(family) {
    }

    /// @brief Destructor.
    virtual ~PerfMonConfigTest() = default;

    /// @brief Verifies PerfMonConfig constructors and accessors.
    void testBasics() {
        PerfMonConfigPtr config;

        // Verify that an invalid family is caught.
        ASSERT_THROW_MSG(config.reset(new PerfMonConfig(777)), BadValue,
                         "PerfmonConfig: family must be AF_INET or AF_INET6");

        // Verify initial values.
        ASSERT_NO_THROW_LOG(config.reset(new PerfMonConfig(family_)));
        ASSERT_TRUE(config);
        EXPECT_FALSE(config->getEnableMonitoring());
        EXPECT_EQ(config->getIntervalWidthSecs(), 60);
        EXPECT_TRUE(config->getStatsMgrReporting());
        EXPECT_EQ(config->getAlarmReportSecs(), 300);
        EXPECT_TRUE(config->getAlarmStore());

        // Verify accessors.
        EXPECT_NO_THROW_LOG(config->setEnableMonitoring(true));
        EXPECT_TRUE(config->getEnableMonitoring());

        EXPECT_NO_THROW_LOG(config->setIntervalWidthSecs(4));
        EXPECT_EQ(config->getIntervalWidthSecs(), 4);

        EXPECT_NO_THROW_LOG(config->setStatsMgrReporting(false));
        EXPECT_FALSE(config->getStatsMgrReporting());

        EXPECT_NO_THROW_LOG(config->setAlarmReportSecs(120));
        EXPECT_EQ(config->getAlarmReportSecs(), 120);
    }

    /// @brief Exercises PerfMonConfig parameter parsing with valid configuration
    /// permutations.
    /// @todo add alarms
    void testValidScenarios() {
        // Describes a test scenario.
        struct Scenario {
            int line_;                          // Scenario line number
            std::string json_;                  // JSON configuration to parse
            bool exp_enable_monitoring_;        // Expected value for enable-monitoring
            uint32_t exp_interval_width_secs_;  // Expected value for interval-width-secs
            bool exp_stats_mgr_reporting_;      // Expected value for stats-mgr-reporting
            uint32_t exp_alarm_report_secs_;    // Expected value for alarm-report-secs
        };

        // List of test scenarios to run.
        list<Scenario> scenarios = {
            {
                // Empty map
                __LINE__,
                R"({ })",
                false, 60, true, 300
            },
            {
                // Only enable-monitoring",
                __LINE__,
                R"({ "enable-monitoring": true })",
                true, 60, true, 300
            },
            {
                // Only interval-width-secs",
                __LINE__,
                R"({ "interval-width-secs": 3 })",
                false, 3, true, 300
            },
            {
                // Only stats-mgr-reporting",
                __LINE__,
                R"({ "stats-mgr-reporting": false })",
                false, 60, false, 300
            },
            {
                // Only alarm-report-secs",
                __LINE__,
                R"({ "alarm-report-secs": 77 })",
                false, 60, true, 77
            },
            {
                // All parameters",
                __LINE__,
                R"(
                {
                    "enable-monitoring": true,
                    "interval-width-secs": 2,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 120
                })",
                true, 2, false, 120
            },
        };

        // Iterate over the scenarios.
        for (auto const& scenario : scenarios) {
            stringstream oss;
            oss << "scenario at line: " << scenario.line_;
            SCOPED_TRACE(oss.str());

            // Convert JSON texts to Element map.
            ConstElementPtr json_elements;
            ASSERT_NO_THROW_LOG(json_elements = Element::fromJSON(scenario.json_));

            // Parsing elements should succeed.
            PerfMonConfig config(family_);
            ASSERT_NO_THROW_LOG(config.parse(json_elements));

            // Verify expected values.
            EXPECT_EQ(config.getEnableMonitoring(), scenario.exp_enable_monitoring_);
            EXPECT_EQ(config.getIntervalWidthSecs(), scenario.exp_interval_width_secs_);
            EXPECT_EQ(config.getStatsMgrReporting(), scenario.exp_stats_mgr_reporting_);
            EXPECT_EQ(config.getAlarmReportSecs(), scenario.exp_alarm_report_secs_);
        }
    }

    /// @brief Exercises PerfMonConfig parameter parsing with invalid configuration
    /// permutations.  Duplicate alarms are tested elsewhere.
    void testInvalidScenarios() {
        // Describes a test scenario.
        struct Scenario {
            int line_;              // Scenario line number
            string json_;           // JSON configuration to parse
            string exp_message_;    // Expected exception message
        };

        // List of test scenarios to run.  Most scenario supply
        // all valid parameters except one in error.  This allows
        // us to verify that no values are changed if any are in error.
        list<Scenario> scenarios = {
            {
                // Unknown parameter
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 3,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 90,
                    "bogus": false
                })",
                "spurious 'bogus' parameter"
            },
            {
                // Invalid type for enable-monitoring
                __LINE__,
                R"(
                {
                    "enable-monitoring": "not bool",
                    "interval-width-secs": 3,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 90
                })",
                "'enable-monitoring' parameter is not a boolean"
            },
            {
                // Invalid type for interval-width-secs
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": "bogus",
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 90
                })",
                "'interval-width-secs' parameter is not an integer"
            },
            {
                // Value of interval-width-secs is zero
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 0,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 90
                })",
                "invalid interval-width-secs: '0', must be greater than 0"
            },
            {
                // Value of interval-width-secs less than zero
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": -2,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 90
                })",
                "invalid interval-width-secs: '-2', must be greater than 0"
            },
            {
                // Non-boolean type for stats-mgr-reporting
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 1,
                    "stats-mgr-reporting": "not bool",
                    "alarm-report-secs": 90
                })",
                "'stats-mgr-reporting' parameter is not a boolean"
            },
            {
                // Invalid type for alarm-report-secs
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 5,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": "bogus"
                })",
                "'alarm-report-secs' parameter is not an integer"
            },
            {
                // Value of alarm-report-secs is zero
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 1,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": -3
                })",
                "invalid alarm-report-secs: '-3', cannot be less than 0"
            },
            {
                // Value of alarm-report-secs less than zero
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 1,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": -3
                })",
                "invalid alarm-report-secs: '-3', cannot be less than 0"
            },
            {
                // Value for alarms is not a list.
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 60,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 90,
                    "alarms": {}
                })",
                "'alarms' parameter is not a list"
            },
            {
                // Alarms list contains an invalid entry
                __LINE__,
                R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 60,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 90,
                    "alarms": [{ "bogus": "alarm" }]
                })",
                "cannot add Alarm to store: spurious 'bogus' parameter"
            }
        };

        // Iterate over the scenarios.
        PerfMonConfig default_config(family_);
        for (auto const& scenario : scenarios) {
            stringstream oss;
            oss << "scenario at line: " << scenario.line_;
            SCOPED_TRACE(oss.str());

            // Convert JSON text to a map of parameters.
            ConstElementPtr json_elements;
            ASSERT_NO_THROW_LOG(json_elements = Element::fromJSON(scenario.json_));

            // Parsing parameters should throw.
            PerfMonConfig config(family_);
            ASSERT_THROW_MSG(config.parse(json_elements), DhcpConfigError,
                             scenario.exp_message_);

            // Original values should be intact.
            EXPECT_EQ(default_config.getEnableMonitoring(), config.getEnableMonitoring());
            EXPECT_EQ(default_config.getIntervalWidthSecs(), config.getIntervalWidthSecs());
            EXPECT_EQ(default_config.getStatsMgrReporting(), config.getStatsMgrReporting());
            EXPECT_EQ(default_config.getAlarmReportSecs(), config.getAlarmReportSecs());
        }
    }

    /// @brief Creates a valid configuration with a list of alarms.
    ///
    /// @parameter keys list of DurationKeyPtrs for alarms that should appear
    /// in the list.
    ///
    /// @return JSON text for the configuration.
    std::string makeConfigWithAlarms(std::vector<DurationKeyPtr> keys) {
        // Create valid configuration test which includes an arbitrary number of
        // family-specific alarms from a set of DurationKeys.
        stringstream joss;
        joss << R"(
                {
                    "enable-monitoring": false,
                    "interval-width-secs": 60,
                    "stats-mgr-reporting": false,
                    "alarm-report-secs": 90,
                    "alarms": [
                )";

        std::string comma = "";
        for (auto const& key : keys) {
            joss << comma << "\t{";
            joss << R"("duration-key": )";
            auto key_elems = DurationKeyParser::toElement(key);
            key_elems->toJSON(joss);
            joss << R"(,
                    "high-water-ms": 500,
                    "low-water-ms": 25
                    }
                )";

            comma = ",";
        }

        joss << "]}";
        return (joss.str());
    }

    /// @brief Verifies a valid configuration that includes a list of Alarms.
    void testValidAlarmsList() {
        // Create valid configuration test which includes an arbitrary number of
        // family-specific alarms from a pre-defined set of unique DurationKeys.
        std::string json_text = makeConfigWithAlarms(keys_);

        // Convert JSON text to a map of parameters.
        ConstElementPtr json_elements;
        ASSERT_NO_THROW_LOG(json_elements = Element::fromJSON(json_text));

        // Parsing parameters should throw.
        PerfMonConfig config(family_);
        ASSERT_NO_THROW_LOG(config.parse(json_elements));

        // Get all should retrieve the alarms in ascending order.
        AlarmCollectionPtr alarms = config.getAlarmStore()->getAll();
        ASSERT_EQ(alarms->size(), keys_.size());

        int idx = 0;
        for (auto const& d : *alarms) {
            EXPECT_EQ(*d, *keys_[idx]) << "failed on pass: " << idx;
            ++idx;
        }
    }

    /// @brief Verifies a valid configuration with a list duplicate Alarms.
    void testDuplicateAlarms() {
        std::vector<DurationKeyPtr> duplicate_keys;
        duplicate_keys.push_back(keys_[0]);
        duplicate_keys.push_back(keys_[0]);

        // Create valid configuration test which includes an arbitrary number of
        // family-specific alarms from a pre-defined set of unique DurationKeys.
        std::string json_text = makeConfigWithAlarms(duplicate_keys);

        // Convert JSON text to a map of parameters.
        ConstElementPtr json_elements;
        ASSERT_NO_THROW_LOG(json_elements = Element::fromJSON(json_text));

        // Parsing parameters should throw.
        PerfMonConfig config(family_);
        if (family_ == AF_INET) {
            ASSERT_THROW_MSG(config.parse(json_elements), DhcpConfigError,
                             "cannot add Alarm to store: AlarmStore::addAlarm:"
                             " alarm already exists for:"
                             " DHCPDISCOVER-DHCPOFFER.socket_received-buffer_read.0");
        } else {
            ASSERT_THROW_MSG(config.parse(json_elements), DhcpConfigError,
                             "cannot add Alarm to store: AlarmStore::addAlarm:"
                             " alarm already exists for:"
                             " SOLICIT-REPLY.socket_received-buffer_read.0");
        }
    }

    /// @brief Protocol family AF_INET or AF_INET6.
    uint16_t family_;

    /// @brief Collection of valid family-specific keys.
    std::vector<DurationKeyPtr> keys_;
};

/// @brief Test fixture for testing PerfMonConfig for DHCPV4.
class PerfMonConfigTest4: public PerfMonConfigTest {
public:
    /// @brief Constructor.
    explicit PerfMonConfigTest4() : PerfMonConfigTest(AF_INET) {
        for (int subnet = 0; subnet < 3; ++subnet) {
            DurationKeyPtr key(new DurationKey(AF_INET, DHCPDISCOVER, DHCPOFFER,
                                               "socket_received", "buffer_read", subnet));
            keys_.push_back(key);
        }
    }

    /// @brief Destructor.
    virtual ~PerfMonConfigTest4() = default;
};

/// @brief Test fixture for testing PerfMonConfig for DHCPV6.
class PerfMonConfigTest6: public PerfMonConfigTest {
public:
    /// @brief Constructor.
    explicit PerfMonConfigTest6() : PerfMonConfigTest(AF_INET6) {
        for (int subnet = 0; subnet < 3; ++subnet) {
            DurationKeyPtr key(new DurationKey(AF_INET6, DHCPV6_SOLICIT, DHCPV6_REPLY,
                                               "socket_received", "buffer_read", subnet));
            keys_.push_back(key);
        }
    }

    /// @brief Destructor.
    virtual ~PerfMonConfigTest6() = default;
};

TEST_F(PerfMonConfigTest4, basics) {<--- syntax error
    testBasics();
}

TEST_F(PerfMonConfigTest6, basics) {
    testBasics();
}

TEST_F(PerfMonConfigTest4, validScenarios) {
    testValidScenarios();
}

TEST_F(PerfMonConfigTest6, validScenarios) {
    testValidScenarios();
}

TEST_F(PerfMonConfigTest4, invalidScenarios) {
    testInvalidScenarios();
}

TEST_F(PerfMonConfigTest6, invalidScenarios) {
    testInvalidScenarios();
}

TEST_F(PerfMonConfigTest4, validAlarmsList) {
    testValidAlarmsList();
}

TEST_F(PerfMonConfigTest6, validAlarmsList) {
    testValidAlarmsList();
}

TEST_F(PerfMonConfigTest4, duplicateAlarms) {
    testDuplicateAlarms();
}

TEST_F(PerfMonConfigTest6, duplicateAlarms) {
    testDuplicateAlarms();
}

} // end of anonymous namespace