| 13 | ) |
| 14 | |
| 15 | func TestWatch(t *testing.T) { |
| 16 | t.Run("edit", func(t *testing.T) { |
| 17 | t.Parallel() |
| 18 | ch := make(chan struct{}, 2) |
| 19 | f, _ := ioutil.TempFile(".", "*") |
| 20 | defer os.Remove(f.Name()) |
| 21 | |
| 22 | ioutil.WriteFile(f.Name(), []byte(`foo`), os.ModePerm) |
| 23 | |
| 24 | w := File{f.Name()} |
| 25 | ctx, cancel := context.WithCancel(context.Background()) |
| 26 | defer cancel() |
| 27 | |
| 28 | go w.Watch(ctx, func() error { |
| 29 | ch <- struct{}{} |
| 30 | return nil |
| 31 | }) |
| 32 | time.Sleep(time.Second) |
| 33 | ioutil.WriteFile(f.Name(), []byte(`bar`), os.ModePerm) |
| 34 | <-ch |
| 35 | }) |
| 36 | |
| 37 | t.Run("delete", func(t *testing.T) { |
| 38 | t.Parallel() |
| 39 | var ( |
| 40 | ch chan struct{} |
| 41 | called atomic.Bool |
| 42 | ) |
| 43 | ch = make(chan struct{}) |
| 44 | f, _ := ioutil.TempFile(".", "*") |
| 45 | |
| 46 | ioutil.WriteFile(f.Name(), []byte(`foo`), os.ModePerm) |
| 47 | |
| 48 | w := File{f.Name()} |
| 49 | ctx, cancel := context.WithCancel(context.Background()) |
| 50 | defer cancel() |
| 51 | |
| 52 | go func() { |
| 53 | w.Watch(ctx, func() error { |
| 54 | called.Store(true) |
| 55 | ch <- struct{}{} |
| 56 | return nil |
| 57 | }) |
| 58 | ch <- struct{}{} |
| 59 | }() |
| 60 | time.Sleep(time.Second) |
| 61 | os.Remove(f.Name()) |
| 62 | <-ch |
| 63 | assert.False(t, called.Load()) |
| 64 | }) |
| 65 | |
| 66 | t.Run("reload failed", func(t *testing.T) { |
| 67 | t.Parallel() |
| 68 | var ( |
| 69 | ch chan struct{} |
| 70 | called atomic.Bool |
| 71 | ) |
| 72 | ch = make(chan struct{}) |