@cryptotaxi247 / kubo / commits / 8f623139c

test: add unit tests for peerlog config parsing

(cherry picked from commit c3ac1b4282d2c6af36da5ead8dab2e96113865ef)

guseggert committed Aug 24, 2021 at 14:05 UTC 8f623139c24d36f90e4665a0d08724d95e8a2f15
2 files changed +70 -17
plugin/plugins/peerlog/peerlog.go
+21 -17
@@ -67,26 +67,30 @@ func (*peerLogPlugin) Version() string {
67 return "0.1.0"
68 }
69
70 +func extractEnabled(config interface{}) bool {
71 + // plugin is disabled by default, unless Enabled=true
72 + if config == nil {
73 + return false
74 + }
75 + mapIface, ok := config.(map[string]interface{})
76 + if !ok {
77 + return false
78 + }
79 + enabledIface, ok := mapIface["Enabled"]
80 + if !ok || enabledIface == nil {
81 + return false
82 + }
83 + enabled, ok := enabledIface.(bool)
84 + if !ok {
85 + return false
86 + }
87 + return enabled
88 +}
89 +
90 // Init initializes plugin
91 func (pl *peerLogPlugin) Init(env *plugin.Environment) error {
92 pl.events = make(chan plEvent, eventQueueSize)
73 -
74 - // plugin is disabled by default, unless Enabled=true
75 - if env.Config != nil {
76 - mapIface, ok := env.Config.(map[string]interface{})
77 - if !ok {
78 - return nil
79 - }
80 - enabledIface, ok := mapIface["Enabled"]
81 - if !ok || enabledIface == nil {
82 - return nil
83 - }
84 - enabled, ok := enabledIface.(bool)
85 - if !ok {
86 - return nil
87 - }
88 - pl.enabled = enabled
89 - }
93 + pl.enabled = extractEnabled(env.Config)
94 return nil
95 }
96
plugin/plugins/peerlog/peerlog_test.go new
+49
@@ -0,0 +1,49 @@
1 +package peerlog
2 +
3 +import "testing"
4 +
5 +func TestExtractEnabled(t *testing.T) {
6 + for _, c := range []struct {
7 + name string
8 + config interface{}
9 + expected bool
10 + }{
11 + {
12 + name: "nil config returns false",
13 + config: nil,
14 + expected: false,
15 + },
16 + {
17 + name: "returns false when config is not a string map",
18 + config: 1,
19 + expected: false,
20 + },
21 + {
22 + name: "returns false when config has no Enabled field",
23 + config: map[string]interface{}{},
24 + expected: false,
25 + },
26 + {
27 + name: "returns false when config has a null Enabled field",
28 + config: map[string]interface{}{"Enabled": nil},
29 + expected: false,
30 + },
31 + {
32 + name: "returns false when config has a non-boolean Enabled field",
33 + config: map[string]interface{}{"Enabled": 1},
34 + expected: false,
35 + },
36 + {
37 + name: "returns the vlaue of the Enabled field",
38 + config: map[string]interface{}{"Enabled": true},
39 + expected: true,
40 + },
41 + } {
42 + t.Run(c.name, func(t *testing.T) {
43 + isEnabled := extractEnabled(c.config)
44 + if isEnabled != c.expected {
45 + t.Fatalf("expected %v, got %v", c.expected, isEnabled)
46 + }
47 + })
48 + }
49 +}