notify_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. package watch
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/windmilleng/tilt/internal/logger"
  15. "github.com/windmilleng/tilt/internal/testutils/tempdir"
  16. )
  17. // Each implementation of the notify interface should have the same basic
  18. // behavior.
  19. func TestNoEvents(t *testing.T) {
  20. f := newNotifyFixture(t)
  21. defer f.tearDown()
  22. f.assertEvents()
  23. }
  24. func TestEventOrdering(t *testing.T) {
  25. f := newNotifyFixture(t)
  26. defer f.tearDown()
  27. count := 8
  28. dirs := make([]string, count)
  29. for i, _ := range dirs {
  30. dir := f.TempDir("watched")
  31. dirs[i] = dir
  32. err := f.notify.Add(dir)
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. }
  37. f.fsync()
  38. f.events = nil
  39. var expected []string
  40. for i, dir := range dirs {
  41. base := fmt.Sprintf("%d.txt", i)
  42. p := filepath.Join(dir, base)
  43. err := ioutil.WriteFile(p, []byte(base), os.FileMode(0777))
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. expected = append(expected, filepath.Join(dir, base))
  48. }
  49. f.assertEvents(expected...)
  50. }
  51. // Simulate a git branch switch that creates a bunch
  52. // of directories, creates files in them, then deletes
  53. // them all quickly. Make sure there are no errors.
  54. func TestGitBranchSwitch(t *testing.T) {
  55. f := newNotifyFixture(t)
  56. defer f.tearDown()
  57. count := 10
  58. dirs := make([]string, count)
  59. for i, _ := range dirs {
  60. dir := f.TempDir("watched")
  61. dirs[i] = dir
  62. err := f.notify.Add(dir)
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. }
  67. f.fsync()
  68. f.events = nil
  69. // consume all the events in the background
  70. ctx, cancel := context.WithCancel(context.Background())
  71. done := f.consumeEventsInBackground(ctx)
  72. for i, dir := range dirs {
  73. for j := 0; j < count; j++ {
  74. base := fmt.Sprintf("x/y/dir-%d/x.txt", j)
  75. p := filepath.Join(dir, base)
  76. f.WriteFile(p, "contents")
  77. }
  78. if i != 0 {
  79. os.RemoveAll(dir)
  80. }
  81. }
  82. cancel()
  83. err := <-done
  84. if err != nil {
  85. t.Fatal(err)
  86. }
  87. f.fsync()
  88. f.events = nil
  89. // Make sure the watch on the first dir still works.
  90. dir := dirs[0]
  91. path := filepath.Join(dir, "change")
  92. f.WriteFile(path, "hello\n")
  93. f.fsync()
  94. f.assertEvents(path)
  95. // Make sure there are no errors in the out stream
  96. assert.Equal(t, "", f.out.String())
  97. }
  98. func TestWatchesAreRecursive(t *testing.T) {
  99. f := newNotifyFixture(t)
  100. defer f.tearDown()
  101. root := f.TempDir("root")
  102. // add a sub directory
  103. subPath := filepath.Join(root, "sub")
  104. f.MkdirAll(subPath)
  105. // watch parent
  106. err := f.notify.Add(root)
  107. if err != nil {
  108. t.Fatal(err)
  109. }
  110. f.fsync()
  111. f.events = nil
  112. // change sub directory
  113. changeFilePath := filepath.Join(subPath, "change")
  114. _, err = os.OpenFile(changeFilePath, os.O_RDONLY|os.O_CREATE, 0666)
  115. if err != nil {
  116. t.Fatal(err)
  117. }
  118. f.assertEvents(changeFilePath)
  119. }
  120. func TestNewDirectoriesAreRecursivelyWatched(t *testing.T) {
  121. f := newNotifyFixture(t)
  122. defer f.tearDown()
  123. root := f.TempDir("root")
  124. // watch parent
  125. err := f.notify.Add(root)
  126. if err != nil {
  127. t.Fatal(err)
  128. }
  129. f.fsync()
  130. f.events = nil
  131. // add a sub directory
  132. subPath := filepath.Join(root, "sub")
  133. f.MkdirAll(subPath)
  134. // change something inside sub directory
  135. changeFilePath := filepath.Join(subPath, "change")
  136. _, err = os.OpenFile(changeFilePath, os.O_RDONLY|os.O_CREATE, 0666)
  137. if err != nil {
  138. t.Fatal(err)
  139. }
  140. f.assertEvents(subPath, changeFilePath)
  141. }
  142. func TestWatchNonExistentPath(t *testing.T) {
  143. f := newNotifyFixture(t)
  144. defer f.tearDown()
  145. root := f.TempDir("root")
  146. path := filepath.Join(root, "change")
  147. err := f.notify.Add(path)
  148. if err != nil {
  149. t.Fatal(err)
  150. }
  151. f.fsync()
  152. d1 := "hello\ngo\n"
  153. f.WriteFile(path, d1)
  154. f.assertEvents(path)
  155. }
  156. func TestWatchNonExistentPathDoesNotFireSiblingEvent(t *testing.T) {
  157. f := newNotifyFixture(t)
  158. defer f.tearDown()
  159. root := f.TempDir("root")
  160. watchedFile := filepath.Join(root, "a.txt")
  161. unwatchedSibling := filepath.Join(root, "b.txt")
  162. err := f.notify.Add(watchedFile)
  163. if err != nil {
  164. t.Fatal(err)
  165. }
  166. f.fsync()
  167. d1 := "hello\ngo\n"
  168. f.WriteFile(unwatchedSibling, d1)
  169. f.assertEvents()
  170. }
  171. func TestRemove(t *testing.T) {
  172. f := newNotifyFixture(t)
  173. defer f.tearDown()
  174. root := f.TempDir("root")
  175. path := filepath.Join(root, "change")
  176. d1 := "hello\ngo\n"
  177. f.WriteFile(path, d1)
  178. err := f.notify.Add(path)
  179. if err != nil {
  180. t.Fatal(err)
  181. }
  182. f.fsync()
  183. f.events = nil
  184. err = os.Remove(path)
  185. if err != nil {
  186. t.Fatal(err)
  187. }
  188. f.assertEvents(path)
  189. }
  190. func TestRemoveAndAddBack(t *testing.T) {
  191. f := newNotifyFixture(t)
  192. defer f.tearDown()
  193. path := filepath.Join(f.watched, "change")
  194. d1 := []byte("hello\ngo\n")
  195. err := ioutil.WriteFile(path, d1, 0644)
  196. if err != nil {
  197. t.Fatal(err)
  198. }
  199. err = f.notify.Add(path)
  200. if err != nil {
  201. t.Fatal(err)
  202. }
  203. f.assertEvents(path)
  204. err = os.Remove(path)
  205. if err != nil {
  206. t.Fatal(err)
  207. }
  208. f.assertEvents(path)
  209. f.events = nil
  210. err = ioutil.WriteFile(path, d1, 0644)
  211. if err != nil {
  212. t.Fatal(err)
  213. }
  214. f.assertEvents(path)
  215. }
  216. func TestSingleFile(t *testing.T) {
  217. f := newNotifyFixture(t)
  218. defer f.tearDown()
  219. root := f.TempDir("root")
  220. path := filepath.Join(root, "change")
  221. d1 := "hello\ngo\n"
  222. f.WriteFile(path, d1)
  223. err := f.notify.Add(path)
  224. if err != nil {
  225. t.Fatal(err)
  226. }
  227. f.fsync()
  228. d2 := []byte("hello\nworld\n")
  229. err = ioutil.WriteFile(path, d2, 0644)
  230. if err != nil {
  231. t.Fatal(err)
  232. }
  233. f.assertEvents(path)
  234. }
  235. func TestWriteBrokenLink(t *testing.T) {
  236. f := newNotifyFixture(t)
  237. defer f.tearDown()
  238. link := filepath.Join(f.watched, "brokenLink")
  239. missingFile := filepath.Join(f.watched, "missingFile")
  240. err := os.Symlink(missingFile, link)
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. f.assertEvents(link)
  245. }
  246. func TestWriteGoodLink(t *testing.T) {
  247. f := newNotifyFixture(t)
  248. defer f.tearDown()
  249. goodFile := filepath.Join(f.watched, "goodFile")
  250. err := ioutil.WriteFile(goodFile, []byte("hello"), 0644)
  251. if err != nil {
  252. t.Fatal(err)
  253. }
  254. link := filepath.Join(f.watched, "goodFileSymlink")
  255. err = os.Symlink(goodFile, link)
  256. if err != nil {
  257. t.Fatal(err)
  258. }
  259. f.assertEvents(goodFile, link)
  260. }
  261. func TestWatchBrokenLink(t *testing.T) {
  262. f := newNotifyFixture(t)
  263. defer f.tearDown()
  264. newRoot, err := NewDir(t.Name())
  265. if err != nil {
  266. t.Fatal(err)
  267. }
  268. defer newRoot.TearDown()
  269. link := filepath.Join(newRoot.Path(), "brokenLink")
  270. missingFile := filepath.Join(newRoot.Path(), "missingFile")
  271. err = os.Symlink(missingFile, link)
  272. if err != nil {
  273. t.Fatal(err)
  274. }
  275. err = f.notify.Add(newRoot.Path())
  276. if err != nil {
  277. t.Fatal(err)
  278. }
  279. os.Remove(link)
  280. f.assertEvents(link)
  281. }
  282. func TestMoveAndReplace(t *testing.T) {
  283. f := newNotifyFixture(t)
  284. defer f.tearDown()
  285. root := f.TempDir("root")
  286. file := filepath.Join(root, "myfile")
  287. f.WriteFile(file, "hello")
  288. err := f.notify.Add(file)
  289. if err != nil {
  290. t.Fatal(err)
  291. }
  292. tmpFile := filepath.Join(root, ".myfile.swp")
  293. f.WriteFile(tmpFile, "world")
  294. err = os.Rename(tmpFile, file)
  295. if err != nil {
  296. t.Fatal(err)
  297. }
  298. f.assertEvents(file)
  299. }
  300. func TestWatchBothDirAndFile(t *testing.T) {
  301. f := newNotifyFixture(t)
  302. defer f.tearDown()
  303. dir := f.JoinPath("foo")
  304. fileA := f.JoinPath("foo", "a")
  305. fileB := f.JoinPath("foo", "b")
  306. f.WriteFile(fileA, "a")
  307. f.WriteFile(fileB, "b")
  308. f.watch(fileA)
  309. f.watch(dir)
  310. f.fsync()
  311. f.events = nil
  312. f.WriteFile(fileB, "b-new")
  313. f.assertEvents(fileB)
  314. }
  315. func TestWatchNonexistentFileInNonexistentDirectoryCreatedSimultaneously(t *testing.T) {
  316. f := newNotifyFixture(t)
  317. defer f.tearDown()
  318. root := f.JoinPath("root")
  319. err := os.Mkdir(root, 0777)
  320. if err != nil {
  321. t.Fatal(err)
  322. }
  323. file := f.JoinPath("root", "parent", "a")
  324. f.watch(file)
  325. f.fsync()
  326. f.events = nil
  327. f.WriteFile(file, "hello")
  328. f.assertEvents(file)
  329. }
  330. func TestWatchNonexistentDirectory(t *testing.T) {
  331. f := newNotifyFixture(t)
  332. defer f.tearDown()
  333. root := f.JoinPath("root")
  334. err := os.Mkdir(root, 0777)
  335. if err != nil {
  336. t.Fatal(err)
  337. }
  338. parent := f.JoinPath("parent")
  339. file := f.JoinPath("parent", "a")
  340. f.watch(parent)
  341. f.fsync()
  342. f.events = nil
  343. err = os.Mkdir(parent, 0777)
  344. if err != nil {
  345. t.Fatal(err)
  346. }
  347. if runtime.GOOS == "darwin" {
  348. // for directories that were the root of an Add, we don't report creation, cf. watcher_darwin.go
  349. f.assertEvents()
  350. } else {
  351. f.assertEvents(parent)
  352. }
  353. f.WriteFile(file, "hello")
  354. if runtime.GOOS == "darwin" {
  355. // mac doesn't return the dir change as part of file creation
  356. f.assertEvents(file)
  357. } else {
  358. f.assertEvents(parent, file)
  359. }
  360. }
  361. // doesn't work on linux
  362. // func TestWatchNonexistentFileInNonexistentDirectory(t *testing.T) {
  363. // f := newNotifyFixture(t)
  364. // defer f.tearDown()
  365. // root := f.JoinPath("root")
  366. // err := os.Mkdir(root, 0777)
  367. // if err != nil {
  368. // t.Fatal(err)
  369. // }
  370. // parent := f.JoinPath("parent")
  371. // file := f.JoinPath("parent", "a")
  372. // f.watch(file)
  373. // f.assertEvents()
  374. // err = os.Mkdir(parent, 0777)
  375. // if err != nil {
  376. // t.Fatal(err)
  377. // }
  378. // f.assertEvents()
  379. // f.WriteFile(file, "hello")
  380. // f.assertEvents(file)
  381. // }
  382. type notifyFixture struct {
  383. out *bytes.Buffer
  384. *tempdir.TempDirFixture
  385. notify Notify
  386. watched string
  387. events []FileEvent
  388. }
  389. func newNotifyFixture(t *testing.T) *notifyFixture {
  390. out := bytes.NewBuffer(nil)
  391. notify, err := NewWatcher(logger.NewLogger(logger.DebugLvl, out))
  392. if err != nil {
  393. t.Fatal(err)
  394. }
  395. f := tempdir.NewTempDirFixture(t)
  396. watched := f.TempDir("watched")
  397. err = notify.Add(watched)
  398. if err != nil {
  399. t.Fatal(err)
  400. }
  401. return &notifyFixture{
  402. TempDirFixture: f,
  403. watched: watched,
  404. notify: notify,
  405. out: out,
  406. }
  407. }
  408. func (f *notifyFixture) watch(path string) {
  409. err := f.notify.Add(path)
  410. if err != nil {
  411. f.T().Fatalf("notify.Add: %s", path)
  412. }
  413. }
  414. func (f *notifyFixture) assertEvents(expected ...string) {
  415. f.fsync()
  416. if len(f.events) != len(expected) {
  417. f.T().Fatalf("Got %d events (expected %d): %v %v", len(f.events), len(expected), f.events, expected)
  418. }
  419. for i, actual := range f.events {
  420. e := FileEvent{expected[i]}
  421. if actual != e {
  422. f.T().Fatalf("Got event %v (expected %v)", actual, e)
  423. }
  424. }
  425. }
  426. func (f *notifyFixture) consumeEventsInBackground(ctx context.Context) chan error {
  427. done := make(chan error)
  428. go func() {
  429. for {
  430. select {
  431. case <-ctx.Done():
  432. close(done)
  433. return
  434. case err := <-f.notify.Errors():
  435. done <- err
  436. close(done)
  437. return
  438. case <-f.notify.Events():
  439. }
  440. }
  441. }()
  442. return done
  443. }
  444. func (f *notifyFixture) fsync() {
  445. syncPathBase := fmt.Sprintf("sync-%d.txt", time.Now().UnixNano())
  446. syncPath := filepath.Join(f.watched, syncPathBase)
  447. anySyncPath := filepath.Join(f.watched, "sync-")
  448. timeout := time.After(time.Second)
  449. f.WriteFile(syncPath, fmt.Sprintf("%s", time.Now()))
  450. F:
  451. for {
  452. select {
  453. case err := <-f.notify.Errors():
  454. f.T().Fatal(err)
  455. case event := <-f.notify.Events():
  456. if strings.Contains(event.Path, syncPath) {
  457. break F
  458. }
  459. if strings.Contains(event.Path, anySyncPath) {
  460. continue
  461. }
  462. // Don't bother tracking duplicate changes to the same path
  463. // for testing.
  464. if len(f.events) > 0 && f.events[len(f.events)-1].Path == event.Path {
  465. continue
  466. }
  467. f.events = append(f.events, event)
  468. case <-timeout:
  469. f.T().Fatalf("fsync: timeout")
  470. }
  471. }
  472. }
  473. func (f *notifyFixture) tearDown() {
  474. err := f.notify.Close()
  475. if err != nil {
  476. f.T().Fatal(err)
  477. }
  478. // drain channels from watcher
  479. go func() {
  480. for _ = range f.notify.Events() {
  481. }
  482. }()
  483. go func() {
  484. for _ = range f.notify.Errors() {
  485. }
  486. }()
  487. f.TempDirFixture.TearDown()
  488. }