gotest.tools/gotestsum@v1.11.0/internal/filewatcher/watch_unix_test.go (about) 1 //go:build !windows && !aix 2 // +build !windows,!aix 3 4 package filewatcher 5 6 import ( 7 "context" 8 "io" 9 "testing" 10 "time" 11 12 "github.com/google/go-cmp/cmp" 13 "github.com/google/go-cmp/cmp/cmpopts" 14 "gotest.tools/v3/assert" 15 "gotest.tools/v3/fs" 16 ) 17 18 func TestWatch(t *testing.T) { 19 ctx, cancel := context.WithCancel(context.Background()) 20 t.Cleanup(cancel) 21 dir := fs.NewDir(t, t.Name()) 22 23 r, w := io.Pipe() 24 patchStdin(t, r) 25 patchFloodThreshold(t, 0) 26 27 chEvents := make(chan Event, 1) 28 capture := func(event Event) error { 29 chEvents <- event 30 return nil 31 } 32 33 go func() { 34 err := Watch(ctx, []string{dir.Path()}, capture) 35 assert.Check(t, err) 36 }() 37 38 t.Run("run all tests", func(t *testing.T) { 39 _, err := w.Write([]byte("a")) 40 assert.NilError(t, err) 41 42 event := <-chEvents 43 expected := Event{PkgPath: "./..."} 44 assert.DeepEqual(t, event, expected, cmpEvent) 45 }) 46 47 t.Run("run tests on file change", func(t *testing.T) { 48 fs.Apply(t, dir, fs.WithFile("file.go", "")) 49 50 event := <-chEvents 51 expected := Event{PkgPath: "./" + dir.Path()} 52 assert.DeepEqual(t, event, expected, cmpEvent) 53 54 t.Run("and rerun", func(t *testing.T) { 55 _, err := w.Write([]byte("r")) 56 assert.NilError(t, err) 57 58 event := <-chEvents 59 expected := Event{PkgPath: "./" + dir.Path(), useLastPath: true} 60 assert.DeepEqual(t, event, expected, cmpEvent) 61 }) 62 63 t.Run("and debug", func(t *testing.T) { 64 _, err := w.Write([]byte("d")) 65 assert.NilError(t, err) 66 67 event := <-chEvents 68 expected := Event{ 69 PkgPath: "./" + dir.Path(), 70 useLastPath: true, 71 Debug: true, 72 } 73 assert.DeepEqual(t, event, expected, cmpEvent) 74 }) 75 76 t.Run("and update", func(t *testing.T) { 77 _, err := w.Write([]byte("u")) 78 assert.NilError(t, err) 79 80 event := <-chEvents 81 expected := Event{ 82 PkgPath: "./" + dir.Path(), 83 Args: []string{"-update"}, 84 useLastPath: true, 85 } 86 assert.DeepEqual(t, event, expected, cmpEvent) 87 }) 88 }) 89 } 90 91 var cmpEvent = cmp.Options{ 92 cmp.AllowUnexported(Event{}), 93 cmpopts.IgnoreTypes(make(chan struct{})), 94 } 95 96 func patchStdin(t *testing.T, in io.Reader) { 97 orig := stdin 98 stdin = in 99 t.Cleanup(func() { 100 stdin = orig 101 }) 102 } 103 104 func patchFloodThreshold(t *testing.T, d time.Duration) { 105 orig := floodThreshold 106 floodThreshold = d 107 t.Cleanup(func() { 108 floodThreshold = orig 109 }) 110 }