(t *testing.T)
| 2785 | } |
| 2786 | |
| 2787 | func TestCompleteWithDisableFlagParsing(t *testing.T) { |
| 2788 | |
| 2789 | flagValidArgs := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { |
| 2790 | return []string{"--flag", "-f"}, ShellCompDirectiveNoFileComp |
| 2791 | } |
| 2792 | |
| 2793 | rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun} |
| 2794 | childCmd := &Command{ |
| 2795 | Use: "child", |
| 2796 | Run: emptyRun, |
| 2797 | DisableFlagParsing: true, |
| 2798 | ValidArgsFunction: flagValidArgs, |
| 2799 | } |
| 2800 | rootCmd.AddCommand(childCmd) |
| 2801 | |
| 2802 | rootCmd.PersistentFlags().StringP("persistent", "p", "", "persistent flag") |
| 2803 | childCmd.Flags().StringP("nonPersistent", "n", "", "non-persistent flag") |
| 2804 | |
| 2805 | // Test that when DisableFlagParsing==true, ValidArgsFunction is called to complete flag names, |
| 2806 | // after Cobra tried to complete the flags it knows about. |
| 2807 | childCmd.DisableFlagParsing = true |
| 2808 | output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "-") |
| 2809 | if err != nil { |
| 2810 | t.Errorf("Unexpected error: %v", err) |
| 2811 | } |
| 2812 | |
| 2813 | expected := strings.Join([]string{ |
| 2814 | "--persistent", |
| 2815 | "-p", |
| 2816 | "--nonPersistent", |
| 2817 | "-n", |
| 2818 | "--flag", |
| 2819 | "-f", |
| 2820 | ":4", |
| 2821 | "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") |
| 2822 | |
| 2823 | if output != expected { |
| 2824 | t.Errorf("expected: %q, got: %q", expected, output) |
| 2825 | } |
| 2826 | |
| 2827 | // Test that when DisableFlagParsing==false, Cobra completes the flags itself and ValidArgsFunction is not called |
| 2828 | childCmd.DisableFlagParsing = false |
| 2829 | output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "-") |
| 2830 | if err != nil { |
| 2831 | t.Errorf("Unexpected error: %v", err) |
| 2832 | } |
| 2833 | |
| 2834 | // Cobra was not told of any flags, so it returns nothing |
| 2835 | expected = strings.Join([]string{ |
| 2836 | "--persistent", |
| 2837 | "-p", |
| 2838 | "--help", |
| 2839 | "-h", |
| 2840 | "--nonPersistent", |
| 2841 | "-n", |
| 2842 | ":4", |
| 2843 | "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") |
| 2844 |
nothing calls this directly
no test coverage detected