cleanenv
cleanenv copied to clipboard
Default Values on Nested Structs
I am attempting to use cleanenv with a nested struct and the env-default
tag is not being applied on the child struct.
Is this something cleanenv could support?
Here's a test case replicating the issue:
func TestNestedStructsParseFileEnv(t *testing.T) {
type child struct {
Number int64 `yaml:"number"`
DefaultNumber int64 `yaml:"default_number" env-defult:"-1"`
}
type parent struct {
Children map[string]child `yaml:"children"`
}
children := make(map[string]child)
children["first"] = child{1, -1}
wantConfig := parent{children}
tests := []struct {
name string
file string
ext string
want *parent
wantErr bool
}{
{
name: "yaml",
file: `
children:
first:
number: 1`,
ext: "yaml",
want: &wantConfig,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpFile, err := ioutil.TempFile(os.TempDir(), fmt.Sprintf("*.%s", tt.ext))
if err != nil {
t.Fatal("cannot create temporary file:", err)
}
defer os.Remove(tmpFile.Name())
text := []byte(tt.file)
if _, err = tmpFile.Write(text); err != nil {
t.Fatal("failed to write to temporary file:", err)
}
var prnt parent
if err = ReadConfig(tmpFile.Name(), &prnt); (err != nil) != tt.wantErr {
t.Errorf("wrong error behavior %v, wantErr %v", err, tt.wantErr)
}
if err == nil && !reflect.DeepEqual(&prnt, tt.want) {
t.Errorf("wrong data %v, want %v", &prnt, tt.want)
}
})
}
}
It seems that the default processing logic for nested maps has not yet been implemented. Thank you for finding this error.
@ilyakaznacheev do u have time to implement this or you can assign me
@abakermi go ahead, if you have ideas how to fix that, please send a PR :)
sure, thanks !
Unassigned due to inactivity
This applies for all tags as far as I can tell, for example env-required
does not validate on nested structs either. Logical but worth pointing out I felt, love the library by the way.