Skip to content

Commit

Permalink
testutil: add ApplyMockIODiscardOutErr, simplify existing functions (c…
Browse files Browse the repository at this point in the history
  • Loading branch information
Alessio Treglia authored Jul 10, 2020
1 parent d269eaf commit 255ed06
Show file tree
Hide file tree
Showing 16 changed files with 63 additions and 36 deletions.
5 changes: 2 additions & 3 deletions client/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ package client_test
import (
"context"
"fmt"
"io/ioutil"
"testing"

"github.com/spf13/cobra"
"github.com/stretchr/testify/require"

"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/testutil"
)

func TestValidateCmd(t *testing.T) {
Expand Down Expand Up @@ -106,8 +106,7 @@ func TestSetCmdClientContextHandler(t *testing.T) {
ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{})

cmd := newCmd()
cmd.SetOut(ioutil.Discard)
cmd.SetErr(ioutil.Discard)
_ = testutil.ApplyMockIODiscardOutErr(cmd)
cmd.SetArgs(tc.args)

require.NoError(t, cmd.ExecuteContext(ctx))
Expand Down
4 changes: 2 additions & 2 deletions client/keys/add_ledger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func Test_runAddCmdLedgerWithCustomCoinType(t *testing.T) {
fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest),
})

mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)
mockIn.Reset("test1234\ntest1234\n")
require.NoError(t, cmd.Execute())

Expand Down Expand Up @@ -85,7 +85,7 @@ func Test_runAddCmdLedgerWithCustomCoinType(t *testing.T) {
func Test_runAddCmdLedger(t *testing.T) {
cmd := AddKeyCommand()
cmd.Flags().AddFlagSet(Commands().PersistentFlags())
mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)

// Prepare a keybase
kbHome, kbCleanUp := testutil.NewTestCaseDir(t)
Expand Down
2 changes: 1 addition & 1 deletion client/keys/add_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func Test_runAddCmdBasic(t *testing.T) {
cmd := AddKeyCommand()
cmd.Flags().AddFlagSet(Commands().PersistentFlags())

mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)

kbHome, kbCleanUp := testutil.NewTestCaseDir(t)
require.NotNil(t, kbHome)
Expand Down
2 changes: 1 addition & 1 deletion client/keys/delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
func Test_runDeleteCmd(t *testing.T) {
cmd := DeleteKeyCommand()
cmd.Flags().AddFlagSet(Commands().PersistentFlags())
mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)

yesF, _ := cmd.Flags().GetBool(flagYes)
forceF, _ := cmd.Flags().GetBool(flagForce)
Expand Down
2 changes: 1 addition & 1 deletion client/keys/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
func Test_runExportCmd(t *testing.T) {
cmd := ExportKeyCommand()
cmd.Flags().AddFlagSet(Commands().PersistentFlags())
mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)

// Now add a temporary keybase
kbHome, cleanUp := testutil.NewTestCaseDir(t)
Expand Down
2 changes: 1 addition & 1 deletion client/keys/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
func Test_runImportCmd(t *testing.T) {
cmd := ImportKeyCommand()
cmd.Flags().AddFlagSet(Commands().PersistentFlags())
mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)

// Now add a temporary keybase
kbHome, cleanUp := testutil.NewTestCaseDir(t)
Expand Down
2 changes: 1 addition & 1 deletion client/keys/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func Test_runListCmd(t *testing.T) {
kbHome2, cleanUp2 := testutil.NewTestCaseDir(t)
t.Cleanup(cleanUp2)

mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)
kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome2, mockIn)
require.NoError(t, err)

Expand Down
6 changes: 2 additions & 4 deletions client/keys/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package keys

