2020-12-04 02:28:45 +03:00
|
|
|
package config_test
|
|
|
|
|
2020-12-13 13:10:04 +03:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/unistack-org/micro/v3/config"
|
|
|
|
)
|
2020-12-04 02:28:45 +03:00
|
|
|
|
|
|
|
type Cfg struct {
|
2020-12-13 13:10:04 +03:00
|
|
|
StringValue string `default:"string_value"`
|
|
|
|
IntValue int `default:"99"`
|
2020-12-13 13:17:38 +03:00
|
|
|
StructValue struct {
|
|
|
|
StringValue string `default:"string_value"`
|
|
|
|
}
|
2020-12-04 02:28:45 +03:00
|
|
|
}
|
|
|
|
|
2020-12-13 13:10:04 +03:00
|
|
|
func TestDefault(t *testing.T) {
|
2020-12-04 02:28:45 +03:00
|
|
|
ctx := context.Background()
|
|
|
|
conf := &Cfg{}
|
|
|
|
blfn := func(ctx context.Context, cfg config.Config) error {
|
|
|
|
conf, ok := cfg.Options().Struct.(*Cfg)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("failed to get Struct from options: %v", cfg.Options())
|
|
|
|
}
|
2020-12-13 13:10:04 +03:00
|
|
|
conf.StringValue = "before_load"
|
2020-12-04 02:28:45 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
alfn := func(ctx context.Context, cfg config.Config) error {
|
|
|
|
conf, ok := cfg.Options().Struct.(*Cfg)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("failed to get Struct from options: %v", cfg.Options())
|
|
|
|
}
|
2020-12-13 13:10:04 +03:00
|
|
|
conf.StringValue = "after_load"
|
2020-12-04 02:28:45 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-12-08 00:41:14 +03:00
|
|
|
cfg := config.NewConfig(config.Struct(conf), config.BeforeLoad(blfn), config.AfterLoad(alfn))
|
2020-12-04 02:28:45 +03:00
|
|
|
if err := cfg.Init(); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
for _, fn := range cfg.Options().BeforeLoad {
|
|
|
|
if err := fn(ctx, cfg); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
2020-12-13 13:10:04 +03:00
|
|
|
if conf.StringValue != "before_load" {
|
2020-12-04 02:28:45 +03:00
|
|
|
t.Fatal("BeforeLoad option not working")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := cfg.Load(ctx); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2020-12-13 13:17:38 +03:00
|
|
|
if conf.StringValue != "string_value" || conf.IntValue != 99 || conf.StructValue.StringValue != "string_value" {
|
2020-12-13 13:10:04 +03:00
|
|
|
t.Fatalf("load failed: %#+v", conf)
|
|
|
|
}
|
|
|
|
|
2020-12-04 02:28:45 +03:00
|
|
|
for _, fn := range cfg.Options().AfterLoad {
|
|
|
|
if err := fn(ctx, cfg); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
2020-12-13 13:10:04 +03:00
|
|
|
if conf.StringValue != "after_load" {
|
2020-12-04 02:28:45 +03:00
|
|
|
t.Fatal("AfterLoad option not working")
|
|
|
|
}
|
|
|
|
|
2020-12-13 13:17:38 +03:00
|
|
|
t.Logf("%#+v\n", conf)
|
2020-12-04 02:28:45 +03:00
|
|
|
}
|