multithreading - 如何测试在 goroutine 中监视文件的函数

标签 multithreading unit-testing go

我有一个函数可以通过 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/

相关文章:

c - 阅读是否涉及多线程应用程序中的任何锁定?

python - Python 中 GIL 的新实现是否处理了竞争条件问题?

unit-testing - 如何使用 ng-template 测试模态元素以及触发它的操作?

c# - 如何在 AutoFixture 中设置更复杂(类似 IoC)的注册

scala - 从 rpc 调用到其他节点的错误?

Go heap.Interface 作为一个结构

c++ - 这些锁定的内存访问是否等效?

.net - 一旦线程加入,如何通知线程停止等待互斥体?

java - JUnit 中未调用 setUp()

xml - 在 Go 中将 XML 代码写入 XML 文件