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