device_overrides_test.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. // device_overrides_test.go — issue #797: nombre visible y tipo de dispositivo
  2. // como overrides persistidos (además del icono existente, #437).
  3. package httpapi
  4. import (
  5. "encoding/json"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. "github.com/gnacho/netpulse/server-go/internal/db"
  11. )
  12. func newOverrideTestServer(t *testing.T) *server {
  13. t.Helper()
  14. dataDir := t.TempDir()
  15. d, err := db.Open(dataDir)
  16. if err != nil {
  17. t.Fatalf("db: %v", err)
  18. }
  19. t.Cleanup(func() { _ = d.Close() })
  20. return &server{db: d}
  21. }
  22. func doOverridePut(t *testing.T, s *server, mac, body string) *httptest.ResponseRecorder {
  23. t.Helper()
  24. req := httptest.NewRequest("PUT", "/api/devices/"+mac+"/override", strings.NewReader(body))
  25. req.SetPathValue("mac", mac)
  26. rec := httptest.NewRecorder()
  27. s.handleDeviceOverridePut(rec, req)
  28. return rec
  29. }
  30. func doOverrideGet(t *testing.T, s *server, mac string) map[string]any {
  31. t.Helper()
  32. req := httptest.NewRequest("GET", "/api/devices/"+mac+"/override", nil)
  33. req.SetPathValue("mac", mac)
  34. rec := httptest.NewRecorder()
  35. s.handleDeviceOverrideGet(rec, req)
  36. var out map[string]any
  37. if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
  38. t.Fatalf("get decode: %v", err)
  39. }
  40. return out
  41. }
  42. func TestDeviceOverrideNameTypeRoundtrip(t *testing.T) {
  43. s := newOverrideTestServer(t)
  44. mac := "aa:bb:cc:dd:ee:ff"
  45. rec := doOverridePut(t, s, mac, `{"icon":"tv","name":"TV Salón","type":"tv"}`)
  46. if rec.Code != 200 {
  47. t.Fatalf("put: %d %s", rec.Code, rec.Body.String())
  48. }
  49. got := doOverrideGet(t, s, mac)
  50. if got["icon"] != "tv" || got["name"] != "TV Salón" || got["type"] != "tv" {
  51. t.Errorf("roundtrip incompleto: %+v", got)
  52. }
  53. }
  54. func TestDeviceOverridePartialPutPreservesOthers(t *testing.T) {
  55. s := newOverrideTestServer(t)
  56. mac := "aa:bb:cc:dd:ee:ff"
  57. doOverridePut(t, s, mac, `{"icon":"tv","name":"TV Salón","type":"tv"}`)
  58. // Cliente antiguo que solo envía icon (#772): name/type no se tocan.
  59. rec := doOverridePut(t, s, mac, `{"icon":"speaker"}`)
  60. if rec.Code != 200 {
  61. t.Fatalf("put parcial: %d", rec.Code)
  62. }
  63. got := doOverrideGet(t, s, mac)
  64. if got["icon"] != "speaker" || got["name"] != "TV Salón" || got["type"] != "tv" {
  65. t.Errorf("el put parcial pisó otros campos: %+v", got)
  66. }
  67. // Limpiar solo el nombre.
  68. doOverridePut(t, s, mac, `{"name":""}`)
  69. got = doOverrideGet(t, s, mac)
  70. if got["name"] != "" || got["icon"] != "speaker" || got["type"] != "tv" {
  71. t.Errorf("limpiar name no funcionó: %+v", got)
  72. }
  73. }
  74. func TestDeviceOverrideClearAllDeletesRow(t *testing.T) {
  75. s := newOverrideTestServer(t)
  76. mac := "aa:bb:cc:dd:ee:ff"
  77. doOverridePut(t, s, mac, `{"icon":"tv","name":"TV","type":"tv"}`)
  78. rec := doOverridePut(t, s, mac, `{"icon":"","name":"","type":""}`)
  79. if rec.Code != 200 {
  80. t.Fatalf("clear: %d", rec.Code)
  81. }
  82. var n int
  83. if err := s.db.QueryRow("SELECT COUNT(*) FROM device_overrides WHERE mac = ?", mac).Scan(&n); err != nil {
  84. t.Fatalf("count: %v", err)
  85. }
  86. if n != 0 {
  87. t.Errorf("la fila debió borrarse con los tres campos vacíos")
  88. }
  89. }
  90. func TestDeviceOverrideValidation(t *testing.T) {
  91. s := newOverrideTestServer(t)
  92. mac := "aa:bb:cc:dd:ee:ff"
  93. if rec := doOverridePut(t, s, mac, `{"type":"router-magico"}`); rec.Code != 400 {
  94. t.Errorf("tipo inválido debió dar 400, dio %d", rec.Code)
  95. }
  96. if rec := doOverridePut(t, s, mac, `{"icon":"icono-falso"}`); rec.Code != 400 {
  97. t.Errorf("icon inválido debió dar 400, dio %d", rec.Code)
  98. }
  99. if rec := doOverridePut(t, s, "not-a-mac", `{"name":"x"}`); rec.Code != 400 {
  100. t.Errorf("mac inválida debió dar 400, dio %d", rec.Code)
  101. }
  102. // Nombre con salto de línea: rechazado.
  103. if rec := doOverridePut(t, s, mac, `{"name":"a\nb"}`); rec.Code != 400 {
  104. t.Errorf("name con newline debió dar 400, dio %d", rec.Code)
  105. }
  106. // Tipo válido del clasificador: aceptado.
  107. if rec := doOverridePut(t, s, mac, `{"type":"movil"}`); rec.Code != 200 {
  108. t.Errorf("tipo válil debió dar 200, dio %d", rec.Code)
  109. }
  110. }
  111. // #1145: DELETE /api/devices/{mac} borra la fila del registro y 404 si no
  112. // existe. El handler requiere admin (el test llama al handler directamente
  113. // con PathValue, como el resto de tests de handlers con PathValue).
  114. func TestDeviceDelete(t *testing.T) {
  115. s := panelTestServer(t)
  116. if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('AA:BB:CC:DD:EE:FF', 1, 2, 'watch')", ); err != nil {
  117. t.Fatalf("seed: %v", err)
  118. }
  119. r := httptest.NewRequest(http.MethodDelete, "/api/devices/aa-bb-cc-dd-ee-ff", nil)
  120. r.SetPathValue("mac", "aa-bb-cc-dd-ee-ff")
  121. rec := httptest.NewRecorder()
  122. s.handleDeviceDelete(rec, r)
  123. if rec.Code != http.StatusNoContent {
  124. t.Fatalf("status = %d, want 204", rec.Code)
  125. }
  126. var n int
  127. if err := s.db.QueryRow("SELECT COUNT(*) FROM device_seen WHERE mac = 'AA:BB:CC:DD:EE:FF'").Scan(&n); err != nil {
  128. t.Fatal(err)
  129. }
  130. if n != 0 {
  131. t.Fatalf("rows = %d, want 0 (borrado)", n)
  132. }
  133. // MAC desconocida: 404.
  134. rec = httptest.NewRecorder()
  135. r = httptest.NewRequest(http.MethodDelete, "/api/devices/11-22-33-44-55-66", nil)
  136. r.SetPathValue("mac", "11-22-33-44-55-66")
  137. s.handleDeviceDelete(rec, r)
  138. if rec.Code != http.StatusNotFound {
  139. t.Fatalf("status = %d, want 404", rec.Code)
  140. }
  141. }
  142. // #1151: link con validaciones (self 400, ok 200, ya enlazada 409, target
  143. // alias 409) y unlink (204 / 404).
  144. func TestDeviceLinkPutDelete(t *testing.T) {
  145. s := panelTestServer(t)
  146. do := func(method, mac, body string) *httptest.ResponseRecorder {
  147. r := httptest.NewRequest(method, "/api/devices/"+mac+"/link", strings.NewReader(body))
  148. r.SetPathValue("mac", mac)
  149. if body != "" {
  150. r.Header.Set("Content-Type", "application/json")
  151. }
  152. rec := httptest.NewRecorder()
  153. if method == http.MethodPut {
  154. s.handleDeviceLinkPut(rec, r)
  155. } else {
  156. s.handleDeviceLinkDelete(rec, r)
  157. }
  158. return rec
  159. }
  160. // self-link: 400
  161. if rec := do(http.MethodPut, "AA:AA:AA:00:00:01", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusBadRequest {
  162. t.Fatalf("self link = %d, want 400", rec.Code)
  163. }
  164. // ok: 200
  165. if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusOK {
  166. t.Fatalf("link = %d, want 200", rec.Code)
  167. }
  168. // ya enlazada: 409
  169. if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:09"}`); rec.Code != http.StatusConflict {
  170. t.Fatalf("relink = %d, want 409", rec.Code)
  171. }
  172. // target es a su vez alias: 409
  173. if rec := do(http.MethodPut, "AA:AA:AA:00:00:03", `{"target":"AA:AA:AA:00:00:02"}`); rec.Code != http.StatusConflict {
  174. t.Fatalf("target alias = %d, want 409", rec.Code)
  175. }
  176. // unlink: 204 y 404
  177. if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNoContent {
  178. t.Fatalf("unlink = %d, want 204", rec.Code)
  179. }
  180. if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNotFound {
  181. t.Fatalf("unlink de nuevo = %d, want 404", rec.Code)
  182. }
  183. }