definition_generate_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package main
  2. import (
  3. "encoding/json"
  4. "os"
  5. "path/filepath"
  6. "strconv"
  7. "strings"
  8. "testing"
  9. intrgb "netdome.biz/paul/qmk-rgb/internal/rgb"
  10. intvia "netdome.biz/paul/qmk-rgb/internal/via"
  11. )
  12. // generateStub is a keyboard that answers an effect range, so the generated
  13. // scaffold can be checked without hardware.
  14. type generateStub struct {
  15. tops map[intvia.Channel]int
  16. }
  17. func (g generateStub) EffectTop(ch intvia.Channel) (int, error) {
  18. return g.tops[ch], nil
  19. }
  20. func (g generateStub) GetValue(intvia.Channel, uint8) ([]byte, error) { return []byte{0}, nil }
  21. func (g generateStub) SetValue(intvia.Channel, uint8, uint8) error { return nil }
  22. func (g generateStub) SetColor(intvia.Channel, uint8, uint8) error { return nil }
  23. func (g generateStub) DetectChannels() ([]intvia.Channel, error) { return nil, nil }
  24. func (g generateStub) Close() error { return nil }
  25. // stubGenerateTarget makes the connected keyboard a fixed one. The identifiers
  26. // are a parameter because a board the binary carries a definition for is the
  27. // case `generate` has to refuse, and a stub for the wrong board would test
  28. // nothing.
  29. func stubGenerateTarget(t *testing.T, vendorID, productID uint16, channels []intvia.Channel, tops map[intvia.Channel]int) {
  30. t.Helper()
  31. original := openTarget
  32. t.Cleanup(func() { openTarget = original })
  33. openTarget = func(string) (rgbProtocol, targetDeviceData, []intvia.Channel, error) {
  34. return generateStub{tops: tops}, stubTargetData(vendorID, productID), channels, nil
  35. }
  36. }
  37. func forceGenerateRestore(t *testing.T) func() {
  38. t.Helper()
  39. original := generateForce
  40. return func() { generateForce = original }
  41. }
  42. // The whole point of the command: a generated file names no effect, so a board
  43. // with a generated definition reports the same "no names" it reported before one
  44. // existed. A scaffold that claimed names would be a guess the tool could not
  45. // read back off the keyboard.
  46. func TestGeneratedDefinitionNamesNoEffectUntilTheUserFillsItIn(t *testing.T) {
  47. dir := t.TempDir()
  48. t.Cleanup(definitionFlagRestore(t))
  49. t.Cleanup(forceDefinitionsDir(t, dir))
  50. t.Cleanup(forceGenerateRestore(t))
  51. stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
  52. cmd := NewKeyboardDefinitionsGenerateCmd()
  53. var out, errOut strings.Builder
  54. cmd.SetOut(&out)
  55. cmd.SetErr(&errOut)
  56. if err := cmd.Execute(); err != nil {
  57. t.Fatalf("definitions generate error = %v (stderr %q)", err, errOut.String())
  58. }
  59. path := onlyDefinition(t, dir)
  60. def, err := intrgb.ParseDefinition(path, []byte(mustRead(t, path)))
  61. if err != nil {
  62. t.Fatalf("ParseDefinition(%s) error = %v; the generated file has to load", path, err)
  63. }
  64. if got := len(def.Catalog.Effects(intvia.ChannelRgbMatrix)); got != 0 {
  65. t.Errorf("effects on rgb_matrix = %d, want 0 until the names are written in", got)
  66. }
  67. // The slots are still there, which is the other half: the file states which
  68. // IDs exist and leaves the naming to the user.
  69. var file struct {
  70. Menus []struct {
  71. Content []struct {
  72. Label string `json:"label"`
  73. Type string `json:"type"`
  74. Content []any `json:"content"`
  75. Options []any `json:"options"`
  76. } `json:"content"`
  77. } `json:"menus"`
  78. }
  79. if err := json.Unmarshal([]byte(mustRead(t, path)), &file); err != nil {
  80. t.Fatalf("unmarshal generated file: %v", err)
  81. }
  82. var options []any
  83. for _, menu := range file.Menus {
  84. for _, entry := range menu.Content {
  85. if entry.Type == "dropdown" {
  86. options = entry.Options
  87. }
  88. }
  89. }
  90. if len(options) != 46 {
  91. t.Fatalf("effect options = %d, want 46, one per ID from 0 to 45", len(options))
  92. }
  93. for i, option := range options {
  94. pair, ok := option.([]any)
  95. if !ok || len(pair) != 2 {
  96. t.Fatalf("option %d = %v, want a name and a number", i, option)
  97. }
  98. if name, _ := pair[0].(string); name != "" {
  99. t.Errorf("option %d is named %q, want a slot with no name", i, name)
  100. }
  101. if number, _ := pair[1].(float64); int(number) != i {
  102. t.Errorf("option %d carries ID %v, want the slot numbered %d", i, pair[1], i)
  103. }
  104. }
  105. // Every control has to be addressed by a value key the parser recognises. A
  106. // key built by trimming a suffix and appending without the underscore is
  107. // `id_qmk_rgb_matrixbrightness`, which names nothing, and nothing in the
  108. // output above would say so.
  109. wantKeys := map[string]bool{
  110. "id_qmk_rgb_matrix_brightness": false,
  111. "id_qmk_rgb_matrix_effect": false,
  112. "id_qmk_rgb_matrix_effect_speed": false,
  113. }
  114. for _, menu := range file.Menus {
  115. for _, entry := range menu.Content {
  116. key, _ := entry.Content[0].(string)
  117. if _, ok := wantKeys[key]; !ok {
  118. t.Errorf("control %q is addressed by %q, which is not a VIA value key", entry.Label, key)
  119. continue
  120. }
  121. wantKeys[key] = true
  122. }
  123. }
  124. for key, found := range wantKeys {
  125. if !found {
  126. t.Errorf("no control addresses %q", key)
  127. }
  128. }
  129. }
  130. // A definition a user has written is the one command they would have run to write
  131. // it, so it must survive a second run of the command.
  132. func TestGenerateDoesNotReplaceAStoredDefinition(t *testing.T) {
  133. dir := t.TempDir()
  134. t.Cleanup(definitionFlagRestore(t))
  135. t.Cleanup(forceDefinitionsDir(t, dir))
  136. t.Cleanup(forceGenerateRestore(t))
  137. stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
  138. written := `{"name":"Test Board","vendorId":"0x1234","productId":"0x5678","menus":[],"note":"hand written"}`
  139. if err := os.WriteFile(filepath.Join(dir, "test_board.json"), []byte(written), 0o644); err != nil {
  140. t.Fatal(err)
  141. }
  142. cmd := NewKeyboardDefinitionsGenerateCmd()
  143. var out, errOut strings.Builder
  144. cmd.SetOut(&out)
  145. cmd.SetErr(&errOut)
  146. err := cmd.Execute()
  147. if err == nil {
  148. t.Fatal("definitions generate = nil error, want a refusal to replace a stored definition")
  149. }
  150. if !strings.Contains(err.Error(), "--force") {
  151. t.Errorf("error = %q, want it to offer --force", err)
  152. }
  153. if got := mustRead(t, filepath.Join(dir, "test_board.json")); got != written {
  154. t.Errorf("stored file = %q, want it untouched (%q)", got, written)
  155. }
  156. }
  157. // The note beside the file is what carries the names, because a JSON file cannot
  158. // hold them: the tool would have to read comments and VIA's parser would reject
  159. // them. It has to say who wrote what, or a name is a guess wearing a count.
  160. func TestGeneratedNoteCarriesTheSpellingsAndWhoWroteThem(t *testing.T) {
  161. dir := t.TempDir()
  162. t.Cleanup(definitionFlagRestore(t))
  163. t.Cleanup(forceDefinitionsDir(t, dir))
  164. t.Cleanup(forceGenerateRestore(t))
  165. stubGenerateTarget(t, 0x1234, 0x5678, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
  166. cmd := NewKeyboardDefinitionsGenerateCmd()
  167. var out, errOut strings.Builder
  168. cmd.SetOut(&out)
  169. cmd.SetErr(&errOut)
  170. if err := cmd.Execute(); err != nil {
  171. t.Fatalf("definitions generate error = %v", err)
  172. }
  173. note := mustRead(t, strings.TrimSuffix(onlyDefinition(t, dir), ".json")+spottedNoteSuffix)
  174. if !strings.Contains(note, "rgb_matrix (channel 3), IDs 0 to 45") {
  175. t.Errorf("note = %q, want it to name the channel and the ID range", note)
  176. }
  177. // The measurement behind the names: a spelling, how many boards wrote it, and
  178. // which manufacturer most of them were.
  179. if !strings.Contains(note, "rainbow_moving_chevron") {
  180. t.Errorf("note = %q, want the spellings other definitions use", note)
  181. }
  182. if !strings.Contains(note, "boards:") {
  183. t.Errorf("note = %q, want a count of boards next to every name", note)
  184. }
  185. if !strings.Contains(note, "keychron") {
  186. t.Errorf("note = %q, want the manufacturer behind most of a name's spellings", note)
  187. }
  188. // Effect 23 is where the collection disagrees about what the number even is,
  189. // so the note has to show the runner-up rather than pick a winner.
  190. if !strings.Contains(note, "ID 23 ") {
  191. t.Errorf("note = %q, want a line for ID 23", note)
  192. }
  193. }
  194. func onlyDefinition(t *testing.T, dir string) string {
  195. t.Helper()
  196. matches, err := filepath.Glob(filepath.Join(dir, "*.json"))
  197. if err != nil {
  198. t.Fatal(err)
  199. }
  200. if len(matches) != 1 {
  201. t.Fatalf("definitions dir = %v, want one JSON file", matches)
  202. }
  203. return matches[0]
  204. }
  205. func mustRead(t *testing.T, path string) string {
  206. t.Helper()
  207. data, err := os.ReadFile(path)
  208. if err != nil {
  209. t.Fatal(err)
  210. }
  211. return string(data)
  212. }
  213. // A generated scaffold names no effect, so writing one for a board the binary
  214. // carries a definition for takes that board from 46 named effects to none — and
  215. // the file in the user directory is the one that is read. This is the whole
  216. // reason the built-in set is checked and not only the directory.
  217. func TestGenerateDoesNotShadowABuiltInDefinition(t *testing.T) {
  218. dir := t.TempDir()
  219. t.Cleanup(definitionFlagRestore(t))
  220. t.Cleanup(forceDefinitionsDir(t, dir))
  221. t.Cleanup(forceGenerateRestore(t))
  222. // The Impact 80, whose definition is built into the binary.
  223. stubGenerateTarget(t, 0x36B0, 0x309F, []intvia.Channel{intvia.ChannelRgbMatrix}, map[intvia.Channel]int{intvia.ChannelRgbMatrix: 45})
  224. builtIn := 0
  225. for _, def := range builtInDefinitions() {
  226. if def.Matches(0x36B0, 0x309F) {
  227. builtIn = namedEffectCount(def)
  228. }
  229. }
  230. if builtIn == 0 {
  231. t.Fatal("the binary carries no definition for 0x36B0/0x309F, so there is nothing to shadow")
  232. }
  233. cmd := NewKeyboardDefinitionsGenerateCmd()
  234. var out, errOut strings.Builder
  235. cmd.SetOut(&out)
  236. cmd.SetErr(&errOut)
  237. err := cmd.Execute()
  238. if err == nil {
  239. t.Fatal("definitions generate = nil error, want a refusal to shadow a built-in definition")
  240. }
  241. if !strings.Contains(err.Error(), "carries a definition") {
  242. t.Errorf("error = %q, want it to say the definition is one the binary carries", err)
  243. }
  244. if !strings.Contains(err.Error(), strconv.Itoa(builtIn)) {
  245. t.Errorf("error = %q, want it to name how many effects would be lost (%d)", err, builtIn)
  246. }
  247. if entries, _ := filepath.Glob(filepath.Join(dir, "*.json")); len(entries) != 0 {
  248. t.Errorf("definitions dir = %v, want nothing written", entries)
  249. }
  250. }