- Replace global ConfigPath and Overrides with viper-based configuration - Add viper.New() to create configurable viper instances - Store viper and unmarshaled Config struct in context for testability - Add RetrieveFromContext and AddToContext helper functions - Update files.Append to accept context and retrieve config from it - Update formatters.Preferred and formatters.New to accept context - Add PersistentPreRunE in CLI to create and configure viper instance - Support -c flag for custom config file path - Support -v flag for config value overrides - Update all test files to create viper and add to context - Remove unused config types and load functions - Add viper as dependency with automatic env var support (MYLOG_*)
51 lines
1 KiB
Go
51 lines
1 KiB
Go
package config
|
|
|
|
import (
|
|
"os"
|
|
"testing"
|
|
|
|
"github.com/nalgeon/be"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
func TestNew(t *testing.T) {
|
|
_, v, err := New(t.Context())
|
|
be.Err(t, err, nil)
|
|
be.True(t, v != nil)
|
|
}
|
|
|
|
func TestNewWithEnvOverrides(t *testing.T) {
|
|
os.Setenv("MYLOG_INPUT_PATH", "/test/path")
|
|
defer os.Unsetenv("MYLOG_INPUT_PATH")
|
|
|
|
_, v, err := New(t.Context())
|
|
be.Err(t, err, nil)
|
|
be.Equal(t, v.GetString("input.path"), "/test/path")
|
|
}
|
|
|
|
func TestNewWithConfigFile(t *testing.T) {
|
|
dir := t.ArtifactDir()
|
|
f, _ := os.CreateTemp(dir, "test*.toml")
|
|
defer os.Remove(f.Name())
|
|
f.WriteString(`[input]
|
|
path = "/file/path"
|
|
ext = "log"`)
|
|
f.Close()
|
|
|
|
_, v, err := New(t.Context())
|
|
be.Err(t, err, nil)
|
|
|
|
v.SetConfigFile(f.Name())
|
|
v.SetConfigType("toml")
|
|
err = v.ReadInConfig()
|
|
be.Err(t, err, nil)
|
|
be.Equal(t, v.GetString("input.path"), "/file/path")
|
|
be.Equal(t, v.GetString("input.ext"), "log")
|
|
}
|
|
|
|
func TestRetrieveFromContext(t *testing.T) {
|
|
v := viper.New()
|
|
ctx := AddToContext(t.Context(), v)
|
|
result, _ := RetrieveFromContext(ctx)
|
|
be.True(t, v == result)
|
|
}
|