github.com/bazelbuild/remote-apis-sdks@v0.0.0-20240425170053-8a36686a6350/go/pkg/outerr/outerr_test.go (about) 1 package outerr 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "os" 8 "testing" 9 ) 10 11 func TestRecordingOutErr(t *testing.T) { 12 t.Parallel() 13 o := NewRecordingOutErr() 14 o.WriteOut([]byte("hello")) 15 o.WriteErr([]byte("world")) 16 gotOut := o.Stdout() 17 if !bytes.Equal(gotOut, []byte("hello")) { 18 t.Errorf("expected o.Stdout() to return hello, got %v", gotOut) 19 } 20 gotErr := o.Stderr() 21 if !bytes.Equal(gotErr, []byte("world")) { 22 t.Errorf("expected o.Stderr() to return hello, got %v", gotErr) 23 } 24 } 25 26 func TestSystemOutErr(t *testing.T) { 27 // Capture the actual system stdout/stderr. 28 r, w, err := os.Pipe() 29 if err != nil { 30 t.Fatalf("error calling os.Pipe() = %v", err) 31 } 32 33 stdout := os.Stdout 34 fmt.Printf("capturing stdout to %v\n", w) 35 os.Stdout = w 36 defer func() { 37 fmt.Printf("resetting stdout to %v", stdout) 38 os.Stdout = stdout 39 }() 40 41 stderr := os.Stderr 42 os.Stderr = w 43 defer func() { 44 os.Stderr = stderr 45 }() 46 47 // We have to replicate the construction in the test instead of using SystemOutErr directly. 48 systemOutErr := NewStreamOutErr(os.Stdout, os.Stderr) 49 systemOutErr.WriteOut([]byte("hello ")) 50 systemOutErr.WriteErr([]byte("world")) 51 52 w.Close() 53 54 var buf bytes.Buffer 55 io.Copy(&buf, r) 56 57 if buf.String() != "hello world" { 58 t.Errorf("expected stdout+stderr to equal \"hello world\", got %v", buf.String()) 59 } 60 } 61 62 func TestWriters(t *testing.T) { 63 t.Parallel() 64 oe := NewRecordingOutErr() 65 o, e := NewOutWriter(oe), NewErrWriter(oe) 66 if n, err := o.Write([]byte("hello")); n != 5 || err != nil { 67 t.Errorf("expected o.Write(\"hello\") to return 5, nil; got %d, %v", n, err) 68 } 69 if n, err := e.Write([]byte("world")); n != 5 || err != nil { 70 t.Errorf("expected e.Write(\"world\") to return 5, nil; got %d, %v", n, err) 71 } 72 if got := oe.Stdout(); !bytes.Equal(got, []byte("hello")) { 73 t.Errorf("expected oe.Stdout() to return hello, got %v", got) 74 } 75 if got := oe.Stderr(); !bytes.Equal(got, []byte("world")) { 76 t.Errorf("expected oe.Stderr() to return world, got %v", got) 77 } 78 }