github.com/rzurga/go-swagger@v0.28.1-0.20211109195225-5d1f453ffa3a/cmd/swagger/commands/internal/cmdtest/output.go (about) 1 // Package cmdtest provides test utilities 2 // to assert the output of CLI commands 3 package cmdtest 4 5 import ( 6 "io" 7 "io/ioutil" 8 "os" 9 "strings" 10 "testing" 11 12 "github.com/stretchr/testify/assert" 13 "github.com/stretchr/testify/require" 14 ) 15 16 // AssertReadersContent compares the contents from io.Readers, optionally stripping blanks 17 func AssertReadersContent(t testing.TB, noBlanks bool, expected, actual io.Reader) bool { 18 e, err := ioutil.ReadAll(expected) 19 require.NoError(t, err) 20 21 a, err := ioutil.ReadAll(actual) 22 require.NoError(t, err) 23 24 var wants, got strings.Builder 25 _, _ = wants.Write(e) 26 _, _ = got.Write(a) 27 28 if noBlanks { 29 r := strings.NewReplacer(" ", "", "\t", "", "\n", "") 30 return assert.Equalf(t, r.Replace(wants.String()), r.Replace(got.String()), "expected:\n%s\ngot %s", wants.String(), got.String()) 31 } 32 return assert.Equal(t, wants.String(), got.String()) 33 } 34 35 // CatchStdOut captures the standard output from a runnable function. 36 // You shouln't run this in parallel. 37 func CatchStdOut(t testing.TB, runnable func() error) ([]byte, error) { 38 realStdout := os.Stdout 39 defer func() { os.Stdout = realStdout }() 40 r, fakeStdout, err := os.Pipe() 41 require.NoError(t, err) 42 os.Stdout = fakeStdout 43 e := runnable() 44 // need to close here, otherwise ReadAll never gets "EOF". 45 require.NoError(t, fakeStdout.Close()) 46 newOutBytes, err := ioutil.ReadAll(r) 47 require.NoError(t, err) 48 require.NoError(t, r.Close()) 49 return newOutBytes, e 50 }