From ad6db7f8f6e485f55b1561df9276fa4d8e278bde Mon Sep 17 00:00:00 2001 From: Brian Pursley Date: Mon, 14 Nov 2022 21:46:57 -0500 Subject: [PATCH] Create unit test illustrating unknown flag bug (#1854) Created a unit test that tests the unknown flag error message when the unknown flag is located in different arg positions. --- command_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/command_test.go b/command_test.go index 3fd36c7..1801132 100644 --- a/command_test.go +++ b/command_test.go @@ -2692,3 +2692,46 @@ func TestFind(t *testing.T) { }) } } + +func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) { + testCases := [][]string{ + //{"--unknown", "--namespace", "foo", "child", "--bar"}, // FIXME: This test case fails, returning the error `unknown command "foo" for "root"` instead of the expected error `unknown flag: --unknown` + {"--namespace", "foo", "--unknown", "child", "--bar"}, + {"--namespace", "foo", "child", "--unknown", "--bar"}, + {"--namespace", "foo", "child", "--bar", "--unknown"}, + + {"--unknown", "--namespace=foo", "child", "--bar"}, + {"--namespace=foo", "--unknown", "child", "--bar"}, + {"--namespace=foo", "child", "--unknown", "--bar"}, + {"--namespace=foo", "child", "--bar", "--unknown"}, + + {"--unknown", "--namespace=foo", "child", "--bar=true"}, + {"--namespace=foo", "--unknown", "child", "--bar=true"}, + {"--namespace=foo", "child", "--unknown", "--bar=true"}, + {"--namespace=foo", "child", "--bar=true", "--unknown"}, + } + + root := &Command{ + Use: "root", + Run: emptyRun, + } + root.PersistentFlags().String("namespace", "", "a string flag") + + c := &Command{ + Use: "child", + Run: emptyRun, + } + c.Flags().Bool("bar", false, "a boolean flag") + + root.AddCommand(c) + + for _, tc := range testCases { + t.Run(strings.Join(tc, " "), func(t *testing.T) { + output, err := executeCommand(root, tc...) + if err == nil { + t.Error("expected unknown flag error") + } + checkStringContains(t, output, "unknown flag: --unknown") + }) + } +}