file_test.go 957 B

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