| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package device
- import (
- "os"
- "path/filepath"
- "testing"
- )
- func TestLoadKeyboards(t *testing.T) {
- // Create a temporary keyboards.json for testing
- tmpDir := t.TempDir()
- tmpFile := filepath.Join(tmpDir, "keyboards.json")
- testData := `[
- {"name": "Test Keyboard 1", "vendorId": 22222, "productId": 1, "protocol": "via"},
- {"name": "Test Keyboard 2", "vendorId": 33333, "productId": 2, "protocol": "viapro"}
- ]`
- if err := os.WriteFile(tmpFile, []byte(testData), 0644); err != nil {
- t.Fatalf("failed to write test file: %v", err)
- }
- // Save original function and override search path for testing
- origFind := findKeyboardsJSON
- findKeyboardsJSON = func() (string, error) {
- return tmpFile, nil
- }
- defer func() { findKeyboardsJSON = origFind }()
- keyboards, err := LoadKeyboards()
- if err != nil {
- t.Fatalf("LoadKeyboards() returned error: %v", err)
- }
- if len(keyboards) != 2 {
- t.Errorf("LoadKeyboards() returned %d keyboards, want 2", len(keyboards))
- }
- if keyboards[0].Name != "Test Keyboard 1" {
- t.Errorf("First keyboard name = %q, want %q", keyboards[0].Name, "Test Keyboard 1")
- }
- if keyboards[0].VendorID != 22222 {
- t.Errorf("First keyboard VID = %d, want %d", keyboards[0].VendorID, 22222)
- }
- if keyboards[1].ProductID != 2 {
- t.Errorf("Second keyboard PID = %d, want %d", keyboards[1].ProductID, 2)
- }
- }
- func TestLoadKeyboardsInvalid(t *testing.T) {
- // Test with invalid JSON
- tmpDir := t.TempDir()
- tmpFile := filepath.Join(tmpDir, "keyboards.json")
- invalidData := `[this is not valid json`
- if err := os.WriteFile(tmpFile, []byte(invalidData), 0644); err != nil {
- t.Fatalf("failed to write test file: %v", err)
- }
- origFind := findKeyboardsJSON
- findKeyboardsJSON = func() (string, error) {
- return tmpFile, nil
- }
- defer func() { findKeyboardsJSON = origFind }()
- _, err := LoadKeyboards()
- if err == nil {
- t.Error("LoadKeyboards() expected error for invalid JSON, got nil")
- }
- }
- func TestLoadKeyboardsEmptyFile(t *testing.T) {
- tmpDir := t.TempDir()
- tmpFile := filepath.Join(tmpDir, "keyboards.json")
- if err := os.WriteFile(tmpFile, []byte("[]"), 0644); err != nil {
- t.Fatalf("failed to write test file: %v", err)
- }
- origFind := findKeyboardsJSON
- findKeyboardsJSON = func() (string, error) {
- return tmpFile, nil
- }
- defer func() { findKeyboardsJSON = origFind }()
- keyboards, err := LoadKeyboards()
- if err != nil {
- t.Fatalf("LoadKeyboards() returned error: %v", err)
- }
- if len(keyboards) != 0 {
- t.Errorf("LoadKeyboards() returned %d keyboards, want 0", len(keyboards))
- }
- }
|