Skip to content

Commit

Permalink
Extracted yaml_parser into utils; Added tests for yaml_parser
Browse files Browse the repository at this point in the history
  • Loading branch information
vertisan committed Sep 17, 2024
1 parent 529237a commit 57c5101
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 4 deletions.
3 changes: 2 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"os"

"github.com/charmbracelet/log"
"github.com/vertisan/vault-snapshot-agent/internal/utils"
)

type Configuration struct {
Expand Down Expand Up @@ -38,7 +39,7 @@ func LoadConfig(configPath string) (*Configuration, error) {
return nil, err
}

config, err := ParseConfigFile(fileContent)
config, err := utils.ParseYamlData[Configuration](fileContent)
if err != nil {
log.Error("Cannot parse configuration!", "err", err)
return nil, err
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package config
package utils

import (
"bytes"
Expand All @@ -9,8 +9,8 @@ import (
"gopkg.in/yaml.v3"
)

func ParseConfigFile(data []byte) (*Configuration, error) {
config := &Configuration{}
func ParseYamlData[T any](data []byte) (*T, error) {
config := new(T)

decoder := yaml.NewDecoder(bytes.NewReader(data))
decoder.KnownFields(true)
Expand Down
72 changes: 72 additions & 0 deletions internal/utils/yaml_parser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package utils

import (
"testing"

"github.com/stretchr/testify/assert"
)

type ConfigTest struct {
// Define the fields of your ConfigTest here
Field1 string `yaml:"field1"`
Field2 int `yaml:"field2"`
}

func TestParseYamlData(t *testing.T) {
tests := []struct {
name string
input []byte
expected *ConfigTest
expectError bool
}{
{
name: "Valid YAML",
input: []byte(`
field1: "value1"
field2: 2
`),
expected: &ConfigTest{
Field1: "value1",
Field2: 2,
},
expectError: false,
},
{
name: "Empty YAML",
input: []byte(``),
expected: &ConfigTest{},
expectError: false,
},
{
name: "Invalid YAML",
input: []byte(`
field1: "value1"
field2: "invalid_int"
`),
expected: nil,
expectError: true,
},
{
name: "Unknown Field",
input: []byte(`
field1: "value1"
field2: 2
unknown_field: "value"
`),
expected: nil,
expectError: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config, err := ParseYamlData[ConfigTest](tt.input)
if tt.expectError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.expected, config)
}
})
}
}

0 comments on commit 57c5101

Please sign in to comment.