completion_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package main
  2. import (
  3. "errors"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "testing"
  8. "github.com/spf13/cobra"
  9. intdevice "netdome.biz/paul/qmk-rgb/internal/device"
  10. )
  11. // The tool knows what a zone may be, but the shell only offers what the binary
  12. // tells it about. The zone is a positional argument, so the completion hangs off
  13. // the command rather than off a flag, and a board's own channel names come from
  14. // a definition file the tool reads.
  15. func TestZoneCompletionOffersSubsystemsAndTheBoardsOwnNames(t *testing.T) {
  16. dir := t.TempDir()
  17. writeDefinition(t, dir, "impact80.json", `{
  18. "name": "Impact 80", "vendorId": "0x36B0", "productId": "0x309F",
  19. "menus": [{"label":"Lighting","content":[
  20. {"label":"logo","content":[{"label":"Effect","type":"dropdown",
  21. "content":["id_qmk_rgblight_effect",2,2],"options":["none"]}]},
  22. {"label":"Backlight","content":[{"label":"Effect","type":"dropdown",
  23. "content":["id_qmk_rgb_matrix_effect",3,2],"options":["none"]}]}]}]}`)
  24. t.Cleanup(forceDefinitionsDir(t, dir))
  25. got, directive := completeZoneNames(nil, nil, "")
  26. if directive != cobra.ShellCompDirectiveNoFileComp {
  27. t.Errorf("directive = %v, want NoFileComp so the shell does not fall back to paths", directive)
  28. }
  29. for _, want := range []string{"backlight", "rgblight", "rgb_matrix", "audio", "led_matrix", "logo", "Backlight"} {
  30. if !contains(got, want) {
  31. t.Errorf("completeZoneNames() = %v, want it to offer %q", got, want)
  32. }
  33. }
  34. // Nothing is offered twice: Backlight is both a label and close to
  35. // backlight, and a list with repeats reads as a bug.
  36. if len(got) != countDistinct(got) {
  37. t.Errorf("completeZoneNames() = %v, want no duplicates", got)
  38. }
  39. }
  40. // The shell is completing as the user types, so a prefix has to narrow the list.
  41. func TestZoneCompletionNarrowsToThePrefix(t *testing.T) {
  42. t.Cleanup(forceDefinitionsDir(t, t.TempDir()))
  43. got, directive := completeZoneNames(nil, nil, "rgb")
  44. if directive != cobra.ShellCompDirectiveNoFileComp {
  45. t.Errorf("directive = %v, want NoFileComp so the shell does not fall back to paths", directive)
  46. }
  47. for _, g := range got {
  48. if !strings.HasPrefix(g, "rgb") {
  49. t.Errorf("completeZoneNames(%q) = %v, want only names with that prefix", "rgb", got)
  50. }
  51. }
  52. if !contains(got, "rgb_matrix") {
  53. t.Errorf("completeZoneNames(\"rgb\") = %v, want rgb_matrix", got)
  54. }
  55. }
  56. // `all` is a zone name like any other, and the shell has to offer it: it is the
  57. // one spelling that reaches every channel, and a user who cannot see it will not
  58. // reach every channel.
  59. func TestZoneCompletionOffersAll(t *testing.T) {
  60. t.Cleanup(forceDefinitionsDir(t, t.TempDir()))
  61. got, _ := completeZoneNames(nil, nil, "")
  62. if !contains(got, "all") {
  63. t.Errorf("completeZoneNames() = %v, want it to offer \"all\"", got)
  64. }
  65. }
  66. // A board's own names come from a definition file, and the one built into the
  67. // binary counts as much as one in the data directory. `go install` creates no
  68. // data directory, so a shell that only read that one would offer a board nothing
  69. // but the subsystem names — and the subsystem names a board renamed are not the
  70. // names it answers to.
  71. func TestZoneCompletionOffersTheBuiltInDefinitionsToo(t *testing.T) {
  72. t.Cleanup(forceDefinitionsDir(t, t.TempDir()))
  73. got, _ := completeZoneNames(nil, nil, "")
  74. // The Impact 80's file is the one that ships, and it names three channels.
  75. for _, want := range []string{"logo", "Backlight", "side"} {
  76. if !contains(got, want) {
  77. t.Errorf("completeZoneNames() = %v, want the built-in definition's name %q", got, want)
  78. }
  79. }
  80. }
  81. // The zone is a positional argument now, so the completion hangs off the command
  82. // rather than off a flag, and it stops after the first argument rather than
  83. // offering a channel where a value belongs.
  84. func TestZoneCompletionIsOnTheCommandNotTheFlag(t *testing.T) {
  85. lighting := map[string]*cobra.Command{
  86. "effect": NewEffectCmd(),
  87. "brightness": NewBrightnessCmd(),
  88. "speed": NewSpeedCmd(),
  89. "color": NewColorCmd(),
  90. "enable": NewEnableCmd(),
  91. "disable": NewDisableCmd(),
  92. "info": NewInfoCmd(),
  93. }
  94. for name, cmd := range lighting {
  95. t.Run(name, func(t *testing.T) {
  96. if cmd.ValidArgsFunction == nil {
  97. t.Fatalf("%s has no ValidArgsFunction, want the shell offered the zone names", name)
  98. }
  99. got, _ := cmd.ValidArgsFunction(cmd, nil, "")
  100. if !contains(got, "all") {
  101. t.Errorf("%s completion = %v, want it to offer the zones", name, got)
  102. }
  103. // After the zone, the next argument is a value or a name the tool
  104. // cannot know without opening the keyboard.
  105. after, directive := cmd.ValidArgsFunction(cmd, []string{"logo"}, "")
  106. if len(after) != 0 {
  107. t.Errorf("%s completion after a zone = %v, want nothing", name, after)
  108. }
  109. if directive != cobra.ShellCompDirectiveNoFileComp {
  110. t.Errorf("%s directive = %v, want NoFileComp", name, directive)
  111. }
  112. })
  113. }
  114. }
  115. // `load` takes a profile name first and a zone second, in that order, so the two
  116. // completions cannot be swapped without offering something that does not exist.
  117. func TestLoadCompletionIsAProfileThenAZone(t *testing.T) {
  118. t.Cleanup(forceDefinitionsDir(t, t.TempDir()))
  119. cmd := NewProfileLoadCmd()
  120. first, _ := cmd.ValidArgsFunction(cmd, nil, "")
  121. if !contains(first, "lava") {
  122. t.Errorf("load completion = %v, want the profile names", first)
  123. }
  124. second, _ := cmd.ValidArgsFunction(cmd, []string{"lava"}, "")
  125. if contains(second, "lava") {
  126. t.Errorf("load completion after a name = %v, want zones, not more profiles", second)
  127. }
  128. if !contains(second, "all") {
  129. t.Errorf("load completion after a name = %v, want the zone names", second)
  130. }
  131. }
  132. // A command that cannot address a channel offers no zone, so the shell does not
  133. // suggest one where there is none to use. `delete` completes a profile name, so
  134. // what matters is that the candidates are the names, not the channels.
  135. func TestCommandsWithoutAChannelOfferNoZone(t *testing.T) {
  136. for name, cmd := range map[string]*cobra.Command{
  137. "list": NewProfileListCmd(),
  138. "save": NewProfileSaveCmd(),
  139. } {
  140. t.Run(name, func(t *testing.T) {
  141. if cmd.ValidArgsFunction != nil {
  142. t.Errorf("%s offers completion, want only the commands that name a channel to", name)
  143. }
  144. })
  145. }
  146. profiles, _ := NewProfileDeleteCmd().ValidArgsFunction(nil, nil, "")
  147. for _, candidate := range profiles {
  148. if candidate == "all" || candidate == "rgb_matrix" {
  149. t.Errorf("delete completion = %v, want profile names, not channels", profiles)
  150. }
  151. }
  152. }
  153. // A definition that is not there must not break completion: a shell prints the
  154. // error text, which is worse than offering nothing.
  155. func TestZoneCompletionSurvivesAMissingDataDirectory(t *testing.T) {
  156. t.Cleanup(forceDefinitionsDir(t, filepath.Join(t.TempDir(), "absent")))
  157. got, directive := completeZoneNames(nil, nil, "")
  158. if directive != cobra.ShellCompDirectiveNoFileComp {
  159. t.Errorf("directive = %v, want NoFileComp so the shell does not fall back to paths", directive)
  160. }
  161. if !contains(got, "rgb_matrix") {
  162. t.Errorf("completeZoneNames() = %v, want the QMK subsystem names at least", got)
  163. }
  164. }
  165. // --device takes the numbers keyboard info prints, which come from enumeration
  166. // alone and need no open keyboard.
  167. func TestDeviceCompletionOffersTheConnectedKeyboards(t *testing.T) {
  168. original := discoverAll
  169. discoverAll = func() ([]intdevice.Device, error) {
  170. return []intdevice.Device{{Index: 1}, {Index: 2}}, nil
  171. }
  172. t.Cleanup(func() { discoverAll = original })
  173. got, directive := completeDeviceNumbers(nil, nil, "")
  174. if directive != cobra.ShellCompDirectiveNoFileComp {
  175. t.Errorf("directive = %v, want NoFileComp so the shell does not fall back to paths", directive)
  176. }
  177. if len(got) != 2 || got[0] != "1" || got[1] != "2" {
  178. t.Errorf("completeDeviceNumbers() = %v, want [1 2]", got)
  179. }
  180. }
  181. func TestDeviceCompletionSurvivesADiscoveryFailure(t *testing.T) {
  182. original := discoverAll
  183. discoverAll = func() ([]intdevice.Device, error) { return nil, errors.New("no keyboard") }
  184. t.Cleanup(func() { discoverAll = original })
  185. got, directive := completeDeviceNumbers(nil, nil, "")
  186. if directive != cobra.ShellCompDirectiveNoFileComp {
  187. t.Errorf("directive = %v, want NoFileComp so the shell does not fall back to paths", directive)
  188. }
  189. if len(got) != 0 {
  190. t.Errorf("completeDeviceNumbers() = %v, want nothing when discovery fails", got)
  191. }
  192. }
  193. // load, save and delete take a profile name, and the names in profiles/ are
  194. // readable without a keyboard — which is the point, because the shell is asking
  195. // while nothing is plugged in.
  196. func TestProfileNameCompletionOffersTheFilesInTheDirectory(t *testing.T) {
  197. dir := t.TempDir()
  198. original := profilesDirOverride
  199. profilesDirOverride = dir
  200. t.Cleanup(func() { profilesDirOverride = original })
  201. for _, name := range []string{"paul.json", "default.json", "notes.txt"} {
  202. if err := os.WriteFile(filepath.Join(dir, name), []byte("{}"), 0o600); err != nil {
  203. t.Fatal(err)
  204. }
  205. }
  206. for _, cmd := range []*cobra.Command{NewProfileLoadCmd(), NewProfileDeleteCmd()} {
  207. got, _ := completeProfileNames(cmd, nil, "")
  208. if len(got) != 2 || got[0] != "default" || got[1] != "paul" {
  209. t.Errorf("completeProfileNames() = %v, want [default paul]", got)
  210. }
  211. }
  212. }
  213. func TestProfileNameCompletionSurvivesAMissingDirectory(t *testing.T) {
  214. original := profilesDirOverride
  215. profilesDirOverride = filepath.Join(t.TempDir(), "absent")
  216. t.Cleanup(func() { profilesDirOverride = original })
  217. got, directive := completeProfileNames(nil, nil, "")
  218. if directive != cobra.ShellCompDirectiveNoFileComp {
  219. t.Errorf("directive = %v, want NoFileComp so the shell does not fall back to paths", directive)
  220. }
  221. if len(got) != 0 {
  222. t.Errorf("completeProfileNames() = %v, want nothing", got)
  223. }
  224. }
  225. func contains(list []string, want string) bool {
  226. for _, s := range list {
  227. if s == want {
  228. return true
  229. }
  230. }
  231. return false
  232. }
  233. func countDistinct(list []string) int {
  234. seen := make(map[string]bool, len(list))
  235. for _, s := range list {
  236. seen[s] = true
  237. }
  238. return len(seen)
  239. }