From b514d22f1ec142cf0d2964733e3abb57eb29d551 Mon Sep 17 00:00:00 2001 From: Sam Coe Date: Tue, 29 Jun 2021 13:59:51 -0700 Subject: [PATCH] Fix issue in FindEntry that causes extensions and alias crash --- internal/config/config_map.go | 13 ++++-- internal/config/config_map_test.go | 65 ++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 4 deletions(-) create mode 100644 internal/config/config_map_test.go diff --git a/internal/config/config_map.go b/internal/config/config_map.go index f6b25fcb6..8afaf3a4c 100644 --- a/internal/config/config_map.go +++ b/internal/config/config_map.go @@ -68,13 +68,18 @@ func (cm *ConfigMap) FindEntry(key string) (ce *ConfigEntry, err error) { ce = &ConfigEntry{} - topLevelKeys := cm.Root.Content - for i, v := range topLevelKeys { + // Content slice goes [key1, value1, key2, value2, ...] + topLevelPairs := cm.Root.Content + for i, v := range topLevelPairs { + // Skip every other slice item since we only want to check against keys + if i%2 != 0 { + continue + } if v.Value == key { ce.KeyNode = v ce.Index = i - if i+1 < len(topLevelKeys) { - ce.ValueNode = topLevelKeys[i+1] + if i+1 < len(topLevelPairs) { + ce.ValueNode = topLevelPairs[i+1] } return } diff --git a/internal/config/config_map_test.go b/internal/config/config_map_test.go new file mode 100644 index 000000000..c504e4cbc --- /dev/null +++ b/internal/config/config_map_test.go @@ -0,0 +1,65 @@ +package config + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "gopkg.in/yaml.v3" +) + +func TestFindEntry(t *testing.T) { + tests := []struct { + name string + key string + output string + wantErr bool + }{ + { + name: "find key", + key: "valid", + output: "present", + }, + { + name: "find key that is not present", + key: "invalid", + wantErr: true, + }, + { + name: "find key with blank value", + key: "blank", + output: "", + }, + { + name: "find key that has same content as a value", + key: "same", + output: "logical", + }, + } + + for _, tt := range tests { + cm := ConfigMap{Root: testYaml()} + t.Run(tt.name, func(t *testing.T) { + out, err := cm.FindEntry(tt.key) + if tt.wantErr { + assert.EqualError(t, err, "not found") + return + } + assert.NoError(t, err) + fmt.Println(out) + assert.Equal(t, tt.output, out.ValueNode.Value) + }) + } +} + +func testYaml() *yaml.Node { + var root yaml.Node + var data = ` +valid: present +erroneous: same +blank: +same: logical +` + _ = yaml.Unmarshal([]byte(data), &root) + return root.Content[0] +}