<test> config/file: add tests for file watcher (#1199)

* add file watcher test
pull/1204/head
Kuiba 3 years ago committed by GitHub
parent dc0ed5bc42
commit 060cb24535
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 95
      config/file/file_test.go
  2. 10
      config/file/watcher.go

@ -9,6 +9,7 @@ import (
"time"
"github.com/go-kratos/kratos/v2/config"
"github.com/stretchr/testify/assert"
)
const (
@ -38,6 +39,35 @@ const (
]
}`
_testJSONUpdate = `
{
"test":{
"settings":{
"int_key":1000,
"float_key":1000.1,
"duration_key":10000,
"string_key":"string_value"
},
"server":{
"addr":"127.0.0.1",
"port":8000
}
},
"foo":[
{
"name":"nihao",
"age":18
},
{
"name":"nihao",
"age":18
}
],
"bar":{
"event":"update"
}
}`
// _testYaml = `
//Foo:
// bar :
@ -67,6 +97,71 @@ func TestFile(t *testing.T) {
}
testSource(t, file, data)
testSource(t, path, data)
testWatchFile(t, file)
testWatchDir(t, path, file)
}
func testWatchFile(t *testing.T, path string) {
t.Log(path)
s := NewSource(path)
watch, err := s.Watch()
if err != nil {
t.Error(err)
}
f, err := os.OpenFile(path, os.O_RDWR, 0)
if err != nil {
t.Error(err)
}
defer f.Close()
_, err = f.WriteString(_testJSONUpdate)
if err != nil {
t.Error(err)
}
kvs, err := watch.Next()
assert.Nil(t, err)
assert.Equal(t, string(kvs[0].Value), _testJSONUpdate)
newFilepath := filepath.Join(filepath.Dir(path), "test1.json")
if err := os.Rename(path, newFilepath); err != nil {
t.Error(err)
}
kvs, err = watch.Next()
assert.NotNil(t, err)
assert.Nil(t, kvs)
err = watch.Stop()
assert.Nil(t, err)
if err := os.Rename(newFilepath, path); err != nil {
t.Error(err)
}
}
func testWatchDir(t *testing.T, path, file string) {
t.Log(path)
t.Log(file)
s := NewSource(path)
watch, err := s.Watch()
if err != nil {
t.Error(err)
}
f, err := os.OpenFile(file, os.O_RDWR, 0)
if err != nil {
t.Error(err)
}
defer f.Close()
_, err = f.WriteString(_testJSONUpdate)
if err != nil {
t.Error(err)
}
kvs, err := watch.Next()
assert.Nil(t, err)
assert.Equal(t, string(kvs[0].Value), _testJSONUpdate)
}
func testSource(t *testing.T, path string, data []byte) {

@ -18,7 +18,9 @@ func newWatcher(f *file) (config.Watcher, error) {
if err != nil {
return nil, err
}
fw.Add(f.path)
if err := fw.Add(f.path); err != nil {
return nil, err
}
return &watcher{f: f, fw: fw}, nil
}
@ -27,7 +29,9 @@ func (w *watcher) Next() ([]*config.KeyValue, error) {
case event := <-w.fw.Events:
if event.Op == fsnotify.Rename {
if _, err := os.Stat(event.Name); err == nil || os.IsExist(err) {
w.fw.Add(event.Name)
if err := w.fw.Add(event.Name); err != nil {
return nil, err
}
}
}
fi, err := os.Stat(w.f.path)
@ -36,7 +40,7 @@ func (w *watcher) Next() ([]*config.KeyValue, error) {
}
path := w.f.path
if fi.IsDir() {
path = filepath.Join(w.f.path, event.Name)
path = filepath.Join(w.f.path, filepath.Base(event.Name))
}
kv, err := w.f.loadFile(path)
if err != nil {

Loading…
Cancel
Save