test: add unit tests for peerlog config parsing

This commit is contained in:
guseggert 2021-08-24 14:05:51 -04:00 committed by Gus Eggert
parent a35dd2ea0d
commit c3ac1b4282
2 changed files with 70 additions and 17 deletions

View File

@ -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
}

View File

@ -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)
}
})
}
}