import (
"fmt"
"io/ioutil"
"testing"

"github.com/otiai10/copy"
Expand All @@ -16,8 +15,7 @@ import (

func Test_runMigrateCmd(t *testing.T) {
cmd := AddKeyCommand()
cmd.SetErr(ioutil.Discard)
cmd.SetOut(ioutil.Discard)
_ = testutil.ApplyMockIODiscardOutErr(cmd)
cmd.Flags().AddFlagSet(Commands().PersistentFlags())

kbHome, kbCleanUp := testutil.NewTestCaseDir(t)
Expand All @@ -35,7 +33,7 @@ func Test_runMigrateCmd(t *testing.T) {

cmd = MigrateCommand()
cmd.Flags().AddFlagSet(Commands().PersistentFlags())
mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)

cmd.SetArgs([]string{
fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome),
Expand Down
9 changes: 3 additions & 6 deletions client/keys/mnemonic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package keys

import (
"fmt"
"io/ioutil"
"strings"
"testing"

Expand All @@ -13,24 +12,22 @@ import (

func Test_RunMnemonicCmdNormal(t *testing.T) {
cmd := MnemonicKeyCommand()
cmd.SetErr(ioutil.Discard)
cmd.SetOut(ioutil.Discard)
_ = testutil.ApplyMockIODiscardOutErr(cmd)
cmd.SetArgs([]string{})
require.NoError(t, cmd.Execute())
}

func Test_RunMnemonicCmdUser(t *testing.T) {
cmd := MnemonicKeyCommand()
cmd.SetErr(ioutil.Discard)
cmd.SetOut(ioutil.Discard)
_ = testutil.ApplyMockIODiscardOutErr(cmd)

cmd.SetArgs([]string{fmt.Sprintf("--%s=1", flagUserEntropy)})
err := cmd.Execute()
require.Error(t, err)
require.Equal(t, "EOF", err.Error())

// Try again
mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)
mockIn.Reset("Hi!\n")
err = cmd.Execute()
require.Error(t, err)
Expand Down
2 changes: 1 addition & 1 deletion client/keys/show_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func Test_showKeysCmd(t *testing.T) {
func Test_runShowCmd(t *testing.T) {
cmd := ShowKeysCmd()
cmd.Flags().AddFlagSet(Commands().PersistentFlags())
mockIn, _, _ := testutil.ApplyMockIO(cmd)
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)

cmd.SetArgs([]string{"invalid"})
require.EqualError(t, cmd.Execute(), "invalid is not a valid name or address: decoding bech32 failed: invalid bech32 string length 7")
Expand Down
36 changes: 32 additions & 4 deletions testutil/ioutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package testutil

import (
"bytes"
"io"
"io/ioutil"
"os"
"strings"
Expand All @@ -20,15 +21,42 @@ func NewTestCaseDir(t testing.TB) (string, func()) {
return dir, func() { os.RemoveAll(dir) }
}

// 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()
String() string
}

// ApplyMockIO replaces stdin/out/err with buffers that can be used during testing.
func ApplyMockIO(c *cobra.Command) (*strings.Reader, *bytes.Buffer, *bytes.Buffer) {
// Returns an input BufferReader and an output BufferWriter.
func ApplyMockIO(c *cobra.Command) (BufferReader, BufferWriter) {
mockIn := strings.NewReader("")
mockOut := bytes.NewBufferString("")
mockErr := bytes.NewBufferString("")

c.SetIn(mockIn)
c.SetOut(mockOut)
c.SetErr(mockErr)
return mockIn, mockOut, mockErr
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.
Expand Down
12 changes: 11 additions & 1 deletion testutil/ioutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ func TestNewTestCaseDir(t *testing.T) {

func TestApplyMockIO(t *testing.T) {
cmd := &cobra.Command{}

oldStdin := cmd.InOrStdin()
oldStdout := cmd.OutOrStdout()
oldStderr := cmd.ErrOrStderr()
Expand All @@ -39,6 +38,7 @@ func TestApplyMockIO(t *testing.T) {
require.NotEqual(t, cmd.InOrStdin(), oldStdin)
require.NotEqual(t, cmd.OutOrStdout(), oldStdout)
require.NotEqual(t, cmd.ErrOrStderr(), oldStderr)
require.Equal(t, cmd.ErrOrStderr(), cmd.OutOrStdout())
}

func TestWriteToNewTempFile(t *testing.T) {
Expand All @@ -53,3 +53,13 @@ func TestWriteToNewTempFile(t *testing.T) {

require.NoFileExists(t, tempfile.Name())
}

func TestApplyMockIODiscardOutErr(t *testing.T) {
cmd := &cobra.Command{}
oldStdin := cmd.InOrStdin()

testutil.ApplyMockIODiscardOutErr(cmd)
require.NotEqual(t, cmd.InOrStdin(), oldStdin)
require.Equal(t, cmd.OutOrStdout(), ioutil.Discard)
require.Equal(t, cmd.ErrOrStderr(), ioutil.Discard)
}
2 changes: 1 addition & 1 deletion version/version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ go version go1.14 linux/amd64`

func Test_runVersionCmd(t *testing.T) {
cmd := NewVersionCommand()
_, mockOut, _ := testutil.ApplyMockIO(cmd)
_, mockOut := testutil.ApplyMockIO(cmd)

cmd.SetArgs([]string{
fmt.Sprintf("--%s=''", cli.OutputFlag),
Expand Down
3 changes: 1 addition & 2 deletions x/auth/client/cli/broadcast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ func TestGetBroadcastCommand_OfflineFlag(t *testing.T) {
clientCtx = clientCtx.WithTxGenerator(simappparams.MakeEncodingConfig().TxGenerator)

cmd := GetBroadcastCommand(clientCtx)
cmd.SetOut(ioutil.Discard)
cmd.SetErr(ioutil.Discard)
_ = testutil.ApplyMockIODiscardOutErr(cmd)
cmd.SetArgs([]string{fmt.Sprintf("--%s=true", flags.FlagOffline), ""})

require.EqualError(t, cmd.Execute(), "cannot broadcast tx during offline mode")
Expand Down
7 changes: 2 additions & 5 deletions x/auth/client/cli/encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cli

import (
"encoding/base64"
"io/ioutil"
"testing"

"github.com/stretchr/testify/require"
Expand All @@ -21,8 +20,7 @@ func TestGetCommandEncode(t *testing.T) {
WithJSONMarshaler(encodingConfig.Marshaler)

cmd := GetEncodeCommand(clientCtx)
cmd.SetErr(ioutil.Discard)
cmd.SetOut(ioutil.Discard)
_ = testutil.ApplyMockIODiscardOutErr(cmd)

authtypes.RegisterCodec(encodingConfig.Amino)
sdk.RegisterCodec(encodingConfig.Amino)
Expand Down Expand Up @@ -51,8 +49,7 @@ func TestGetCommandDecode(t *testing.T) {
WithJSONMarshaler(encodingConfig.Marshaler)

cmd := GetDecodeCommand(clientCtx)
cmd.SetErr(ioutil.Discard)
cmd.SetOut(ioutil.Discard)
_ = testutil.ApplyMockIODiscardOutErr(cmd)

sdk.RegisterCodec(encodingConfig.Amino)

Expand Down
3 changes: 1 addition & 2 deletions x/genutil/client/cli/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ func TestMigrateGenesis(t *testing.T) {
target := "v0.36"

cmd := MigrateGenesisCmd()
cmd.SetErr(ioutil.Discard)
cmd.SetOut(ioutil.Discard)
_ = testutil.ApplyMockIODiscardOutErr(cmd)

clientCtx := client.Context{}.WithJSONMarshaler(cdc)
ctx := context.Background()
Expand Down

0 comments on commit 255ed06

Please sign in to comment.