summaryrefslogtreecommitdiffstats
path: root/pkg/config/config_test.go
blob: 2418094293af55536e48292d37a49ab2d91f0cd2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
`

	miniOutput := &Config{}
	_ = defaults.Set(miniOutput)

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

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

	subtests := []struct {
		name   string
		input  string
		output *Config
		warn   bool
	}{
		{
			name:   "mini",
			input:  miniConf,
			output: miniOutput,
			warn:   false,
		},
		{
			name:   "mini-with-unknown",
			input:  miniConf + "\nunknown: 42",
			output: miniOutput,
			warn:   true,
		},
	}

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

			actual, err := FromYAMLFile(tempFile.Name())
			require.NoError(t, err)

			if st.warn {
				require.Error(t, actual.DecodeWarning, "reading config should produce a warning")

				// Reset the warning so that the following require.Equal() doesn't try to compare it.
				actual.DecodeWarning = nil
			} else {
				require.NoError(t, actual.DecodeWarning, "reading config should not produce a warning")
			}

			require.Equal(t, st.output, actual)
		})
	}
}