MCPcopy
hub / github.com/spf13/cobra / TestFlagCompletionWorksRootCommandAddedAfterFlags

Function TestFlagCompletionWorksRootCommandAddedAfterFlags

completions_test.go:2044–2077  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

2042}
2043
2044func TestFlagCompletionWorksRootCommandAddedAfterFlags(t *testing.T) {
2045 rootCmd := &Command{Use: "root", Run: emptyRun}
2046 childCmd := &Command{
2047 Use: "child",
2048 Run: emptyRun,
2049 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
2050 return []string{"--validarg", "test"}, ShellCompDirectiveDefault
2051 },
2052 }
2053 childCmd.Flags().Bool("bool", false, "test bool flag")
2054 childCmd.Flags().String("string", "", "test string flag")
2055 _ = childCmd.RegisterFlagCompletionFunc("string", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
2056 return []string{"myval"}, ShellCompDirectiveDefault
2057 })
2058
2059 // Important: This is a test for https://github.com/spf13/cobra/issues/1437
2060 // Only add the subcommand after RegisterFlagCompletionFunc was called, do not change this order!
2061 rootCmd.AddCommand(childCmd)
2062
2063 // Test that flag completion works for the subcmd
2064 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child", "--string", "")
2065 if err != nil {
2066 t.Errorf("Unexpected error: %v", err)
2067 }
2068
2069 expected := strings.Join([]string{
2070 "myval",
2071 ":0",
2072 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")
2073
2074 if output != expected {
2075 t.Errorf("expected: %q, got: %q", expected, output)
2076 }
2077}
2078
2079func TestFlagCompletionForPersistentFlagsCalledFromSubCmd(t *testing.T) {
2080 rootCmd := &Command{Use: "root", Run: emptyRun}

Callers

nothing calls this directly

Calls 5

FlagsMethod · 0.95
AddCommandMethod · 0.95
executeCommandFunction · 0.85
StringMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…