arity_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. "mode": NewModeCmd(),
  54. }
  55. for name, cmd := range cmds {
  56. t.Run(name, func(t *testing.T) {
  57. if err := cmd.ValidateArgs([]string{"160"}); err != nil {
  58. t.Errorf("%s rejected its argument: %v", name, err)
  59. }
  60. if err := cmd.ValidateArgs([]string{"1", "2"}); err == nil {
  61. t.Errorf("%s accepted two arguments, want exactly one", name)
  62. }
  63. })
  64. }
  65. }