Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Config parsing: fail on unknown fields and print them #605

Merged
merged 2 commits into from
Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/icingadb-migrate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func parseConfig(f *Flags) (_ *Config, exit int) {
return nil, 2
}

if err := yaml.NewDecoder(cf).Decode(c); err != nil {
if err := yaml.NewDecoder(cf, yaml.DisallowUnknownField()).Decode(c); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "can't parse config file: %s\n", err.Error())
return nil, 2
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func FromYAMLFile(name string) (*Config, error) {
defer f.Close()

c := &Config{}
d := yaml.NewDecoder(f)
d := yaml.NewDecoder(f, yaml.DisallowUnknownField())

if err := defaults.Set(c); err != nil {
return nil, errors.Wrap(err, "can't set config defaults")
Expand Down
69 changes: 69 additions & 0 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package config

import (
"github.com/creasty/defaults"
"github.com/icinga/icingadb/pkg/logging"
"github.com/stretchr/testify/require"
"os"
"testing"
)

func TestFromYAMLFile(t *testing.T) {
const miniConf = `
database:
host: 192.0.2.1
database: icingadb
user: icingadb
password: icingadb

redis:
host: 2001:db8::1
`

subtests := []struct {
name string
input string
output *Config
}{
{
name: "mini",
input: miniConf,
output: func() *Config {
c := &Config{}
_ = defaults.Set(c)

c.Database.Host = "192.0.2.1"
c.Database.Database = "icingadb"
c.Database.User = "icingadb"
c.Database.Password = "icingadb"

c.Redis.Host = "2001:db8::1"
c.Logging.Output = logging.CONSOLE

return c
}(),
},
{
name: "mini-with-unknown",
input: miniConf + "\nunknown: 42",
output: nil,
},
}

for _, st := range subtests {
t.Run(st.name, func(t *testing.T) {
tempFile, err := os.CreateTemp("", "")
require.NoError(t, err)
defer func() { _ = os.Remove(tempFile.Name()) }()

require.NoError(t, os.WriteFile(tempFile.Name(), []byte(st.input), 0o600))

if actual, err := FromYAMLFile(tempFile.Name()); st.output == nil {
require.Error(t, err)
} else {
require.NoError(t, err)
require.Equal(t, st.output, actual)
}
})
}
}
Loading