github.com/annwntech/go-micro/v2@v2.9.5/config/source/file/file_test.go (about) 1 package file_test 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "testing" 8 "time" 9 10 "github.com/annwntech/go-micro/v2/config" 11 "github.com/annwntech/go-micro/v2/config/source/file" 12 ) 13 14 func TestConfig(t *testing.T) { 15 data := []byte(`{"foo": "bar"}`) 16 path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano())) 17 fh, err := os.Create(path) 18 if err != nil { 19 t.Error(err) 20 } 21 defer func() { 22 fh.Close() 23 os.Remove(path) 24 }() 25 _, err = fh.Write(data) 26 if err != nil { 27 t.Error(err) 28 } 29 30 conf, err := config.NewConfig() 31 if err != nil { 32 t.Fatal(err) 33 } 34 conf.Load(file.NewSource(file.WithPath(path))) 35 // simulate multiple close 36 go conf.Close() 37 go conf.Close() 38 } 39 40 func TestFile(t *testing.T) { 41 data := []byte(`{"foo": "bar"}`) 42 path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano())) 43 fh, err := os.Create(path) 44 if err != nil { 45 t.Error(err) 46 } 47 defer func() { 48 fh.Close() 49 os.Remove(path) 50 }() 51 52 _, err = fh.Write(data) 53 if err != nil { 54 t.Error(err) 55 } 56 57 f := file.NewSource(file.WithPath(path)) 58 c, err := f.Read() 59 if err != nil { 60 t.Error(err) 61 } 62 if string(c.Data) != string(data) { 63 t.Logf("%+v", c) 64 t.Error("data from file does not match") 65 } 66 }