|
| 1 | +package root |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/cli/cli/pkg/iostreams" |
| 8 | + "github.com/google/shlex" |
| 9 | + "github.com/spf13/cobra" |
| 10 | +) |
| 11 | + |
| 12 | +func TestNewCmdCompletion(t *testing.T) { |
| 13 | + tests := []struct { |
| 14 | + name string |
| 15 | + args string |
| 16 | + wantOut string |
| 17 | + wantErr string |
| 18 | + }{ |
| 19 | + { |
| 20 | + name: "no arguments", |
| 21 | + args: "completion", |
| 22 | + wantOut: "complete -o default -F __start_gh gh", |
| 23 | + }, |
| 24 | + { |
| 25 | + name: "zsh completion", |
| 26 | + args: "completion -s zsh", |
| 27 | + wantOut: "#compdef _gh gh", |
| 28 | + }, |
| 29 | + { |
| 30 | + name: "fish completion", |
| 31 | + args: "completion -s fish", |
| 32 | + wantOut: "complete -c gh ", |
| 33 | + }, |
| 34 | + { |
| 35 | + name: "PowerShell completion", |
| 36 | + args: "completion -s powershell", |
| 37 | + wantOut: "Register-ArgumentCompleter", |
| 38 | + }, |
| 39 | + { |
| 40 | + name: "unsupported shell", |
| 41 | + args: "completion -s csh", |
| 42 | + wantErr: "unsupported shell type \"csh\"", |
| 43 | + }, |
| 44 | + } |
| 45 | + for _, tt := range tests { |
| 46 | + t.Run(tt.name, func(t *testing.T) { |
| 47 | + io, _, stdout, stderr := iostreams.Test() |
| 48 | + completeCmd := NewCmdCompletion(io) |
| 49 | + rootCmd := &cobra.Command{Use: "gh"} |
| 50 | + rootCmd.AddCommand(completeCmd) |
| 51 | + |
| 52 | + argv, err := shlex.Split(tt.args) |
| 53 | + if err != nil { |
| 54 | + t.Fatalf("argument splitting error: %v", err) |
| 55 | + } |
| 56 | + rootCmd.SetArgs(argv) |
| 57 | + rootCmd.SetOut(stdout) |
| 58 | + rootCmd.SetErr(stderr) |
| 59 | + |
| 60 | + _, err = rootCmd.ExecuteC() |
| 61 | + if tt.wantErr != "" { |
| 62 | + if err == nil || err.Error() != tt.wantErr { |
| 63 | + t.Fatalf("expected error %q, got %q", tt.wantErr, err) |
| 64 | + } |
| 65 | + return |
| 66 | + } |
| 67 | + if err != nil { |
| 68 | + t.Fatalf("error executing command: %v", err) |
| 69 | + } |
| 70 | + |
| 71 | + if !strings.Contains(stdout.String(), tt.wantOut) { |
| 72 | + t.Errorf("completion output did not match:\n%s", stdout.String()) |
| 73 | + } |
| 74 | + if len(stderr.String()) > 0 { |
| 75 | + t.Errorf("expected nothing on stderr, got %q", stderr.String()) |
| 76 | + } |
| 77 | + }) |
| 78 | + } |
| 79 | +} |
0 commit comments