chore(config/env): polish watcher (#1341)

* chore(config/env): polish watcher
pull/1342/head
徐胖 3 years ago committed by GitHub
parent 80378ca10d
commit 3026f9490e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 7
      config/env/watcher.go
  2. 29
      config/env/watcher_test.go

@ -7,8 +7,6 @@ import (
)
type watcher struct {
exit chan struct{}
ctx context.Context
cancel context.CancelFunc
}
@ -17,7 +15,7 @@ var _ config.Watcher = (*watcher)(nil)
func NewWatcher() (config.Watcher, error) {
ctx, cancel := context.WithCancel(context.Background())
return &watcher{exit: make(chan struct{}), ctx: ctx, cancel: cancel}, nil
return &watcher{ctx: ctx, cancel: cancel}, nil
}
// Next will be blocked until the Stop method is called
@ -25,13 +23,10 @@ func (w *watcher) Next() ([]*config.KeyValue, error) {
select {
case <-w.ctx.Done():
return nil, w.ctx.Err()
case <-w.exit:
return nil, nil
}
}
func (w *watcher) Stop() error {
close(w.exit)
w.cancel()
return nil
}

@ -0,0 +1,29 @@
package env
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_watcher_next(t *testing.T) {
t.Run("next after stop should return err", func(t *testing.T) {
w, err := NewWatcher()
require.NoError(t, err)
_ = w.Stop()
_, err = w.Next()
assert.Error(t, err)
})
}
func Test_watcher_stop(t *testing.T) {
t.Run("stop multiple times should not panic", func(t *testing.T) {
w, err := NewWatcher()
require.NoError(t, err)
_ = w.Stop()
_ = w.Stop()
})
}
Loading…
Cancel
Save