2020-03-19 11:54:59 +02:00
|
|
|
package file_test
|
2019-05-31 00:11:13 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"testing"
|
2022-09-24 02:46:18 +02:00
|
|
|
"testing/fstest"
|
2019-05-31 00:11:13 +02:00
|
|
|
"time"
|
2020-03-19 11:54:59 +02:00
|
|
|
|
2021-10-12 13:55:53 +02:00
|
|
|
"go-micro.dev/v4/config"
|
|
|
|
"go-micro.dev/v4/config/source/file"
|
2019-05-31 00:11:13 +02:00
|
|
|
)
|
|
|
|
|
2020-03-19 11:54:59 +02:00
|
|
|
func TestConfig(t *testing.T) {
|
|
|
|
data := []byte(`{"foo": "bar"}`)
|
|
|
|
path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano()))
|
|
|
|
fh, err := os.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
fh.Close()
|
|
|
|
os.Remove(path)
|
|
|
|
}()
|
|
|
|
_, err = fh.Write(data)
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
conf, err := config.NewConfig()
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
conf.Load(file.NewSource(file.WithPath(path)))
|
|
|
|
// simulate multiple close
|
|
|
|
go conf.Close()
|
|
|
|
go conf.Close()
|
|
|
|
}
|
|
|
|
|
2019-05-31 00:11:13 +02:00
|
|
|
func TestFile(t *testing.T) {
|
|
|
|
data := []byte(`{"foo": "bar"}`)
|
|
|
|
path := filepath.Join(os.TempDir(), fmt.Sprintf("file.%d", time.Now().UnixNano()))
|
|
|
|
fh, err := os.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
fh.Close()
|
|
|
|
os.Remove(path)
|
|
|
|
}()
|
|
|
|
|
|
|
|
_, err = fh.Write(data)
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
|
2020-03-19 11:54:59 +02:00
|
|
|
f := file.NewSource(file.WithPath(path))
|
2019-05-31 00:11:13 +02:00
|
|
|
c, err := f.Read()
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
if string(c.Data) != string(data) {
|
2020-04-09 13:05:46 +02:00
|
|
|
t.Logf("%+v", c)
|
2019-05-31 00:11:13 +02:00
|
|
|
t.Error("data from file does not match")
|
|
|
|
}
|
|
|
|
}
|
2022-09-24 02:46:18 +02:00
|
|
|
|
|
|
|
func TestWithFS(t *testing.T) {
|
|
|
|
data := []byte(`{"foo": "bar"}`)
|
|
|
|
path := fmt.Sprintf("file.%d", time.Now().UnixNano())
|
|
|
|
|
|
|
|
fsMock := fstest.MapFS{
|
|
|
|
path: &fstest.MapFile{
|
|
|
|
Data: data,
|
|
|
|
Mode: 0666,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
f := file.NewSource(file.WithFS(fsMock), file.WithPath(path))
|
|
|
|
c, err := f.Read()
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
if string(c.Data) != string(data) {
|
|
|
|
t.Logf("%+v", c)
|
|
|
|
t.Error("data from file does not match")
|
|
|
|
}
|
|
|
|
}
|