github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/config/config_test.go (about) 1 package config 2 3 import ( 4 "testing" 5 "time" 6 ) 7 8 type ( 9 testConfig struct { 10 Config 11 NameValue string `field:"name_value"` 12 Expiry time.Duration 13 Mode ModeType 14 CanLoad bool 15 CanSave bool 16 } 17 ) 18 19 func newTestConfig() *testConfig { 20 Init( 21 WithFileName("config_test.json"), 22 WithWatcher(), 23 ) 24 25 cfg := &testConfig{} 26 27 // 测试空结构体Init调用修改配置 28 cfg.SetValue("SetValue", "TEST") 29 30 // 注册配置 31 Register(cfg) 32 return cfg 33 } 34 35 func (self *testConfig) String() string { 36 return "testConfig" 37 } 38 39 func (self *testConfig) Load() error { 40 self.CanLoad = true 41 self.LoadToModel(self) 42 return nil 43 } 44 45 func (self *testConfig) Save(immed ...bool) error { 46 self.CanSave = true 47 self.NameValue = "123" 48 return self.SaveFromModel(self, immed...) 49 } 50 51 func TestLoad(t *testing.T) { 52 go func() { 53 cfg := newTestConfig() 54 cfg.Config.LoadFromFile() 55 cfg.Save() 56 }() 57 <-make(chan int) 58 } 59 60 func TestLoadAndSave(t *testing.T) { 61 cfg := Default() 62 err := cfg.LoadFromFile("config.json") 63 if err != nil { 64 t.Log(err) 65 } 66 67 cfg.SetValue("project.struct", 11) 68 cfg.SetValue("project2.struct", 11) 69 70 err = cfg.SaveToFile() 71 if err != nil { 72 t.Log(err) 73 } 74 } 75 76 func TestBuildJsonConfigAndGet(t *testing.T) { 77 cfg := defaultConfig 78 err := cfg.LoadFromFile("config.json") 79 if err != nil { 80 t.Log(err) 81 } 82 83 t.Log(cfg.GetInt64("project.struct", 0)) 84 t.Log(cfg.GetInt64("project2.struct", 1)) 85 err = cfg.SaveToFile() 86 if err != nil { 87 t.Log(err) 88 } 89 }