| 1 | package cli_test |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "os" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/tomwright/dasel/v3/internal/cli" |
| 10 | ) |
| 11 | |
| 12 | func runDaselCmd(args []string) (string, string, error) { |
| 13 | stdOut := bytes.NewBuffer(nil) |
| 14 | stdErr := bytes.NewBuffer(nil) |
| 15 | stdIn := bytes.NewReader(nil) |
| 16 | |
| 17 | originalArgs := os.Args |
| 18 | defer func() { |
| 19 | os.Args = originalArgs |
| 20 | }() |
| 21 | |
| 22 | os.Args = append([]string{"dasel"}, args...) |
| 23 | _, err := cli.Run(stdIn, stdOut, stdErr) |
| 24 | return stdOut.String(), stdErr.String(), err |
| 25 | } |
| 26 | |
| 27 | func TestCompletion(t *testing.T) { |
| 28 | tests := []struct { |
| 29 | shell string |
| 30 | markers []string |
| 31 | }{ |
| 32 | { |
| 33 | shell: "bash", |
| 34 | markers: []string{ |
| 35 | "_dasel()", |
| 36 | "complete -F _dasel dasel", |
| 37 | "COMPREPLY", |
| 38 | "compgen", |
| 39 | }, |
| 40 | }, |
| 41 | { |
| 42 | shell: "zsh", |
| 43 | markers: []string{ |
| 44 | "#compdef dasel", |
| 45 | "_dasel()", |
| 46 | "_arguments", |
| 47 | "_describe", |
| 48 | }, |
| 49 | }, |
| 50 | { |
| 51 | shell: "fish", |
| 52 | markers: []string{ |
| 53 | "complete -c dasel", |
| 54 | "__fish_use_subcommand", |
| 55 | "__fish_seen_subcommand_from", |
| 56 | }, |
| 57 | }, |
| 58 | { |
| 59 | shell: "powershell", |
| 60 | markers: []string{ |
| 61 | "Register-ArgumentCompleter", |
| 62 | "-CommandName dasel", |
| 63 | "CompletionResult", |
| 64 | }, |
| 65 | }, |
| 66 | } |
| 67 | |
| 68 | subcommands := []string{"query", "version", "completion", "man"} |
| 69 | // Fish uses -l flag_name format, others use --flag_name |
| 70 | flags := []string{"in", "out", "compact"} |
| 71 | |
| 72 | for _, tt := range tests { |
| 73 | t.Run(tt.shell, func(t *testing.T) { |
| 74 | stdout, _, err := runDaselCmd([]string{"completion", tt.shell}) |
| 75 | if err != nil { |
| 76 | t.Fatalf("unexpected error: %v", err) |
| 77 | } |
| 78 | if stdout == "" { |
| 79 | t.Fatal("expected non-empty output") |
| 80 | } |
| 81 | if !strings.Contains(stdout, "dasel") { |
| 82 | t.Error("expected output to contain 'dasel'") |
| 83 | } |
| 84 | for _, marker := range tt.markers { |
| 85 | if !strings.Contains(stdout, marker) { |
| 86 | t.Errorf("expected output to contain %q", marker) |
| 87 | } |
| 88 | } |
| 89 | for _, sub := range subcommands { |
| 90 | if !strings.Contains(stdout, sub) { |
| 91 | t.Errorf("expected output to contain subcommand %q", sub) |
| 92 | } |
| 93 | } |
| 94 | for _, flag := range flags { |
| 95 | if !strings.Contains(stdout, flag) { |
| 96 | t.Errorf("expected output to contain flag %q", flag) |
| 97 | } |
| 98 | } |
| 99 | }) |
| 100 | } |
| 101 | } |