github.com/lineaje-labs/syft@v0.98.1-0.20231227153149-9e393f60ff1b/cmd/syft/internal/ui/capture_test.go (about) 1 package ui 2 3 import ( 4 "bytes" 5 "io" 6 "os" 7 "testing" 8 9 "github.com/stretchr/testify/require" 10 ) 11 12 func Test_capture(t *testing.T) { 13 r, w, _ := os.Pipe() 14 t.Logf("pipe1: %+v", w) 15 16 buf := &bytes.Buffer{} 17 buf2 := &bytes.Buffer{} 18 19 go func() { 20 // write to the main file (e.g. os.Stdout) 21 _, _ = w.WriteString("write1") 22 23 // capture the output to the provided buffer 24 restoreInitial := capture(&w, buf, 1024) 25 t.Logf("pipe2: %+v", w) 26 _, _ = w.WriteString("write2") 27 28 // capture output nested 29 restoreFirstCapture := capture(&w, buf2, 1024) 30 t.Logf("pipe3: %+v", w) 31 _, _ = w.WriteString("write3") 32 33 // discard file used to write the "write3" 34 restoreFirstCapture() 35 36 // restore should block until all output has been captured, so it's safe to read buf2 here 37 require.Equal(t, "write3", buf2.String()) 38 39 // restore should be safe to call multiple times 40 restoreFirstCapture() 41 require.Equal(t, "write3", buf2.String()) 42 43 // write again to the initial buffer 44 t.Logf("pipe2+: %+v", w) 45 _, _ = w.WriteString("write2+") 46 47 // restore the initial file (e.g. os.Stdout) and write more to it 48 restoreInitial() 49 t.Logf("pipe1+: %+v", w) 50 _, _ = w.WriteString("write1+") 51 52 // close the pipe to continue with the io.ReadAll, below 53 _ = w.Close() 54 }() 55 56 got, err := io.ReadAll(r) 57 require.NoError(t, err) 58 require.Equal(t, "write1write1+", string(got)) 59 60 require.Equal(t, "write2write2+", buf.String()) 61 } 62 63 func Test_captureBufSizes(t *testing.T) { 64 _, w, _ := os.Pipe() 65 66 buf := &bytes.Buffer{} 67 restore := capture(&w, buf, 200) 68 69 line := "line1\nline2\nline3" 70 71 _, err := w.WriteString(line) 72 require.NoError(t, err) 73 74 restore() 75 require.Equal(t, line, buf.String()) 76 77 buf.Reset() 78 restore = capture(&w, buf, 2) 79 80 _, err = w.WriteString(line) 81 require.NoError(t, err) 82 83 restore() 84 require.Equal(t, line, buf.String()) 85 }