zsh_completions_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package cobra
  2. import (
  3. "bytes"
  4. "strings"
  5. "testing"
  6. )
  7. func TestZshCompletion(t *testing.T) {
  8. tcs := []struct {
  9. name string
  10. root *Command
  11. expectedExpressions []string
  12. }{
  13. {
  14. name: "trivial",
  15. root: &Command{Use: "trivialapp"},
  16. expectedExpressions: []string{"#compdef trivial"},
  17. },
  18. {
  19. name: "linear",
  20. root: func() *Command {
  21. r := &Command{Use: "linear"}
  22. sub1 := &Command{Use: "sub1"}
  23. r.AddCommand(sub1)
  24. sub2 := &Command{Use: "sub2"}
  25. sub1.AddCommand(sub2)
  26. sub3 := &Command{Use: "sub3"}
  27. sub2.AddCommand(sub3)
  28. return r
  29. }(),
  30. expectedExpressions: []string{"sub1", "sub2", "sub3"},
  31. },
  32. {
  33. name: "flat",
  34. root: func() *Command {
  35. r := &Command{Use: "flat"}
  36. r.AddCommand(&Command{Use: "c1"})
  37. r.AddCommand(&Command{Use: "c2"})
  38. return r
  39. }(),
  40. expectedExpressions: []string{"(c1 c2)"},
  41. },
  42. {
  43. name: "tree",
  44. root: func() *Command {
  45. r := &Command{Use: "tree"}
  46. sub1 := &Command{Use: "sub1"}
  47. r.AddCommand(sub1)
  48. sub11 := &Command{Use: "sub11"}
  49. sub12 := &Command{Use: "sub12"}
  50. sub1.AddCommand(sub11)
  51. sub1.AddCommand(sub12)
  52. sub2 := &Command{Use: "sub2"}
  53. r.AddCommand(sub2)
  54. sub21 := &Command{Use: "sub21"}
  55. sub22 := &Command{Use: "sub22"}
  56. sub2.AddCommand(sub21)
  57. sub2.AddCommand(sub22)
  58. return r
  59. }(),
  60. expectedExpressions: []string{"(sub11 sub12)", "(sub21 sub22)"},
  61. },
  62. }
  63. for _, tc := range tcs {
  64. t.Run(tc.name, func(t *testing.T) {
  65. buf := new(bytes.Buffer)
  66. tc.root.GenZshCompletion(buf)
  67. output := buf.String()
  68. for _, expectedExpression := range tc.expectedExpressions {
  69. if !strings.Contains(output, expectedExpression) {
  70. t.Errorf("Expected completion to contain %q somewhere; got %q", expectedExpression, output)
  71. }
  72. }
  73. })
  74. }
  75. }