go-micro.dev/v5@v5.12.0/config/source/file/file_test.go (about) 1 package file_test 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "testing" 8 "testing/fstest" 9 "time" 10 11 "go-micro.dev/v5/config" 12 "go-micro.dev/v5/config/source/file" 13 ) 14 15 func TestConfig(t *testing.T) { 16 data := []byte(`{"foo": "bar"}`) 17 path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano())) 18 fh, err := os.Create(path) 19 if err != nil { 20 t.Error(err) 21 } 22 defer func() { 23 fh.Close() 24 os.Remove(path) 25 }() 26 _, err = fh.Write(data) 27 if err != nil { 28 t.Error(err) 29 } 30 31 conf, err := config.NewConfig() 32 if err != nil { 33 t.Fatal(err) 34 } 35 conf.Load(file.NewSource(file.WithPath(path))) 36 // simulate multiple close 37 go conf.Close() 38 go conf.Close() 39 } 40 41 func TestFile(t *testing.T) { 42 data := []byte(`{"foo": "bar"}`) 43 path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano())) 44 fh, err := os.Create(path) 45 if err != nil { 46 t.Error(err) 47 } 48 defer func() { 49 fh.Close() 50 os.Remove(path) 51 }() 52 53 _, err = fh.Write(data) 54 if err != nil { 55 t.Error(err) 56 } 57 58 f := file.NewSource(file.WithPath(path)) 59 c, err := f.Read() 60 if err != nil { 61 t.Error(err) 62 } 63 if string(c.Data) != string(data) { 64 t.Logf("%+v", c) 65 t.Error("data from file does not match") 66 } 67 } 68 69 func TestWithFS(t *testing.T) { 70 data := []byte(`{"foo": "bar"}`) 71 path := fmt.Sprintf("file.%d", time.Now().UnixNano()) 72 73 fsMock := fstest.MapFS{ 74 path: &fstest.MapFile{ 75 Data: data, 76 Mode: 0666, 77 }, 78 } 79 80 f := file.NewSource(file.WithFS(fsMock), file.WithPath(path)) 81 c, err := f.Read() 82 if err != nil { 83 t.Error(err) 84 } 85 if string(c.Data) != string(data) { 86 t.Logf("%+v", c) 87 t.Error("data from file does not match") 88 } 89 }