arity_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "strings"
  4. "testing"
  5. "github.com/spf13/cobra"
  6. )
  7. // `info`, `enable`, `disable` and `list` take nothing. Without a declared
  8. // arity cobra applies arbitraryArgs, so a stray token yielded exit 0 and the
  9. // command looked like it had done its work — a caller could believe a
  10. // lighting change happened when the argument was silently dropped.
  11. func TestZeroArgCommandsRejectStrayTokens(t *testing.T) {
  12. cmds := map[string]*cobra.Command{
  13. "info": NewInfoCmd(),
  14. "enable": NewEnableCmd(),
  15. "disable": NewDisableCmd(),
  16. "list": NewProfileListCmd(),
  17. }
  18. for name, cmd := range cmds {
  19. t.Run(name, func(t *testing.T) {
  20. err := cmd.ValidateArgs([]string{"unexpected-arg"})
  21. if err == nil {
  22. t.Errorf("%s accepted an argument, want it rejected", name)
  23. return
  24. }
  25. if !strings.Contains(err.Error(), "unexpected-arg") {
  26. t.Errorf("%s error = %q, want it to name the offending argument", name, err)
  27. }
  28. })
  29. }
  30. }
  31. // Rejecting extras must not break the no-argument case.
  32. func TestZeroArgCommandsAcceptNoArgs(t *testing.T) {
  33. cmds := map[string]*cobra.Command{
  34. "info": NewInfoCmd(),
  35. "enable": NewEnableCmd(),
  36. "disable": NewDisableCmd(),
  37. "list": NewProfileListCmd(),
  38. }
  39. for name, cmd := range cmds {
  40. t.Run(name, func(t *testing.T) {
  41. if err := cmd.ValidateArgs(nil); err != nil {
  42. t.Errorf("%s rejected the empty argument list: %v", name, err)
  43. }
  44. })
  45. }
  46. }
  47. // Commands that do take an argument must keep accepting exactly one.
  48. func TestOneArgCommandsKeepTheirArity(t *testing.T) {
  49. cmds := map[string]*cobra.Command{
  50. "brightness": NewBrightnessCmd(),
  51. "speed": NewSpeedCmd(),
  52. "color": NewColorCmd(),
  53. }
  54. for name, cmd := range cmds {
  55. t.Run(name, func(t *testing.T) {
  56. if err := cmd.ValidateArgs([]string{"160"}); err != nil {
  57. t.Errorf("%s rejected its argument: %v", name, err)
  58. }
  59. if err := cmd.ValidateArgs([]string{"1", "2"}); err == nil {
  60. t.Errorf("%s accepted two arguments, want exactly one", name)
  61. }
  62. })
  63. }
  64. }