frostfs-node/cmd/frostfs-node/config/test/config.go

71 lines
1.6 KiB
Go

package configtest
import (
"bufio"
"os"
"strings"
"testing"
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config"
"github.com/stretchr/testify/require"
)
func fromFile(path string) *config.Config {
os.Clearenv() // ENVs have priority over config files, so we do this in tests
return config.New(path, "", "")
}
func fromEnvFile(t testing.TB, path string) *config.Config {
loadEnv(t, path) // github.com/joho/godotenv can do that as well
return config.New("", "", config.EnvPrefix)
}
func forEachFile(paths []string, f func(*config.Config)) {
for i := range paths {
f(fromFile(paths[i]))
}
}
// ForEachFileType passes configs read from next files:
// - `<pref>.yaml`;
// - `<pref>.json`.
func ForEachFileType(pref string, f func(*config.Config)) {
forEachFile([]string{
pref + ".yaml",
pref + ".json",
}, f)
}
// ForEnvFileType creates config from `<pref>.env` file.
func ForEnvFileType(t testing.TB, pref string, f func(*config.Config)) {
f(fromEnvFile(t, pref+".env"))
}
// EmptyConfig returns config without any values and sections.
func EmptyConfig() *config.Config {
return config.New("", "", config.EnvPrefix)
}
// loadEnv reads .env file, parses `X=Y` records and sets OS ENVs.
func loadEnv(t testing.TB, path string) {
f, err := os.Open(path)
require.NoError(t, err, "can't open .env file")
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
k, v, found := strings.Cut(scanner.Text(), "=")
if !found {
continue
}
v = strings.Trim(v, `"`)
err = os.Setenv(k, v)
require.NoError(t, err, "can't set environment variable")
}
}