github.com/Finschia/finschia-sdk@v0.48.1/testutil/ioutil.go (about) 1 package testutil 2 3 import ( 4 "bytes" 5 "io" 6 "os" 7 "strings" 8 "testing" 9 10 "github.com/spf13/cobra" 11 "github.com/stretchr/testify/require" 12 ) 13 14 // BufferReader is implemented by types that read from a string buffer. 15 type BufferReader interface { 16 io.Reader 17 Reset(string) 18 } 19 20 // BufferWriter is implemented by types that write to a buffer. 21 type BufferWriter interface { 22 io.Writer 23 Reset() 24 Bytes() []byte 25 String() string 26 } 27 28 // ApplyMockIO replaces stdin/out/err with buffers that can be used during testing. 29 // Returns an input BufferReader and an output BufferWriter. 30 func ApplyMockIO(c *cobra.Command) (BufferReader, BufferWriter) { 31 mockIn := strings.NewReader("") 32 mockOut := bytes.NewBufferString("") 33 34 c.SetIn(mockIn) 35 c.SetOut(mockOut) 36 c.SetErr(mockOut) 37 38 return mockIn, mockOut 39 } 40 41 // ApplyMockIODiscardOutputs replaces a cobra.Command output and error streams with a dummy io.Writer. 42 // Replaces and returns the io.Reader associated to the cobra.Command input stream. 43 func ApplyMockIODiscardOutErr(c *cobra.Command) BufferReader { 44 mockIn := strings.NewReader("") 45 46 c.SetIn(mockIn) 47 c.SetOut(io.Discard) 48 c.SetErr(io.Discard) 49 50 return mockIn 51 } 52 53 // Write the given string to a new temporary file. 54 // Returns an open file for the test to use. 55 func WriteToNewTempFile(t testing.TB, s string) *os.File { 56 t.Helper() 57 58 fp := TempFile(t) 59 _, err := fp.WriteString(s) 60 61 require.Nil(t, err) 62 63 return fp 64 } 65 66 // TempFile returns a writable temporary file for the test to use. 67 func TempFile(t testing.TB) *os.File { 68 t.Helper() 69 70 fp, err := os.CreateTemp(t.TempDir(), "") 71 require.NoError(t, err) 72 73 return fp 74 }