Skip to content

Commit

Permalink
test: add unit tests for peerlog config parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
guseggert committed Aug 25, 2021
1 parent a35dd2e commit c3ac1b4
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 17 deletions.
38 changes: 21 additions & 17 deletions plugin/plugins/peerlog/peerlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
49 changes: 49 additions & 0 deletions plugin/plugins/peerlog/peerlog_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit c3ac1b4

Please sign in to comment.