109 lines
2.3 KiB
Go
109 lines
2.3 KiB
Go
package config_test
|
|
|
|
import (
|
|
"kdelsd/config"
|
|
"reflect"
|
|
"strings"
|
|
"strconv"
|
|
"testing"
|
|
)
|
|
|
|
|
|
type TestConfig struct {
|
|
INT int
|
|
BOOL bool
|
|
STR string
|
|
OTHER_STR string `optional`
|
|
COMPLEX complex64 `optional`
|
|
}
|
|
|
|
var testConfigReference = TestConfig{
|
|
INT: 42,
|
|
BOOL: true,
|
|
STR: "sajtok",
|
|
OTHER_STR: "default-value",
|
|
}
|
|
|
|
var testEnv = []string{
|
|
"TEST_INT=42",
|
|
"TEST_BOOL=true",
|
|
"TEST_STR=sajtok",
|
|
}
|
|
|
|
func configBuilder() *config.ConfigBuilder {
|
|
cb := config.NewBuilder()
|
|
cb.ConfigFetchMethod = func()[]string {
|
|
return testEnv
|
|
}
|
|
|
|
return cb
|
|
}
|
|
|
|
|
|
func TestConfigBuilder(t *testing.T) {
|
|
c := TestConfig{}
|
|
c.OTHER_STR = testConfigReference.OTHER_STR
|
|
builder := configBuilder()
|
|
|
|
err := builder.Build("TEST_", &c)
|
|
if err != nil {
|
|
t.Fatalf("Config building should not fail\n")
|
|
}
|
|
|
|
if c != testConfigReference {
|
|
t.Fatalf("Parsed config shoudl equal reference config\n%v != %v\n", c, testConfigReference)
|
|
}
|
|
}
|
|
|
|
func TestConfigBuilderParsers(t *testing.T) {
|
|
c := TestConfig{}
|
|
builder := configBuilder()
|
|
builder.ConfigFetchMethod = func()[]string {
|
|
return append(testEnv, "TEST_COMPLEX=42+42i")
|
|
}
|
|
|
|
err := builder.Build("TEST_", &c)
|
|
if err == nil {
|
|
t.Fatalf("CONFIG should not be parseable, since type has no default parser\n")
|
|
}
|
|
if !strings.Contains(err.Error(), "complex64") {
|
|
t.Fatalf("Error should contain the type that failed to parse\n")
|
|
}
|
|
|
|
builder.RegisterParser(reflect.Complex64, func(value string)(interface{}, error) {
|
|
num, err := strconv.ParseComplex(value, 64)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return num, nil
|
|
})
|
|
err = builder.Build("TEST_", &c)
|
|
if err != nil {
|
|
t.Fatalf("Parsing type should not fail after registering a parser for it\n")
|
|
}
|
|
}
|
|
|
|
func TestConfigBuilderOptional(t *testing.T) {
|
|
type RequiredConfig struct {
|
|
REQUIRED_STR string
|
|
}
|
|
c := RequiredConfig{}
|
|
builder := config.NewBuilder()
|
|
|
|
err := builder.Build("TEST_", &c)
|
|
if err == nil {
|
|
t.Fatalf("Fields not marked with the `optional` tag should be mandatory\n")
|
|
}
|
|
if !strings.Contains(err.Error(), "REQUIRED_STR") {
|
|
t.Fatalf("Error should contain the name of the field\n")
|
|
}
|
|
|
|
builder.ConfigFetchMethod = func()[]string {
|
|
return append(testEnv, "TEST_REQUIRED_STR=prrrr")
|
|
}
|
|
err = builder.Build("TEST_", &c)
|
|
if err != nil {
|
|
t.Fatalf("Config building should not fail after providing the mandatory field\n")
|
|
}
|
|
}
|