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