device_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package device
  2. import (
  3. "os"
  4. "path/filepath"
  5. "testing"
  6. )
  7. func TestLoadKeyboards(t *testing.T) {
  8. tmpDir := t.TempDir()
  9. tmpFile := filepath.Join(tmpDir, "keyboards.json")
  10. testData := `[
  11. {"name": "Test Keyboard 1", "vendorId": 22222, "productId": 1, "protocol": "via"},
  12. {"name": "Test Keyboard 2", "vendorId": 33333, "productId": 2, "protocol": "viapro"}
  13. ]`
  14. if err := os.WriteFile(tmpFile, []byte(testData), 0644); err != nil {
  15. t.Fatalf("failed to write test file: %v", err)
  16. }
  17. origFind := findKeyboardsJSON
  18. findKeyboardsJSON = func() (string, error) {
  19. return tmpFile, nil
  20. }
  21. defer func() { findKeyboardsJSON = origFind }()
  22. keyboards, err := LoadKeyboards()
  23. if err != nil {
  24. t.Fatalf("LoadKeyboards() returned error: %v", err)
  25. }
  26. if len(keyboards) != 2 {
  27. t.Errorf("LoadKeyboards() returned %d keyboards, want 2", len(keyboards))
  28. }
  29. if keyboards[0].Name != "Test Keyboard 1" {
  30. t.Errorf("First keyboard name = %q, want %q", keyboards[0].Name, "Test Keyboard 1")
  31. }
  32. if keyboards[0].VendorID != 22222 {
  33. t.Errorf("First keyboard VID = %d, want %d", keyboards[0].VendorID, 22222)
  34. }
  35. if keyboards[1].ProductID != 2 {
  36. t.Errorf("Second keyboard PID = %d, want %d", keyboards[1].ProductID, 2)
  37. }
  38. }
  39. func TestLoadKeyboardsInvalid(t *testing.T) {
  40. tmpDir := t.TempDir()
  41. tmpFile := filepath.Join(tmpDir, "keyboards.json")
  42. invalidData := `[this is not valid json`
  43. if err := os.WriteFile(tmpFile, []byte(invalidData), 0644); err != nil {
  44. t.Fatalf("failed to write test file: %v", err)
  45. }
  46. origFind := findKeyboardsJSON
  47. findKeyboardsJSON = func() (string, error) {
  48. return tmpFile, nil
  49. }
  50. defer func() { findKeyboardsJSON = origFind }()
  51. _, err := LoadKeyboards()
  52. if err == nil {
  53. t.Error("LoadKeyboards() expected error for invalid JSON, got nil")
  54. }
  55. }
  56. func TestLoadKeyboardsEmptyFile(t *testing.T) {
  57. tmpDir := t.TempDir()
  58. tmpFile := filepath.Join(tmpDir, "keyboards.json")
  59. if err := os.WriteFile(tmpFile, []byte("[]"), 0644); err != nil {
  60. t.Fatalf("failed to write test file: %v", err)
  61. }
  62. origFind := findKeyboardsJSON
  63. findKeyboardsJSON = func() (string, error) {
  64. return tmpFile, nil
  65. }
  66. defer func() { findKeyboardsJSON = origFind }()
  67. keyboards, err := LoadKeyboards()
  68. if err != nil {
  69. t.Fatalf("LoadKeyboards() returned error: %v", err)
  70. }
  71. if len(keyboards) != 0 {
  72. t.Errorf("LoadKeyboards() returned %d keyboards, want 0", len(keyboards))
  73. }
  74. }