我有一个函数可以通过 fsnotify 监视 certian 文件并在文件更改时调用回调。如果回调返回false,则观看结束:
import (
"github.com/golang/glog"
"github.com/fsnotify/fsnotify"
)
type WatcherFunc func(err error) bool
func WatchFileChanges(filename string, watcherFunc WatcherFunc) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
glog.Errorf("Got error creating watcher %s", err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
glog.Infof("inotify event %s", event)
if event.Op&fsnotify.Write == fsnotify.Write {
glog.Infof("modified file %s, calling watcher func", event.Name)
if !watcherFunc(nil) {
close(done)
}
}
case err := <-watcher.Errors:
glog.Errorf("Got error watching %s, calling watcher func", err)
if !watcherFunc(err) {
close(done)
}
}
}
}()
glog.Infof("Start watching file %s", filename)
err = watcher.Add(filename)
if err != nil {
glog.Errorf("Got error adding watcher %s", err)
}
<-done
}
然后我认为对此进行测试会很好,所以我从一个简单的测试用例开始:
import (
"io/ioutil"
"os"
"testing"
)
func TestStuff(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "test")
if err != nil {
t.Fatal("Failed to create tmp file")
}
defer os.Remove(tmpfile.Name())
watcherFunc := func (err error) bool {
return false
}
WatchFileChanges(tmpfile.Name(), watcherFunc)
}
我想在这里做的是对文件做一些修改,将事件收集到一个数组中,然后从 watcherFunc
返回 false
然后断言阵列。问题是,当 goroutine 启动时,测试当然只是挂起并等待事件。
有什么方法可以测试这样的函数,比如……启动一个不同的线程(?)来更新/修改文件?
最佳答案
Is there any way how I can test a function like this, like … starting a different thread (?) that updates/modifies the file?
当然...启动一个 goroutine 来执行您想要的更新。
func TestStuff(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "test")
if err != nil {
t.Fatal("Failed to create tmp file")
}
defer os.Remove(tmpfile.Name())
watcherFunc := func (err error) bool {
return false
}
go func() {
// Do updates here
}()
WatchFileChanges(tmpfile.Name(), watcherFunc)
}
关于multithreading - 如何测试在 goroutine 中监视文件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43468476/