device_overrides_test.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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","notifyOffline":true}`)
  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" || got["notifyOffline"] != true {
  51. t.Errorf("roundtrip incompleto: %+v", got)
  52. }
  53. }
  54. func TestDeviceOverrideNotifyOffline(t *testing.T) {
  55. s := newOverrideTestServer(t)
  56. mac := "aa:bb:cc:dd:ee:ff"
  57. // Marcar opt-in: persiste el flag aunque icon/name/type queden vacíos.
  58. if rec := doOverridePut(t, s, mac, `{"notifyOffline":true}`); rec.Code != 200 {
  59. t.Fatalf("notifyOffline true: %d", rec.Code)
  60. }
  61. if got := doOverrideGet(t, s, mac); got["notifyOffline"] != true {
  62. t.Errorf("notifyOffline no persistió: %+v", got)
  63. }
  64. // Apagar el flag con el resto vacío: la fila se borra (cero estado).
  65. if rec := doOverridePut(t, s, mac, `{"notifyOffline":false}`); rec.Code != 200 {
  66. t.Fatalf("notifyOffline false: %d", rec.Code)
  67. }
  68. var n int
  69. if err := s.db.QueryRow("SELECT COUNT(*) FROM device_overrides WHERE mac = ?", mac).Scan(&n); err != nil {
  70. t.Fatalf("count: %v", err)
  71. }
  72. if n != 0 {
  73. t.Errorf("la fila debió borrarse con notifyOffline=false y sin más campos, quedaron %d", n)
  74. }
  75. // El flag se conserva ante un put parcial que no lo envía (cliente antiguo).
  76. doOverridePut(t, s, mac, `{"name":"TV","notifyOffline":true}`)
  77. if rec := doOverridePut(t, s, mac, `{"icon":"tv"}`); rec.Code != 200 {
  78. t.Fatalf("put parcial: %d", rec.Code)
  79. }
  80. if got := doOverrideGet(t, s, mac); got["notifyOffline"] != true {
  81. t.Errorf("el put parcial pisó notifyOffline: %+v", got)
  82. }
  83. // Tipo inválido (string en un bool): el decode falla y devuelve 400.
  84. if rec := doOverridePut(t, s, mac, `{"notifyOffline":"yes"}`); rec.Code != 400 {
  85. t.Errorf("notifyOffline no booleano debió dar 400, dio %d", rec.Code)
  86. }
  87. }
  88. func TestDeviceOverridePartialPutPreservesOthers(t *testing.T) {
  89. s := newOverrideTestServer(t)
  90. mac := "aa:bb:cc:dd:ee:ff"
  91. doOverridePut(t, s, mac, `{"icon":"tv","name":"TV Salón","type":"tv"}`)
  92. // Cliente antiguo que solo envía icon (#772): name/type no se tocan.
  93. rec := doOverridePut(t, s, mac, `{"icon":"speaker"}`)
  94. if rec.Code != 200 {
  95. t.Fatalf("put parcial: %d", rec.Code)
  96. }
  97. got := doOverrideGet(t, s, mac)
  98. if got["icon"] != "speaker" || got["name"] != "TV Salón" || got["type"] != "tv" {
  99. t.Errorf("el put parcial pisó otros campos: %+v", got)
  100. }
  101. // Limpiar solo el nombre.
  102. doOverridePut(t, s, mac, `{"name":""}`)
  103. got = doOverrideGet(t, s, mac)
  104. if got["name"] != "" || got["icon"] != "speaker" || got["type"] != "tv" {
  105. t.Errorf("limpiar name no funcionó: %+v", got)
  106. }
  107. }
  108. func TestDeviceOverrideClearAllDeletesRow(t *testing.T) {
  109. s := newOverrideTestServer(t)
  110. mac := "aa:bb:cc:dd:ee:ff"
  111. doOverridePut(t, s, mac, `{"icon":"tv","name":"TV","type":"tv"}`)
  112. rec := doOverridePut(t, s, mac, `{"icon":"","name":"","type":""}`)
  113. if rec.Code != 200 {
  114. t.Fatalf("clear: %d", rec.Code)
  115. }
  116. var n int
  117. if err := s.db.QueryRow("SELECT COUNT(*) FROM device_overrides WHERE mac = ?", mac).Scan(&n); err != nil {
  118. t.Fatalf("count: %v", err)
  119. }
  120. if n != 0 {
  121. t.Errorf("la fila debió borrarse con los tres campos vacíos")
  122. }
  123. }
  124. func TestDeviceOverrideValidation(t *testing.T) {
  125. s := newOverrideTestServer(t)
  126. mac := "aa:bb:cc:dd:ee:ff"
  127. if rec := doOverridePut(t, s, mac, `{"type":"router-magico"}`); rec.Code != 400 {
  128. t.Errorf("tipo inválido debió dar 400, dio %d", rec.Code)
  129. }
  130. if rec := doOverridePut(t, s, mac, `{"icon":"icono-falso"}`); rec.Code != 400 {
  131. t.Errorf("icon inválido debió dar 400, dio %d", rec.Code)
  132. }
  133. if rec := doOverridePut(t, s, "not-a-mac", `{"name":"x"}`); rec.Code != 400 {
  134. t.Errorf("mac inválida debió dar 400, dio %d", rec.Code)
  135. }
  136. // Nombre con salto de línea: rechazado.
  137. if rec := doOverridePut(t, s, mac, `{"name":"a\nb"}`); rec.Code != 400 {
  138. t.Errorf("name con newline debió dar 400, dio %d", rec.Code)
  139. }
  140. // Tipo válido del clasificador: aceptado.
  141. if rec := doOverridePut(t, s, mac, `{"type":"movil"}`); rec.Code != 200 {
  142. t.Errorf("tipo válil debió dar 200, dio %d", rec.Code)
  143. }
  144. }
  145. // #1145: DELETE /api/devices/{mac} borra la fila del registro y 404 si no
  146. // existe. El handler requiere admin (el test llama al handler directamente
  147. // con PathValue, como el resto de tests de handlers con PathValue).
  148. func TestDeviceDelete(t *testing.T) {
  149. s := panelTestServer(t)
  150. 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 {
  151. t.Fatalf("seed: %v", err)
  152. }
  153. r := httptest.NewRequest(http.MethodDelete, "/api/devices/aa-bb-cc-dd-ee-ff", nil)
  154. r.SetPathValue("mac", "aa-bb-cc-dd-ee-ff")
  155. rec := httptest.NewRecorder()
  156. s.handleDeviceDelete(rec, r)
  157. if rec.Code != http.StatusNoContent {
  158. t.Fatalf("status = %d, want 204", rec.Code)
  159. }
  160. var n int
  161. if err := s.db.QueryRow("SELECT COUNT(*) FROM device_seen WHERE mac = 'AA:BB:CC:DD:EE:FF'").Scan(&n); err != nil {
  162. t.Fatal(err)
  163. }
  164. if n != 0 {
  165. t.Fatalf("rows = %d, want 0 (borrado)", n)
  166. }
  167. // MAC desconocida: 404.
  168. rec = httptest.NewRecorder()
  169. r = httptest.NewRequest(http.MethodDelete, "/api/devices/11-22-33-44-55-66", nil)
  170. r.SetPathValue("mac", "11-22-33-44-55-66")
  171. s.handleDeviceDelete(rec, r)
  172. if rec.Code != http.StatusNotFound {
  173. t.Fatalf("status = %d, want 404", rec.Code)
  174. }
  175. }
  176. // #1151: link con validaciones (self 400, ok 200, ya enlazada 409, target
  177. // alias 409) y unlink (204 / 404).
  178. func TestDeviceLinkPutDelete(t *testing.T) {
  179. s := panelTestServer(t)
  180. do := func(method, mac, body string) *httptest.ResponseRecorder {
  181. r := httptest.NewRequest(method, "/api/devices/"+mac+"/link", strings.NewReader(body))
  182. r.SetPathValue("mac", mac)
  183. if body != "" {
  184. r.Header.Set("Content-Type", "application/json")
  185. }
  186. rec := httptest.NewRecorder()
  187. if method == http.MethodPut {
  188. s.handleDeviceLinkPut(rec, r)
  189. } else {
  190. s.handleDeviceLinkDelete(rec, r)
  191. }
  192. return rec
  193. }
  194. // self-link: 400
  195. if rec := do(http.MethodPut, "AA:AA:AA:00:00:01", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusBadRequest {
  196. t.Fatalf("self link = %d, want 400", rec.Code)
  197. }
  198. // ok: 200
  199. if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusOK {
  200. t.Fatalf("link = %d, want 200", rec.Code)
  201. }
  202. // ya enlazada: 409
  203. if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:09"}`); rec.Code != http.StatusConflict {
  204. t.Fatalf("relink = %d, want 409", rec.Code)
  205. }
  206. // target es a su vez alias: 409
  207. if rec := do(http.MethodPut, "AA:AA:AA:00:00:03", `{"target":"AA:AA:AA:00:00:02"}`); rec.Code != http.StatusConflict {
  208. t.Fatalf("target alias = %d, want 409", rec.Code)
  209. }
  210. // unlink: 204 y 404
  211. if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNoContent {
  212. t.Fatalf("unlink = %d, want 204", rec.Code)
  213. }
  214. if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNotFound {
  215. t.Fatalf("unlink de nuevo = %d, want 404", rec.Code)
  216. }
  217. }