definition_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "testing"
  10. intdevice "netdome.biz/paul/qmk-rgb/internal/device"
  11. )
  12. func TestFetchDefinitionStoresTheFileForTheBoard(t *testing.T) {
  13. dir := t.TempDir()
  14. t.Cleanup(definitionFlagRestore(t))
  15. t.Cleanup(forceDefinitionsDir(t, dir))
  16. stubPrepareTarget(t, 0x1234, 0x5678)
  17. served := `{"name":"Test Board","vendorProductId":305419896,"menus":[]}`
  18. var requested []string
  19. stubHTTPGet(t, func(url string) ([]byte, int, error) {
  20. requested = append(requested, url)
  21. if strings.Contains(url, "/v3/") {
  22. return []byte(served), http.StatusOK, nil
  23. }
  24. return nil, http.StatusNotFound, errors.New("404")
  25. })
  26. cmd := NewDefinitionCmd()
  27. var out, errOut strings.Builder
  28. cmd.SetOut(&out)
  29. cmd.SetErr(&errOut)
  30. cmd.SetArgs([]string{"fetch"})
  31. if err := cmd.Execute(); err != nil {
  32. t.Fatalf("definition fetch error = %v (stderr %q)", err, errOut.String())
  33. }
  34. if len(requested) != 1 || !strings.Contains(requested[0], "/v3/305419896.json") {
  35. t.Errorf("requested = %v, want one v3 URL for vendorProductId 305419896", requested)
  36. }
  37. if !strings.Contains(out.String(), "Test Board") {
  38. t.Errorf("stdout = %q, want the board name", out.String())
  39. }
  40. entries, err := os.ReadDir(dir)
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. if len(entries) != 1 || !strings.HasSuffix(entries[0].Name(), ".json") {
  45. t.Fatalf("definitions dir = %v, want one JSON file", entries)
  46. }
  47. }
  48. // An unknown board is answered with a web page and a success status, so the
  49. // fetch must not store it and must say what happened instead.
  50. func TestFetchDefinitionRejectsAPageThatIsNotADefinition(t *testing.T) {
  51. dir := t.TempDir()
  52. t.Cleanup(definitionFlagRestore(t))
  53. t.Cleanup(forceDefinitionsDir(t, dir))
  54. stubPrepareTarget(t, 0x1234, 0x5678)
  55. stubHTTPGet(t, func(string) ([]byte, int, error) {
  56. return []byte("<!doctype html><html><head><title>VIA</title></head></html>"), http.StatusOK, nil
  57. })
  58. cmd := NewDefinitionCmd()
  59. var out, errOut strings.Builder
  60. cmd.SetOut(&out)
  61. cmd.SetErr(&errOut)
  62. cmd.SetArgs([]string{"fetch"})
  63. err := cmd.Execute()
  64. if err == nil {
  65. t.Fatal("definition fetch = nil error, want a failure for a non-definition")
  66. }
  67. if !strings.Contains(err.Error(), "no definition") {
  68. t.Errorf("error = %q, want it to say there is no definition", err)
  69. }
  70. entries, _ := os.ReadDir(dir)
  71. if len(entries) != 0 {
  72. t.Errorf("definitions dir = %v, want nothing stored", entries)
  73. }
  74. }
  75. // A definition for another board must not be used, and saying so is the whole
  76. // point of carrying the identifiers.
  77. func TestDefinitionFlagRejectsTheWrongBoard(t *testing.T) {
  78. dir := t.TempDir()
  79. path := filepath.Join(dir, "other.json")
  80. if err := os.WriteFile(path, []byte(`{"name":"Other","vendorId":"0x1111","productId":"0x2222"}`), 0o600); err != nil {
  81. t.Fatal(err)
  82. }
  83. t.Cleanup(definitionFlagRestore(t))
  84. definitionFlag = path
  85. _, _, err := resolveCatalog(stubTargetData(0x1234, 0x5678))
  86. if err == nil {
  87. t.Fatal("resolveCatalog() = nil error, want a rejection for another board")
  88. }
  89. if !strings.Contains(err.Error(), "0x1111") {
  90. t.Errorf("error = %q, want it to name the board the file is for", err)
  91. }
  92. }
  93. // A definition in the data directory is used for its board without a flag.
  94. func TestResolveCatalogPrefersTheFileForTheBoard(t *testing.T) {
  95. dir := t.TempDir()
  96. if err := os.WriteFile(filepath.Join(dir, "b.json"), []byte(`{
  97. "name":"From File","vendorId":"0x1234","productId":"0x5678",
  98. "menus":[{"label":"Lighting","content":[{"label":"Backlight","content":[
  99. {"label":"Effect","type":"dropdown","content":["id_qmk_rgb_matrix_effect",3,2],
  100. "options":[["Only One",4]]}]}]}]}`), 0o600); err != nil {
  101. t.Fatal(err)
  102. }
  103. t.Cleanup(definitionFlagRestore(t))
  104. t.Cleanup(forceDefinitionsDir(t, dir))
  105. catalog, source, err := resolveCatalog(stubTargetData(0x1234, 0x5678))
  106. if err != nil {
  107. t.Fatalf("resolveCatalog() error = %v", err)
  108. }
  109. if id, ok := catalog.EffectID(3, "Only One"); !ok || id != 4 {
  110. t.Errorf("EffectID(rgb_matrix, \"Only One\") = %d, %t, want 4, true", id, ok)
  111. }
  112. if !strings.Contains(source, "b.json") {
  113. t.Errorf("source = %q, want the file it came from", source)
  114. }
  115. }
  116. // The Impact 80's definition is built into the binary, because `go install`
  117. // delivers a binary and no data directory, and this board's file cannot be
  118. // fetched. It is still the vendor's file and not a hand-written list, so it is
  119. // reported as the file it is and stays overridable.
  120. func TestResolveCatalogFallsBackToTheBuiltInDefinition(t *testing.T) {
  121. dir := t.TempDir()
  122. t.Cleanup(definitionFlagRestore(t))
  123. t.Cleanup(forceDefinitionsDir(t, dir))
  124. catalog, source, err := resolveCatalog(stubTargetData(0x36B0, 0x309F))
  125. if err != nil {
  126. t.Fatalf("resolveCatalog() error = %v", err)
  127. }
  128. if catalog == nil {
  129. t.Fatal("resolveCatalog() = nil, want the built-in definition: go install ships no data directory")
  130. }
  131. if want := "definitions/impact80.json"; source != want {
  132. t.Errorf("source = %q, want %q: it is the shipped file, not a path in an install", source, want)
  133. }
  134. if id, ok := catalog.EffectID(3, "riverflow"); !ok || id != 45 {
  135. t.Errorf("EffectID(3, \"riverflow\") = %d, %t, want 45, true", id, ok)
  136. }
  137. }
  138. // A file in a definitions directory wins over the copy built into the binary, or
  139. // the shipped file could never be corrected without a rebuild. This is the
  140. // property that keeps the built-in copy from being a second source of a name:
  141. // it is consulted last, and only when nothing else has one.
  142. func TestDefinitionsDirectoryOverridesTheBuiltInFile(t *testing.T) {
  143. dir := t.TempDir()
  144. t.Cleanup(definitionFlagRestore(t))
  145. t.Cleanup(forceDefinitionsDir(t, dir))
  146. replacement := `{"name":"Impact 80","vendorId":"0x36B0","productId":"0x309F",
  147. "menus":[{"label":"Lighting","content":[{"label":"Backlight","content":[
  148. {"label":"Effect","type":"dropdown","content":["id_qmk_rgb_matrix_effect",3,2],
  149. "options":[["only one",7]]}]}]}]}`
  150. if err := os.WriteFile(filepath.Join(dir, "impact80.json"), []byte(replacement), 0o644); err != nil {
  151. t.Fatal(err)
  152. }
  153. catalog, source, err := resolveCatalog(stubTargetData(0x36B0, 0x309F))
  154. if err != nil {
  155. t.Fatalf("resolveCatalog() error = %v", err)
  156. }
  157. if source != filepath.Join(dir, "impact80.json") {
  158. t.Errorf("source = %q, want the file in the directory", source)
  159. }
  160. if id, ok := catalog.EffectID(3, "riverflow"); ok {
  161. t.Errorf("EffectID(3, \"riverflow\") = %d, true, want not found: the placed file replaces the built-in one", id)
  162. }
  163. if id, ok := catalog.EffectID(3, "only one"); !ok || id != 7 {
  164. t.Errorf("EffectID(3, \"only one\") = %d, %t, want 7, true", id, ok)
  165. }
  166. }
  167. // An unknown board with no file has no catalog at all, which the commands
  168. // already report rather than guessing.
  169. func TestResolveCatalogHasNothingForAnUnknownBoard(t *testing.T) {
  170. dir := t.TempDir()
  171. t.Cleanup(definitionFlagRestore(t))
  172. t.Cleanup(forceDefinitionsDir(t, dir))
  173. catalog, source, err := resolveCatalog(stubTargetData(0x1111, 0x2222))
  174. if err != nil {
  175. t.Fatalf("resolveCatalog() error = %v", err)
  176. }
  177. if catalog != nil || source != "" {
  178. t.Errorf("resolveCatalog() = %v, %q, want nil, \"\"", catalog, source)
  179. }
  180. }
  181. // definitionFlagRestore resets --definition and returns a cleanup that restores
  182. // it, so a test can use the flag without leaking it into the next one.
  183. func definitionFlagRestore(t *testing.T) func() {
  184. t.Helper()
  185. original := definitionFlag
  186. return func() { definitionFlag = original }
  187. }
  188. // forceDefinitionsDir points the data directory at a test directory. The tool
  189. // looks for it next to the executable and then in the working directory, so a
  190. // test that wants its own has to make that lookup find it.
  191. func forceDefinitionsDir(t *testing.T, dir string) func() {
  192. t.Helper()
  193. original := definitionsDirOverride
  194. definitionsDirOverride = dir
  195. return func() { definitionsDirOverride = original }
  196. }
  197. // stubHTTPGet answers every request from a function instead of a network.
  198. func stubHTTPGet(t *testing.T, fn func(url string) ([]byte, int, error)) {
  199. t.Helper()
  200. original := httpGet
  201. httpGet = fn
  202. t.Cleanup(func() { httpGet = original })
  203. }
  204. // stubPrepareTarget makes the connected keyboard a fixed one, so a test does
  205. // not need hardware to describe a board.
  206. func stubPrepareTarget(t *testing.T, vendorID, productID uint16) {
  207. t.Helper()
  208. original := prepareTarget
  209. prepareTarget = func() (targetDeviceData, error) { return stubTargetData(vendorID, productID), nil }
  210. t.Cleanup(func() { prepareTarget = original })
  211. }
  212. // stubTargetData is a target for a board, for the catalog lookup tests.
  213. func stubTargetData(vendorID, productID uint16) targetDeviceData {
  214. return targetDeviceData{
  215. Device: intdevice.Device{VendorID: vendorID, ProductID: productID},
  216. Display: map[uint16]string{},
  217. }
  218. }
  219. // definition list is structured data, so --json has to reach it like every other
  220. // listing command; text by default is no excuse for a missing machine shape. The
  221. // definitions built into the binary are listed beside the ones in the user
  222. // directory, and each carries which of the two it is.
  223. func TestDefinitionListHonoursTheJSONFlag(t *testing.T) {
  224. dir := t.TempDir()
  225. if err := os.WriteFile(filepath.Join(dir, "b.json"), []byte(`{"name":"Test Board","vendorId":"0x1234","productId":"0x5678"}`), 0o600); err != nil {
  226. t.Fatal(err)
  227. }
  228. t.Cleanup(forceDefinitionsDir(t, dir))
  229. var out, errOut strings.Builder
  230. cmd := NewDefinitionCmd()
  231. cmd.SetOut(&out)
  232. cmd.SetErr(&errOut)
  233. cmd.SetArgs([]string{"list"})
  234. withJSON(t)
  235. if err := cmd.Execute(); err != nil {
  236. t.Fatalf("definition list --json error = %v", err)
  237. }
  238. var payload struct {
  239. Definitions []struct {
  240. Name string `json:"name"`
  241. VendorID string `json:"vendorId"`
  242. ProductID string `json:"productId"`
  243. Path string `json:"path"`
  244. Source string `json:"source"`
  245. } `json:"definitions"`
  246. }
  247. if err := json.Unmarshal([]byte(out.String()), &payload); err != nil {
  248. t.Fatalf("output is not JSON: %v (%q)", err, out.String())
  249. }
  250. var found *struct {
  251. Name string `json:"name"`
  252. VendorID string `json:"vendorId"`
  253. ProductID string `json:"productId"`
  254. Path string `json:"path"`
  255. Source string `json:"source"`
  256. }
  257. for i := range payload.Definitions {
  258. if payload.Definitions[i].Name == "Test Board" {
  259. found = &payload.Definitions[i]
  260. }
  261. }
  262. if found == nil {
  263. t.Fatalf("payload = %+v, want the file in the user directory", payload.Definitions)
  264. }
  265. if found.VendorID != "0x1234" || found.ProductID != "0x5678" {
  266. t.Errorf("identifiers = %s/%s, want 0x1234/0x5678", found.VendorID, found.ProductID)
  267. }
  268. if found.Source != "user" {
  269. t.Errorf("source = %q, want %q: a file in the user directory", found.Source, "user")
  270. }
  271. }
  272. // A board whose definition is built in and whose file is not in the user
  273. // directory still appears, marked as built-in. Without it a listing would say the
  274. // tool has no definition for the board it is driving.
  275. func TestDefinitionListShowsTheBuiltInDefinitions(t *testing.T) {
  276. t.Cleanup(forceDefinitionsDir(t, t.TempDir()))
  277. var out, errOut strings.Builder
  278. cmd := NewDefinitionCmd()
  279. cmd.SetOut(&out)
  280. cmd.SetErr(&errOut)
  281. cmd.SetArgs([]string{"list"})
  282. withJSON(t)
  283. if err := cmd.Execute(); err != nil {
  284. t.Fatalf("definition list --json error = %v", err)
  285. }
  286. var payload struct {
  287. Definitions []struct {
  288. Name string `json:"name"`
  289. Source string `json:"source"`
  290. } `json:"definitions"`
  291. }
  292. if err := json.Unmarshal([]byte(out.String()), &payload); err != nil {
  293. t.Fatalf("output is not JSON: %v (%q)", err, out.String())
  294. }
  295. if len(payload.Definitions) == 0 {
  296. t.Fatal("definitions = none, want the file built into the binary")
  297. }
  298. for _, d := range payload.Definitions {
  299. if d.Source != "built-in" {
  300. t.Errorf("%s source = %q, want %q", d.Name, d.Source, "built-in")
  301. }
  302. }
  303. }
  304. // A file in the user directory that describes a board the binary also carries
  305. // overrides it, and the listing says so, because the two files disagree and only
  306. // one of them is read.
  307. func TestDefinitionListReportsThatAUserFileShadowsABuiltInOne(t *testing.T) {
  308. dir := t.TempDir()
  309. replacement := `{"name":"Impact 80","vendorId":"0x36B0","productId":"0x309F"}`
  310. if err := os.WriteFile(filepath.Join(dir, "impact80.json"), []byte(replacement), 0o600); err != nil {
  311. t.Fatal(err)
  312. }
  313. t.Cleanup(forceDefinitionsDir(t, dir))
  314. var out, errOut strings.Builder
  315. cmd := NewDefinitionCmd()
  316. cmd.SetOut(&out)
  317. cmd.SetErr(&errOut)
  318. cmd.SetArgs([]string{"list"})
  319. if err := cmd.Execute(); err != nil {
  320. t.Fatalf("definition list error = %v", err)
  321. }
  322. if !strings.Contains(out.String(), "shadows the built-in copy") {
  323. t.Errorf("stdout = %q, want it to say the user file overrides the built-in one", out.String())
  324. }
  325. }
  326. func TestDefinitionListPrintsTextByDefault(t *testing.T) {
  327. dir := t.TempDir()
  328. if err := os.WriteFile(filepath.Join(dir, "b.json"), []byte(`{"name":"Test Board","vendorId":"0x1234","productId":"0x5678"}`), 0o600); err != nil {
  329. t.Fatal(err)
  330. }
  331. t.Cleanup(forceDefinitionsDir(t, dir))
  332. var out, errOut strings.Builder
  333. cmd := NewDefinitionCmd()
  334. cmd.SetOut(&out)
  335. cmd.SetErr(&errOut)
  336. cmd.SetArgs([]string{"list"})
  337. if err := cmd.Execute(); err != nil {
  338. t.Fatalf("definition list error = %v", err)
  339. }
  340. var probe any
  341. if err := json.Unmarshal([]byte(out.String()), &probe); err == nil {
  342. t.Errorf("stdout = %q, want text, not JSON", out.String())
  343. }
  344. if !strings.Contains(out.String(), "Test Board") {
  345. t.Errorf("stdout = %q, want the board name", out.String())
  346. }
  347. }
  348. // writeDefinition puts a definition file into a directory, for the tests that
  349. // need a board described by one.
  350. func writeDefinition(t *testing.T, dir, name, content string) {
  351. t.Helper()
  352. if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
  353. t.Fatal(err)
  354. }
  355. }