2017-04-18 6 views
0

私は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を返してから配列にアサートすることをお奨めしました。もちろん、ゴルーチンが始まったので、テストはちょうどハングしてイベントを待っています。

このような関数をどのようにテストできますか?ファイルを更新/変更する別のスレッド(?)を開始するような方法はありますか?

答えて

0

このような関数をテストする方法はありますか?ファイルを更新/変更する別のスレッド(?)を開始しますか?

もちろん、必要な更新を行うゴルーチンを開始してください。

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) 
} 
+0

あなたのゴルーチンは決して呼び出されません。それはgo 1.7のコンパイラエラーです。 – Max

関連する問題