2015-09-08 21:11:35 +00:00
|
|
|
package rconfig
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2021-09-06 16:43:24 +00:00
|
|
|
"testing"
|
2023-12-20 11:13:59 +00:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2015-09-08 21:11:35 +00:00
|
|
|
)
|
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
func TestPrecedence(t *testing.T) {
|
|
|
|
type testcfg struct {
|
2015-09-08 21:11:35 +00:00
|
|
|
A int `default:"1" vardefault:"a" env:"a" flag:"avar,a" description:"a"`
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
2021-09-06 16:43:24 +00:00
|
|
|
cfg testcfg
|
2015-09-08 21:11:35 +00:00
|
|
|
args []string
|
|
|
|
vardefaults map[string]string
|
|
|
|
)
|
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
exec := func(desc string, fn func() interface{}, exp interface{}) {
|
|
|
|
cfg = testcfg{}
|
2015-09-08 21:11:35 +00:00
|
|
|
SetVariableDefaults(vardefaults)
|
2023-12-20 11:13:59 +00:00
|
|
|
assert.NoError(t, parse(&cfg, args), desc)
|
2015-09-08 21:11:35 +00:00
|
|
|
|
2023-12-20 11:13:59 +00:00
|
|
|
assert.Equal(t, exp, fn())
|
2021-09-06 16:43:24 +00:00
|
|
|
}
|
2015-09-08 21:11:35 +00:00
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
// Provided: Flag, Env, Default, VarDefault
|
|
|
|
args = []string{"-a", "5"}
|
2024-08-18 10:09:36 +00:00
|
|
|
t.Setenv("a", "8")
|
2021-09-06 16:43:24 +00:00
|
|
|
vardefaults = map[string]string{
|
|
|
|
"a": "3",
|
|
|
|
}
|
2015-09-08 21:11:35 +00:00
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
exec("Provided: Flag, Env, Default, VarDefault", func() interface{} { return cfg.A }, 5)
|
2015-09-08 21:11:35 +00:00
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
// Provided: Env, Default, VarDefault
|
|
|
|
args = []string{}
|
2024-08-18 10:09:36 +00:00
|
|
|
t.Setenv("a", "8")
|
2021-09-06 16:43:24 +00:00
|
|
|
vardefaults = map[string]string{
|
|
|
|
"a": "3",
|
|
|
|
}
|
|
|
|
|
|
|
|
exec("Provided: Env, Default, VarDefault", func() interface{} { return cfg.A }, 8)
|
2015-09-08 21:11:35 +00:00
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
// Provided: Default, VarDefault
|
|
|
|
args = []string{}
|
2023-12-20 11:13:59 +00:00
|
|
|
require.NoError(t, os.Unsetenv("a"))
|
2021-09-06 16:43:24 +00:00
|
|
|
vardefaults = map[string]string{
|
|
|
|
"a": "3",
|
|
|
|
}
|
2015-09-08 21:11:35 +00:00
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
exec("Provided: Default, VarDefault", func() interface{} { return cfg.A }, 3)
|
2015-09-08 21:11:35 +00:00
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
// Provided: Default
|
|
|
|
args = []string{}
|
2023-12-20 11:13:59 +00:00
|
|
|
require.NoError(t, os.Unsetenv("a"))
|
2021-09-06 16:43:24 +00:00
|
|
|
vardefaults = map[string]string{}
|
2015-09-08 21:11:35 +00:00
|
|
|
|
2021-09-06 16:43:24 +00:00
|
|
|
exec("Provided: Default", func() interface{} { return cfg.A }, 1)
|
|
|
|
}
|