From ed4583eb5930ed9234835c7b00a11eee99ee3f0c Mon Sep 17 00:00:00 2001 From: 5ouma <101255979+5ouma@users.noreply.github.com> Date: Fri, 8 Sep 2023 12:10:16 +0900 Subject: [PATCH] [update] More tests that were requested Root error prefix called from subcommand, and different error prefixes in root and subcommand. https://github.com/spf13/cobra/pull/2023#discussion_r1319266611 --- command_test.go | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/command_test.go b/command_test.go index d234b3558..4afb7f7b8 100644 --- a/command_test.go +++ b/command_test.go @@ -1099,16 +1099,37 @@ func TestShorthandVersionTemplate(t *testing.T) { checkStringContains(t, output, "customized version: 1.0.0") } -func TestErrPrefix(t *testing.T) { - rootCmd := &Command{Use: "root", SilenceUsage: true, Run: emptyRun} - rootCmd.SetErrPrefix("customized error prefix:") +func TestRootErrPrefixExecutedOnSubcommand(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + rootCmd.SetErrPrefix("root error prefix:") + rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun}) - output, err := executeCommand(rootCmd, "--unknown", "flag") + output, err := executeCommand(rootCmd, "sub", "--unknown-flag") if err == nil { t.Errorf("Expected error") } - checkStringContains(t, output, "customized error prefix: unknown flag: --unknown") + checkStringContains(t, output, "root error prefix: unknown flag: --unknown-flag") +} + +func TestRootAndSubErrPrefix(t *testing.T) { + rootCmd := &Command{Use: "root", Run: emptyRun} + subCmd := &Command{Use: "sub", Run: emptyRun} + rootCmd.AddCommand(subCmd) + rootCmd.SetErrPrefix("root error prefix:") + subCmd.SetErrPrefix("sub error prefix:") + + if output, err := executeCommand(rootCmd, "--unknown-root-flag"); err == nil { + t.Errorf("Expected error") + } else { + checkStringContains(t, output, "root error prefix: unknown flag: --unknown-root-flag") + } + + if output, err := executeCommand(rootCmd, "sub", "--unknown-sub-flag"); err == nil { + t.Errorf("Expected error") + } else { + checkStringContains(t, output, "sub error prefix: unknown flag: --unknown-sub-flag") + } } func TestVersionFlagExecutedOnSubcommand(t *testing.T) {