Skip to content

Commit e3b626c

Browse files
chore(client): use command's configured output
I have some external tests that invoke some of the SDK's cobra commands. Those tests often involve creating the command, calling cmd.SetOutput, executing the command, and then inspecting its output. This change updates the client context to prefer cmd.Output if set (which should only happen in tests), falling back to stdout otherwise; so it should not change any existing client-facing behavior, but it does otherwise make command output testable.
1 parent cd3ce0c commit e3b626c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

client/cmd.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ func GetClientQueryContext(cmd *cobra.Command) (Context, error) {
345345
// - client.Context field pre-populated & flag not set: uses pre-populated value
346346
// - client.Context field pre-populated & flag set: uses set flag value
347347
func GetClientTxContext(cmd *cobra.Command) (Context, error) {
348-
ctx := GetClientContextFromCmd(cmd)
348+
ctx := GetClientContextFromCmd(cmd).WithOutput(cmd.OutOrStdout())
349349
return readTxCommandFlags(ctx, cmd.Flags())
350350
}
351351

client/cmd_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package client_test
22

33
import (
4+
"bytes"
45
"context"
56
"fmt"
67
"testing"
@@ -137,3 +138,28 @@ func TestSetCmdClientContextHandler(t *testing.T) {
137138
})
138139
}
139140
}
141+
142+
func TestContext_usesCobraCommandOutput(t *testing.T) {
143+
var initCtx client.Context
144+
145+
cmd := &cobra.Command{
146+
PreRunE: func(cmd *cobra.Command, args []string) error {
147+
return client.SetCmdClientContextHandler(initCtx, cmd)
148+
},
149+
RunE: func(cmd *cobra.Command, _ []string) error {
150+
cctx, err := client.GetClientTxContext(cmd)
151+
if err != nil {
152+
return err
153+
}
154+
155+
return cctx.PrintString("hello")
156+
},
157+
}
158+
159+
var outBuf bytes.Buffer
160+
cmd.SetOutput(&outBuf)
161+
162+
require.NoError(t, cmd.Execute())
163+
164+
require.Equal(t, "hello", outBuf.String())
165+
}

0 commit comments

Comments
 (0)