| // Copyright 2010 The Go Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style |
| // license that can be found in the LICENSE file. |
| |
| // +build freebsd openbsd netbsd darwin linux |
| |
| package fsnotify |
| |
| import ( |
| "os" |
| "path/filepath" |
| "testing" |
| "time" |
| ) |
| |
| func TestFsnotifyAttrib(t *testing.T) { |
| // Create an fsnotify watcher instance and initialize it |
| watcher, err := NewWatcher() |
| if err != nil { |
| t.Fatalf("NewWatcher() failed: %s", err) |
| } |
| |
| const testDir string = "_test" |
| |
| // Create directory to watch |
| if err := os.Mkdir(testDir, 0777); err != nil { |
| t.Fatalf("Failed to create test directory: %s", err) |
| } |
| defer os.RemoveAll(testDir) |
| |
| // Receive errors on the error channel on a separate goroutine |
| go func() { |
| for err := range watcher.Error { |
| t.Fatalf("error received: %s", err) |
| } |
| }() |
| |
| const testFile string = "_test/TestFsnotifyAttrib.testfile" |
| |
| // Receive events on the event channel on a separate goroutine |
| eventstream := watcher.Event |
| var attribReceived counter |
| done := make(chan bool) |
| go func() { |
| for event := range eventstream { |
| // Only count relevant events |
| if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { |
| if event.IsModify() { |
| attribReceived.increment() |
| } |
| t.Logf("event received: %s", event) |
| } else { |
| t.Logf("unexpected event received: %s", event) |
| } |
| } |
| done <- true |
| }() |
| |
| // Create a file |
| // This should add at least one event to the fsnotify event queue |
| var f *os.File |
| f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) |
| if err != nil { |
| t.Fatalf("creating test file failed: %s", err) |
| } |
| f.Sync() |
| |
| f.WriteString("data") |
| f.Sync() |
| f.Close() |
| |
| // Add a watch for testFile |
| err = watcher.Watch(testFile) |
| if err != nil { |
| t.Fatalf("Watcher.Watch() failed: %s", err) |
| } |
| |
| os.Chmod(testFile, 0777) |
| if err != nil { |
| t.Fatalf("chmod failed: %s", err) |
| } |
| |
| // We expect this event to be received almost immediately, but let's wait 500 ms to be sure |
| time.Sleep(500 * time.Millisecond) |
| if attribReceived.value() == 0 { |
| t.Fatal("fsnotify attribute events have not received after 500 ms") |
| } |
| |
| // Try closing the fsnotify instance |
| t.Log("calling Close()") |
| watcher.Close() |
| t.Log("waiting for the event channel to become closed...") |
| select { |
| case <-done: |
| t.Log("event channel closed") |
| case <-time.After(1e9): |
| t.Fatal("event stream was not closed after 1 second") |
| } |
| } |