Skip to content

Commit d5e030c

Browse files
committed
fix: reject unsupported net-info output formats
Signed-off-by: haoshengzhen <haoshengzhen@outlook.com>
1 parent ec9f9bf commit d5e030c

2 files changed

Lines changed: 40 additions & 5 deletions

File tree

pkg/cmd/p2p.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,16 @@ var NetInfoCmd = &cobra.Command{
4040
return fmt.Errorf("RPC address not found in node configuration")
4141
}
4242

43+
outputFormat, err := cmd.Flags().GetString(flagOutput)
44+
if err != nil {
45+
return err
46+
}
47+
switch outputFormat {
48+
case "text", "json":
49+
default:
50+
return fmt.Errorf("unsupported output format %q (supported: text, json)", outputFormat)
51+
}
52+
4353
// Create HTTP client
4454
httpClient := http.Client{
4555
Transport: http.DefaultTransport,
@@ -75,11 +85,6 @@ var NetInfoCmd = &cobra.Command{
7585
return fmt.Errorf("GetPeerInfo RPC: %w", err)
7686
}
7787

78-
outputFormat, err := cmd.Flags().GetString(flagOutput)
79-
if err != nil {
80-
return err
81-
}
82-
8388
if outputFormat == "json" {
8489
return formatJson(cmd.OutOrStdout(), netInfo, peerResp)
8590
}

pkg/cmd/p2p_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,3 +199,33 @@ func TestNetInfoCmd_NoPeers(t *testing.T) {
199199

200200
mockP2P.AssertExpectations(t)
201201
}
202+
203+
func TestNetInfoCmd_InvalidOutputFormat(t *testing.T) {
204+
require := require.New(t)
205+
206+
tempDir, err := os.MkdirTemp("", "evolve-test-home-invalid-output-*")
207+
require.NoError(err)
208+
defer os.RemoveAll(tempDir)
209+
210+
rpcAddr := "127.0.0.1:1"
211+
v := viper.New()
212+
v.Set(config.FlagRPCAddress, rpcAddr)
213+
v.Set(config.FlagRootDir, tempDir)
214+
215+
rootCmd := &cobra.Command{Use: "root"}
216+
rootCmd.PersistentFlags().String(config.FlagRootDir, tempDir, "Root directory for config and data")
217+
rootCmd.PersistentFlags().String(config.FlagRPCAddress, rpcAddr, "RPC listen address")
218+
219+
err = v.BindPFlag(config.FlagRootDir, rootCmd.PersistentFlags().Lookup(config.FlagRootDir))
220+
require.NoError(err)
221+
err = v.BindPFlag(config.FlagRPCAddress, rootCmd.PersistentFlags().Lookup(config.FlagRPCAddress))
222+
require.NoError(err)
223+
224+
NetInfoCmd.SetContext(context.WithValue(context.Background(), viperKey, v))
225+
rootCmd.AddCommand(NetInfoCmd)
226+
227+
output, err := executeCommandC(rootCmd, "net-info", "--evnode.rpc.address="+rpcAddr, "--output", "yaml")
228+
229+
require.Error(err, "Command should reject unsupported output format: %s", output)
230+
require.Contains(err.Error(), `unsupported output format "yaml"`)
231+
}

0 commit comments

Comments
 (0)