(t *testing.T)
| 1622 | } |
| 1623 | |
| 1624 | func TestFlagCompletionInGo(t *testing.T) { |
| 1625 | rootCmd := &Command{ |
| 1626 | Use: "root", |
| 1627 | Run: emptyRun, |
| 1628 | } |
| 1629 | rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot") |
| 1630 | assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { |
| 1631 | completions := []string{} |
| 1632 | for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} { |
| 1633 | if strings.HasPrefix(comp, toComplete) { |
| 1634 | completions = append(completions, comp) |
| 1635 | } |
| 1636 | } |
| 1637 | return completions, ShellCompDirectiveDefault |
| 1638 | })) |
| 1639 | rootCmd.Flags().String("filename", "", "Enter a filename") |
| 1640 | assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { |
| 1641 | completions := []string{} |
| 1642 | for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} { |
| 1643 | if strings.HasPrefix(comp, toComplete) { |
| 1644 | completions = append(completions, comp) |
| 1645 | } |
| 1646 | } |
| 1647 | return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp |
| 1648 | })) |
| 1649 | |
| 1650 | // Test completing an empty string |
| 1651 | output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "") |
| 1652 | if err != nil { |
| 1653 | t.Errorf("Unexpected error: %v", err) |
| 1654 | } |
| 1655 | |
| 1656 | expected := strings.Join([]string{ |
| 1657 | "1", |
| 1658 | "2", |
| 1659 | "10", |
| 1660 | ":0", |
| 1661 | "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") |
| 1662 | |
| 1663 | if output != expected { |
| 1664 | t.Errorf("expected: %q, got: %q", expected, output) |
| 1665 | } |
| 1666 | |
| 1667 | // Check completing with a prefix |
| 1668 | output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "1") |
| 1669 | if err != nil { |
| 1670 | t.Errorf("Unexpected error: %v", err) |
| 1671 | } |
| 1672 | |
| 1673 | expected = strings.Join([]string{ |
| 1674 | "1", |
| 1675 | "10", |
| 1676 | ":0", |
| 1677 | "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") |
| 1678 | |
| 1679 | if output != expected { |
| 1680 | t.Errorf("expected: %q, got: %q", expected, output) |
| 1681 | } |
nothing calls this directly
no test coverage detected