From c3ac1b4282d2c6af36da5ead8dab2e96113865ef Mon Sep 17 00:00:00 2001 From: guseggert <877588+guseggert@users.noreply.github.com> Date: Tue, 24 Aug 2021 14:05:51 -0400 Subject: [PATCH] test: add unit tests for peerlog config parsing --- plugin/plugins/peerlog/peerlog.go | 38 +++++++++++--------- plugin/plugins/peerlog/peerlog_test.go | 49 ++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 17 deletions(-) create mode 100644 plugin/plugins/peerlog/peerlog_test.go diff --git a/plugin/plugins/peerlog/peerlog.go b/plugin/plugins/peerlog/peerlog.go index 33fb26372..685e179a9 100644 --- a/plugin/plugins/peerlog/peerlog.go +++ b/plugin/plugins/peerlog/peerlog.go @@ -67,26 +67,30 @@ func (*peerLogPlugin) Version() string { return "0.1.0" } +func extractEnabled(config interface{}) bool { + // plugin is disabled by default, unless Enabled=true + if config == nil { + return false + } + mapIface, ok := config.(map[string]interface{}) + if !ok { + return false + } + enabledIface, ok := mapIface["Enabled"] + if !ok || enabledIface == nil { + return false + } + enabled, ok := enabledIface.(bool) + if !ok { + return false + } + return enabled +} + // Init initializes plugin func (pl *peerLogPlugin) Init(env *plugin.Environment) error { pl.events = make(chan plEvent, eventQueueSize) - - // plugin is disabled by default, unless Enabled=true - if env.Config != nil { - mapIface, ok := env.Config.(map[string]interface{}) - if !ok { - return nil - } - enabledIface, ok := mapIface["Enabled"] - if !ok || enabledIface == nil { - return nil - } - enabled, ok := enabledIface.(bool) - if !ok { - return nil - } - pl.enabled = enabled - } + pl.enabled = extractEnabled(env.Config) return nil } diff --git a/plugin/plugins/peerlog/peerlog_test.go b/plugin/plugins/peerlog/peerlog_test.go new file mode 100644 index 000000000..b5ab6d6ad --- /dev/null +++ b/plugin/plugins/peerlog/peerlog_test.go @@ -0,0 +1,49 @@ +package peerlog + +import "testing" + +func TestExtractEnabled(t *testing.T) { + for _, c := range []struct { + name string + config interface{} + expected bool + }{ + { + name: "nil config returns false", + config: nil, + expected: false, + }, + { + name: "returns false when config is not a string map", + config: 1, + expected: false, + }, + { + name: "returns false when config has no Enabled field", + config: map[string]interface{}{}, + expected: false, + }, + { + name: "returns false when config has a null Enabled field", + config: map[string]interface{}{"Enabled": nil}, + expected: false, + }, + { + name: "returns false when config has a non-boolean Enabled field", + config: map[string]interface{}{"Enabled": 1}, + expected: false, + }, + { + name: "returns the vlaue of the Enabled field", + config: map[string]interface{}{"Enabled": true}, + expected: true, + }, + } { + t.Run(c.name, func(t *testing.T) { + isEnabled := extractEnabled(c.config) + if isEnabled != c.expected { + t.Fatalf("expected %v, got %v", c.expected, isEnabled) + } + }) + } +}