From 1c949f772f4e1ba22501475e8a137bd50eeeec6d Mon Sep 17 00:00:00 2001 From: Mark Rushakoff Date: Tue, 22 Oct 2024 19:08:45 -0400 Subject: [PATCH] chore(client): use command's configured output (#22334) --- client/cmd.go | 2 +- client/cmd_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/client/cmd.go b/client/cmd.go index 7ea1f49e0942..29a0352f7dbc 100644 --- a/client/cmd.go +++ b/client/cmd.go @@ -345,7 +345,7 @@ func GetClientQueryContext(cmd *cobra.Command) (Context, error) { // - client.Context field pre-populated & flag not set: uses pre-populated value // - client.Context field pre-populated & flag set: uses set flag value func GetClientTxContext(cmd *cobra.Command) (Context, error) { - ctx := GetClientContextFromCmd(cmd) + ctx := GetClientContextFromCmd(cmd).WithOutput(cmd.OutOrStdout()) return readTxCommandFlags(ctx, cmd.Flags()) } diff --git a/client/cmd_test.go b/client/cmd_test.go index 31c7bf390b01..ae57b2f4bac6 100644 --- a/client/cmd_test.go +++ b/client/cmd_test.go @@ -1,6 +1,7 @@ package client_test import ( + "bytes" "context" "fmt" "testing" @@ -137,3 +138,28 @@ func TestSetCmdClientContextHandler(t *testing.T) { }) } } + +func TestContext_usesCobraCommandOutput(t *testing.T) { + var initCtx client.Context + + cmd := &cobra.Command{ + PreRunE: func(cmd *cobra.Command, args []string) error { + return client.SetCmdClientContextHandler(initCtx, cmd) + }, + RunE: func(cmd *cobra.Command, _ []string) error { + cctx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + return cctx.PrintString("hello") + }, + } + + var outBuf bytes.Buffer + cmd.SetOutput(&outBuf) + + require.NoError(t, cmd.Execute()) + + require.Equal(t, "hello", outBuf.String()) +}