file_test.go 977 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // +build !windows
  2. package watcher
  3. import (
  4. "bufio"
  5. "os"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. type mockNotifier struct {
  11. eventPath string
  12. }
  13. func (n *mockNotifier) WatcherItemDidChange(path string) {
  14. n.eventPath = path
  15. }
  16. func (n *mockNotifier) WatcherDidError(err error) {
  17. }
  18. func TestFileChanged(t *testing.T) {
  19. filePath := "test_file"
  20. f, err := os.Create(filePath)
  21. assert.NoError(t, err)
  22. defer func() {
  23. f.Close()
  24. os.Remove(filePath)
  25. }()
  26. service, err := NewFile()
  27. assert.NoError(t, err)
  28. err = service.Add(filePath)
  29. assert.NoError(t, err)
  30. n := &mockNotifier{}
  31. go service.Start(n)
  32. f.Sync()
  33. w := bufio.NewWriter(f)
  34. _, err = w.WriteString("hello Austin, do you like my file watcher?\n")
  35. assert.NoError(t, err)
  36. err = w.Flush()
  37. assert.NoError(t, err)
  38. // give it time to trigger
  39. time.Sleep(20 * time.Millisecond)
  40. service.Shutdown()
  41. assert.Equal(t, filePath, n.eventPath, "notifier didn't get an new file write event")
  42. }