| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572 |
- package main
- import (
- "encoding/json"
- "errors"
- "net/http"
- "os"
- "path/filepath"
- "strings"
- "testing"
- intdevice "netdome.biz/paul/qmk-rgb/internal/device"
- )
- func TestFetchDefinitionStoresTheFileForTheBoard(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- stubPrepareTarget(t, 0x1234, 0x5678)
- served := `{"name":"Test Board","vendorProductId":305419896,"menus":[]}`
- var requested []string
- stubHTTPGet(t, func(url string) ([]byte, int, error) {
- requested = append(requested, url)
- if strings.Contains(url, "/v3/") {
- return []byte(served), http.StatusOK, nil
- }
- return nil, http.StatusNotFound, errors.New("404")
- })
- cmd := NewKeyboardFetchCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("keyboard fetch error = %v (stderr %q)", err, errOut.String())
- }
- if len(requested) != 1 || !strings.Contains(requested[0], "/v3/305419896.json") {
- t.Errorf("requested = %v, want one v3 URL for vendorProductId 305419896", requested)
- }
- if !strings.Contains(out.String(), "Test Board") {
- t.Errorf("stdout = %q, want the board name", out.String())
- }
- entries, err := os.ReadDir(dir)
- if err != nil {
- t.Fatal(err)
- }
- if len(entries) != 1 || !strings.HasSuffix(entries[0].Name(), ".json") {
- t.Fatalf("definitions dir = %v, want one JSON file", entries)
- }
- }
- // A definition in the user directory may be one the user has edited, and nothing
- // on disk says which it is. So a second fetch must not replace it, and must say
- // that the file is there rather than write over it silently.
- func TestFetchDoesNotReplaceAStoredDefinition(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceFetchRestore(t))
- stubPrepareTarget(t, 0x1234, 0x5678)
- edited := `{"name":"Test Board","vendorProductId":305419896,"menus":[],"note":"hand edited"}`
- if err := os.WriteFile(filepath.Join(dir, "test_board.json"), []byte(edited), 0o644); err != nil {
- t.Fatal(err)
- }
- // No HTTP stub: a request would panic here, which is the point. The user is
- // told the file exists without waiting on the network.
- cmd := NewKeyboardFetchCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- err := cmd.Execute()
- if err == nil {
- t.Fatal("keyboard fetch = nil error, want a refusal to replace a stored definition")
- }
- if !strings.Contains(err.Error(), "already at") || !strings.Contains(err.Error(), "--force") {
- t.Errorf("error = %q, want it to name the file and --force", err)
- }
- got, readErr := os.ReadFile(filepath.Join(dir, "test_board.json"))
- if readErr != nil {
- t.Fatal(readErr)
- }
- if string(got) != edited {
- t.Errorf("stored file = %q, want it untouched (%q)", got, edited)
- }
- }
- // --force is the only way to replace a stored definition, and it has to say that
- // is what happened, because the file it wrote over is gone.
- func TestFetchForceReplacesAStoredDefinition(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceFetchRestore(t))
- stubPrepareTarget(t, 0x1234, 0x5678)
- if err := os.WriteFile(filepath.Join(dir, "test_board.json"),
- []byte(`{"name":"Test Board","vendorProductId":305419896,"menus":[],"note":"hand edited"}`), 0o644); err != nil {
- t.Fatal(err)
- }
- served := `{"name":"Test Board","vendorProductId":305419896,"menus":[]}`
- stubHTTPGet(t, func(url string) ([]byte, int, error) {
- if strings.Contains(url, "/v3/") {
- return []byte(served), http.StatusOK, nil
- }
- return nil, http.StatusNotFound, errors.New("404")
- })
- cmd := NewKeyboardFetchCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- cmd.SetArgs([]string{"--force"})
- if err := cmd.Execute(); err != nil {
- t.Fatalf("keyboard fetch --force error = %v (stderr %q)", err, errOut.String())
- }
- if !strings.Contains(out.String(), "Replaced definition") {
- t.Errorf("stdout = %q, want it to say the definition was replaced", out.String())
- }
- entries, err := os.ReadDir(dir)
- if err != nil {
- t.Fatal(err)
- }
- if len(entries) != 1 {
- t.Fatalf("definitions dir = %v, want the one file replaced in place", entries)
- }
- got, readErr := os.ReadFile(filepath.Join(dir, entries[0].Name()))
- if readErr != nil {
- t.Fatal(readErr)
- }
- if string(got) != served {
- t.Errorf("stored file = %q, want what the server served (%q)", got, served)
- }
- }
- // A definition for a different board is not a reason to refuse: the fetch is for
- // this one, and that one is still worth having alongside.
- func TestFetchStoresAlongsideAnotherBoardsDefinition(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceFetchRestore(t))
- stubPrepareTarget(t, 0x1234, 0x5678)
- if err := os.WriteFile(filepath.Join(dir, "other.json"),
- []byte(`{"name":"Other","vendorId":"0x1111","productId":"0x2222"}`), 0o644); err != nil {
- t.Fatal(err)
- }
- served := `{"name":"Test Board","vendorProductId":305419896,"menus":[]}`
- stubHTTPGet(t, func(string) ([]byte, int, error) {
- return []byte(served), http.StatusOK, nil
- })
- cmd := NewKeyboardFetchCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("keyboard fetch error = %v (stderr %q)", err, errOut.String())
- }
- entries, err := os.ReadDir(dir)
- if err != nil {
- t.Fatal(err)
- }
- if len(entries) != 2 {
- t.Errorf("definitions dir = %v, want the other board's file kept alongside", entries)
- }
- }
- // The vendor issues one vendor and product ID to two models, so a directory can
- // hold two files describing the same board. --force has to leave one, not two:
- // which of them is read would otherwise depend on the order the directory comes
- // back in.
- func TestFetchForceLeavesOneFileForABoardWithTwo(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- t.Cleanup(forceFetchRestore(t))
- stubPrepareTarget(t, 0x320F, 0x5055)
- for _, name := range []string{"first.json", "second.json"} {
- body := `{"name":"Twin","vendorId":"0x320F","productId":"0x5055","menus":[]}`
- if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
- t.Fatal(err)
- }
- }
- served := `{"name":"Twin","vendorProductId":839864405,"menus":[]}`
- stubHTTPGet(t, func(string) ([]byte, int, error) {
- return []byte(served), http.StatusOK, nil
- })
- cmd := NewKeyboardFetchCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- cmd.SetArgs([]string{"--force"})
- if err := cmd.Execute(); err != nil {
- t.Fatalf("keyboard fetch --force error = %v (stderr %q)", err, errOut.String())
- }
- entries, err := os.ReadDir(dir)
- if err != nil {
- t.Fatal(err)
- }
- if len(entries) != 1 {
- names := make([]string, 0, len(entries))
- for _, e := range entries {
- names = append(names, e.Name())
- }
- t.Errorf("definitions dir = %v, want exactly one file for the board", names)
- }
- }
- // An unknown board is answered with a web page and a success status, so the
- // fetch must not store it and must say what happened instead.
- func TestFetchDefinitionRejectsAPageThatIsNotADefinition(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- stubPrepareTarget(t, 0x1234, 0x5678)
- stubHTTPGet(t, func(string) ([]byte, int, error) {
- return []byte("<!doctype html><html><head><title>VIA</title></head></html>"), http.StatusOK, nil
- })
- cmd := NewKeyboardFetchCmd()
- var out, errOut strings.Builder
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- err := cmd.Execute()
- if err == nil {
- t.Fatal("keyboard fetch = nil error, want a failure for a non-definition")
- }
- if !strings.Contains(err.Error(), "no definition") {
- t.Errorf("error = %q, want it to say there is no definition", err)
- }
- entries, _ := os.ReadDir(dir)
- if len(entries) != 0 {
- t.Errorf("definitions dir = %v, want nothing stored", entries)
- }
- }
- // A definition for another board must not be used, and saying so is the whole
- // point of carrying the identifiers.
- func TestDefinitionFlagRejectsTheWrongBoard(t *testing.T) {
- dir := t.TempDir()
- path := filepath.Join(dir, "other.json")
- if err := os.WriteFile(path, []byte(`{"name":"Other","vendorId":"0x1111","productId":"0x2222"}`), 0o600); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(definitionFlagRestore(t))
- definitionFlag = path
- _, _, err := resolveCatalog(stubTargetData(0x1234, 0x5678))
- if err == nil {
- t.Fatal("resolveCatalog() = nil error, want a rejection for another board")
- }
- if !strings.Contains(err.Error(), "0x1111") {
- t.Errorf("error = %q, want it to name the board the file is for", err)
- }
- }
- // A definition in the data directory is used for its board without a flag.
- func TestResolveCatalogPrefersTheFileForTheBoard(t *testing.T) {
- dir := t.TempDir()
- if err := os.WriteFile(filepath.Join(dir, "b.json"), []byte(`{
- "name":"From File","vendorId":"0x1234","productId":"0x5678",
- "menus":[{"label":"Lighting","content":[{"label":"Backlight","content":[
- {"label":"Effect","type":"dropdown","content":["id_qmk_rgb_matrix_effect",3,2],
- "options":[["Only One",4]]}]}]}]}`), 0o600); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- catalog, source, err := resolveCatalog(stubTargetData(0x1234, 0x5678))
- if err != nil {
- t.Fatalf("resolveCatalog() error = %v", err)
- }
- if id, ok := catalog.EffectID(3, "Only One"); !ok || id != 4 {
- t.Errorf("EffectID(rgb_matrix, \"Only One\") = %d, %t, want 4, true", id, ok)
- }
- if !strings.Contains(source, "b.json") {
- t.Errorf("source = %q, want the file it came from", source)
- }
- }
- // The Impact 80's definition is built into the binary, because `go install`
- // delivers a binary and no data directory, and this board's file cannot be
- // fetched. It is still the vendor's file and not a hand-written list, so it is
- // reported as the file it is and stays overridable.
- func TestResolveCatalogFallsBackToTheBuiltInDefinition(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- catalog, source, err := resolveCatalog(stubTargetData(0x36B0, 0x309F))
- if err != nil {
- t.Fatalf("resolveCatalog() error = %v", err)
- }
- if catalog == nil {
- t.Fatal("resolveCatalog() = nil, want the built-in definition: go install ships no data directory")
- }
- if want := "definitions/impact80.json"; source != want {
- t.Errorf("source = %q, want %q: it is the shipped file, not a path in an install", source, want)
- }
- if id, ok := catalog.EffectID(3, "riverflow"); !ok || id != 45 {
- t.Errorf("EffectID(3, \"riverflow\") = %d, %t, want 45, true", id, ok)
- }
- }
- // A file in a definitions directory wins over the copy built into the binary, or
- // the shipped file could never be corrected without a rebuild. This is the
- // property that keeps the built-in copy from being a second source of a name:
- // it is consulted last, and only when nothing else has one.
- func TestDefinitionsDirectoryOverridesTheBuiltInFile(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- replacement := `{"name":"Impact 80","vendorId":"0x36B0","productId":"0x309F",
- "menus":[{"label":"Lighting","content":[{"label":"Backlight","content":[
- {"label":"Effect","type":"dropdown","content":["id_qmk_rgb_matrix_effect",3,2],
- "options":[["only one",7]]}]}]}]}`
- if err := os.WriteFile(filepath.Join(dir, "impact80.json"), []byte(replacement), 0o644); err != nil {
- t.Fatal(err)
- }
- catalog, source, err := resolveCatalog(stubTargetData(0x36B0, 0x309F))
- if err != nil {
- t.Fatalf("resolveCatalog() error = %v", err)
- }
- if source != filepath.Join(dir, "impact80.json") {
- t.Errorf("source = %q, want the file in the directory", source)
- }
- if id, ok := catalog.EffectID(3, "riverflow"); ok {
- t.Errorf("EffectID(3, \"riverflow\") = %d, true, want not found: the placed file replaces the built-in one", id)
- }
- if id, ok := catalog.EffectID(3, "only one"); !ok || id != 7 {
- t.Errorf("EffectID(3, \"only one\") = %d, %t, want 7, true", id, ok)
- }
- }
- // An unknown board with no file has no catalog at all, which the commands
- // already report rather than guessing.
- func TestResolveCatalogHasNothingForAnUnknownBoard(t *testing.T) {
- dir := t.TempDir()
- t.Cleanup(definitionFlagRestore(t))
- t.Cleanup(forceDefinitionsDir(t, dir))
- catalog, source, err := resolveCatalog(stubTargetData(0x1111, 0x2222))
- if err != nil {
- t.Fatalf("resolveCatalog() error = %v", err)
- }
- if catalog != nil || source != "" {
- t.Errorf("resolveCatalog() = %v, %q, want nil, \"\"", catalog, source)
- }
- }
- // definitionFlagRestore resets --definition and returns a cleanup that restores
- // it, so a test can use the flag without leaking it into the next one.
- func definitionFlagRestore(t *testing.T) func() {
- t.Helper()
- original := definitionFlag
- return func() { definitionFlag = original }
- }
- // forceFetchRestore resets --force, so a test that sets it does not leak it into
- // the next one.
- func forceFetchRestore(t *testing.T) func() {
- t.Helper()
- original := forceFetch
- return func() { forceFetch = original }
- }
- // forceDefinitionsDir points the data directory at a test directory. The tool
- // looks for it next to the executable and then in the working directory, so a
- // test that wants its own has to make that lookup find it.
- func forceDefinitionsDir(t *testing.T, dir string) func() {
- t.Helper()
- original := definitionsDirOverride
- definitionsDirOverride = dir
- return func() { definitionsDirOverride = original }
- }
- // stubHTTPGet answers every request from a function instead of a network.
- func stubHTTPGet(t *testing.T, fn func(url string) ([]byte, int, error)) {
- t.Helper()
- original := httpGet
- httpGet = fn
- t.Cleanup(func() { httpGet = original })
- }
- // stubPrepareTarget makes the connected keyboard a fixed one, so a test does
- // not need hardware to describe a board.
- func stubPrepareTarget(t *testing.T, vendorID, productID uint16) {
- t.Helper()
- original := prepareTarget
- prepareTarget = func(string) (targetDeviceData, error) { return stubTargetData(vendorID, productID), nil }
- t.Cleanup(func() { prepareTarget = original })
- }
- // stubTargetData is a target for a board, for the catalog lookup tests.
- func stubTargetData(vendorID, productID uint16) targetDeviceData {
- return targetDeviceData{
- Device: intdevice.Device{VendorID: vendorID, ProductID: productID},
- Display: map[uint16]string{},
- }
- }
- // keyboard definitions is structured data, so --json has to reach it like every other
- // listing command; text by default is no excuse for a missing machine shape. The
- // definitions built into the binary are listed beside the ones in the user
- // directory, and each carries which of the two it is.
- func TestDefinitionListHonoursTheJSONFlag(t *testing.T) {
- dir := t.TempDir()
- if err := os.WriteFile(filepath.Join(dir, "b.json"), []byte(`{"name":"Test Board","vendorId":"0x1234","productId":"0x5678"}`), 0o600); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(forceDefinitionsDir(t, dir))
- var out, errOut strings.Builder
- cmd := NewKeyboardDefinitionsCmd()
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- withJSON(t)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("keyboard definitions --json error = %v", err)
- }
- var payload struct {
- Definitions []struct {
- Name string `json:"name"`
- VendorID string `json:"vendorId"`
- ProductID string `json:"productId"`
- Path string `json:"path"`
- Source string `json:"source"`
- } `json:"definitions"`
- }
- if err := json.Unmarshal([]byte(out.String()), &payload); err != nil {
- t.Fatalf("output is not JSON: %v (%q)", err, out.String())
- }
- var found *struct {
- Name string `json:"name"`
- VendorID string `json:"vendorId"`
- ProductID string `json:"productId"`
- Path string `json:"path"`
- Source string `json:"source"`
- }
- for i := range payload.Definitions {
- if payload.Definitions[i].Name == "Test Board" {
- found = &payload.Definitions[i]
- }
- }
- if found == nil {
- t.Fatalf("payload = %+v, want the file in the user directory", payload.Definitions)
- }
- if found.VendorID != "0x1234" || found.ProductID != "0x5678" {
- t.Errorf("identifiers = %s/%s, want 0x1234/0x5678", found.VendorID, found.ProductID)
- }
- if found.Source != "user" {
- t.Errorf("source = %q, want %q: a file in the user directory", found.Source, "user")
- }
- }
- // A board whose definition is built in and whose file is not in the user
- // directory still appears, marked as built-in. Without it a listing would say the
- // tool has no definition for the board it is driving.
- func TestDefinitionListShowsTheBuiltInDefinitions(t *testing.T) {
- t.Cleanup(forceDefinitionsDir(t, t.TempDir()))
- var out, errOut strings.Builder
- cmd := NewKeyboardDefinitionsCmd()
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- withJSON(t)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("keyboard definitions --json error = %v", err)
- }
- var payload struct {
- Definitions []struct {
- Name string `json:"name"`
- Source string `json:"source"`
- } `json:"definitions"`
- }
- if err := json.Unmarshal([]byte(out.String()), &payload); err != nil {
- t.Fatalf("output is not JSON: %v (%q)", err, out.String())
- }
- if len(payload.Definitions) == 0 {
- t.Fatal("definitions = none, want the file built into the binary")
- }
- for _, d := range payload.Definitions {
- if d.Source != "built-in" {
- t.Errorf("%s source = %q, want %q", d.Name, d.Source, "built-in")
- }
- }
- }
- // A file in the user directory that describes a board the binary also carries
- // overrides it, and the listing says so, because the two files disagree and only
- // one of them is read.
- func TestDefinitionListReportsThatAUserFileShadowsABuiltInOne(t *testing.T) {
- dir := t.TempDir()
- replacement := `{"name":"Impact 80","vendorId":"0x36B0","productId":"0x309F"}`
- if err := os.WriteFile(filepath.Join(dir, "impact80.json"), []byte(replacement), 0o600); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(forceDefinitionsDir(t, dir))
- var out, errOut strings.Builder
- cmd := NewKeyboardDefinitionsCmd()
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("keyboard definitions error = %v", err)
- }
- if !strings.Contains(out.String(), "shadows the built-in copy") {
- t.Errorf("stdout = %q, want it to say the user file overrides the built-in one", out.String())
- }
- }
- func TestDefinitionListPrintsTextByDefault(t *testing.T) {
- dir := t.TempDir()
- if err := os.WriteFile(filepath.Join(dir, "b.json"), []byte(`{"name":"Test Board","vendorId":"0x1234","productId":"0x5678"}`), 0o600); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(forceDefinitionsDir(t, dir))
- var out, errOut strings.Builder
- cmd := NewKeyboardDefinitionsCmd()
- cmd.SetOut(&out)
- cmd.SetErr(&errOut)
- if err := cmd.Execute(); err != nil {
- t.Fatalf("keyboard definitions error = %v", err)
- }
- var probe any
- if err := json.Unmarshal([]byte(out.String()), &probe); err == nil {
- t.Errorf("stdout = %q, want text, not JSON", out.String())
- }
- if !strings.Contains(out.String(), "Test Board") {
- t.Errorf("stdout = %q, want the board name", out.String())
- }
- }
- // writeDefinition puts a definition file into a directory, for the tests that
- // need a board described by one.
- func writeDefinition(t *testing.T, dir, name, content string) {
- t.Helper()
- if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
- t.Fatal(err)
- }
- }
|