presence_api_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. // presence_api_test.go — contrato de los endpoints de presencia (#771).
  2. package httpapi_test
  3. import (
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "testing"
  8. "time"
  9. "github.com/gnacho/netpulse/server-go/internal/deviceevents"
  10. "github.com/gnacho/netpulse/server-go/internal/httpapi"
  11. )
  12. // TestDevicePresence devuelve los tramos fusionados de una MAC con eventos
  13. // reales en BD: intervalo cerrado por offline + tramo abierto actual.
  14. func TestDevicePresence(t *testing.T) {
  15. ts := makeDeviceActionsTestServer(t, nil)
  16. defer ts.Server.Close()
  17. mac := "AA:BB:CC:DD:EE:07"
  18. base := time.Now().Add(-2 * time.Hour).UnixMilli()
  19. if err := deviceevents.Insert(ts.db.DB, deviceevents.Event{TsMs: base, MAC: mac, RouterID: "gw", State: deviceevents.StateOnline}); err != nil {
  20. t.Fatalf("insert online: %v", err)
  21. }
  22. if err := deviceevents.Insert(ts.db.DB, deviceevents.Event{TsMs: base + 3600_000, MAC: mac, RouterID: "gw", State: deviceevents.StateOffline}); err != nil {
  23. t.Fatalf("insert offline: %v", err)
  24. }
  25. if err := deviceevents.Insert(ts.db.DB, deviceevents.Event{TsMs: base + 3700_000, MAC: mac, RouterID: "gw", State: deviceevents.StateOnline}); err != nil {
  26. t.Fatalf("insert online 2: %v", err)
  27. }
  28. resp := deviceReq(t, "GET", ts.Server.URL, "/api/devices/"+mac+"/presence?days=7", ts.cookie, "")
  29. defer resp.Body.Close()
  30. if resp.StatusCode != 200 {
  31. t.Fatalf("GET presence: %d, want 200", resp.StatusCode)
  32. }
  33. var body struct {
  34. MAC string `json:"mac"`
  35. Intervals []struct {
  36. RouterID string `json:"routerId"`
  37. StartMs int64 `json:"startMs"`
  38. EndMs *int64 `json:"endMs"`
  39. } `json:"intervals"`
  40. Events []struct {
  41. State string `json:"state"`
  42. } `json:"events"`
  43. Connects24h int `json:"connects24h"`
  44. }
  45. if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
  46. t.Fatalf("decode: %v", err)
  47. }
  48. if len(body.Intervals) != 2 {
  49. t.Fatalf("intervals = %d, want 2 (cerrado + abierto)", len(body.Intervals))
  50. }
  51. if body.Intervals[0].EndMs == nil {
  52. t.Fatal("el primer tramo debe estar cerrado por el offline")
  53. }
  54. if body.Intervals[1].EndMs != nil {
  55. t.Fatal("el segundo tramo debe quedar abierto (endMs null)")
  56. }
  57. if len(body.Events) != 3 {
  58. t.Fatalf("events = %d, want 3", len(body.Events))
  59. }
  60. // MAC inválida → 400.
  61. resp2 := deviceReq(t, "GET", ts.Server.URL, "/api/devices/xx/presence", ts.cookie, "")
  62. defer resp2.Body.Close()
  63. io.Copy(io.Discard, resp2.Body)
  64. if resp2.StatusCode != http.StatusBadRequest {
  65. t.Fatalf("GET presence MAC inválida: %d, want 400", resp2.StatusCode)
  66. }
  67. }
  68. // TestPresenceSettingsRoundtrip: PUT retención → GET la devuelve; fuera de
  69. // rango → 400.
  70. func TestPresenceSettingsRoundtrip(t *testing.T) {
  71. ts := makeDeviceActionsTestServer(t, nil)
  72. defer ts.Server.Close()
  73. resp := deviceReq(t, "PUT", ts.Server.URL, "/api/settings/presence", ts.cookie, `{"retention_days":14}`)
  74. defer resp.Body.Close()
  75. io.Copy(io.Discard, resp.Body)
  76. if resp.StatusCode != 200 {
  77. t.Fatalf("PUT presence settings: %d, want 200", resp.StatusCode)
  78. }
  79. resp2 := deviceReq(t, "GET", ts.Server.URL, "/api/settings/presence", ts.cookie, "")
  80. defer resp2.Body.Close()
  81. var body struct {
  82. RetentionDays int `json:"retention_days"`
  83. }
  84. if err := json.NewDecoder(resp2.Body).Decode(&body); err != nil {
  85. t.Fatalf("decode: %v", err)
  86. }
  87. if body.RetentionDays != 14 {
  88. t.Fatalf("retention_days = %d, want 14", body.RetentionDays)
  89. }
  90. resp3 := deviceReq(t, "PUT", ts.Server.URL, "/api/settings/presence", ts.cookie, `{"retention_days":999}`)
  91. defer resp3.Body.Close()
  92. io.Copy(io.Discard, resp3.Body)
  93. if resp3.StatusCode != http.StatusBadRequest {
  94. t.Fatalf("PUT retención inválida: %d, want 400", resp3.StatusCode)
  95. }
  96. }
  97. // TestHistoryLimitRoundtrip (#975): el interruptor maestro de la poda nace
  98. // ON (ausente = limitar), PUT false lo persiste y GET lo devuelve.
  99. func TestHistoryLimitRoundtrip(t *testing.T) {
  100. ts := makeDeviceActionsTestServer(t, nil)
  101. defer ts.Server.Close()
  102. get := func() bool {
  103. resp := deviceReq(t, "GET", ts.Server.URL, "/api/settings/history-limit", ts.cookie, "")
  104. defer resp.Body.Close()
  105. var body struct {
  106. Enabled bool `json:"enabled"`
  107. }
  108. if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
  109. t.Fatalf("decode: %v", err)
  110. }
  111. return body.Enabled
  112. }
  113. if !get() {
  114. t.Fatal("history-limit debe nacer activado (default ON)")
  115. }
  116. resp := deviceReq(t, "PUT", ts.Server.URL, "/api/settings/history-limit", ts.cookie, `{"enabled":false}`)
  117. defer resp.Body.Close()
  118. io.Copy(io.Discard, resp.Body)
  119. if resp.StatusCode != 200 {
  120. t.Fatalf("PUT history-limit: %d, want 200", resp.StatusCode)
  121. }
  122. if get() {
  123. t.Fatal("history-limit debe quedar desactivado tras PUT enabled=false")
  124. }
  125. if httpapi.HistoryLimitEnabled(ts.db.DB) {
  126. t.Fatal("HistoryLimitEnabled debe ser false con kv history.limit_enabled=0")
  127. }
  128. resp2 := deviceReq(t, "PUT", ts.Server.URL, "/api/settings/history-limit", ts.cookie, `{"enabled":true}`)
  129. defer resp2.Body.Close()
  130. io.Copy(io.Discard, resp2.Body)
  131. if resp2.StatusCode != 200 {
  132. t.Fatalf("PUT history-limit ON: %d, want 200", resp2.StatusCode)
  133. }
  134. if !get() {
  135. t.Fatal("history-limit debe reactivarse tras PUT enabled=true")
  136. }
  137. }
  138. // TestPresenceRoaming lista las MACs con más de un connect en 24 h.
  139. func TestPresenceRoaming(t *testing.T) {
  140. ts := makeDeviceActionsTestServer(t, nil)
  141. defer ts.Server.Close()
  142. now := time.Now().UnixMilli()
  143. for i := 0; i < 3; i++ {
  144. if _, err := ts.db.Exec(`INSERT INTO roam_events (ts_ms, router_id, type, mac, content_hash)
  145. VALUES (?, 'gw', 'connected', 'AA:BB:CC:DD:EE:08', ?)`, now-int64(i)*3600_000, "c8-"+string(rune('0'+i))); err != nil {
  146. t.Fatalf("insert roam: %v", err)
  147. }
  148. }
  149. resp := deviceReq(t, "GET", ts.Server.URL, "/api/presence/roaming", ts.cookie, "")
  150. defer resp.Body.Close()
  151. if resp.StatusCode != 200 {
  152. t.Fatalf("GET roaming: %d, want 200", resp.StatusCode)
  153. }
  154. var body struct {
  155. Items []struct {
  156. MAC string `json:"mac"`
  157. Connects int `json:"connects"`
  158. } `json:"items"`
  159. }
  160. if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
  161. t.Fatalf("decode: %v", err)
  162. }
  163. if len(body.Items) != 1 || body.Items[0].Connects != 3 {
  164. t.Fatalf("roaming items = %+v, want 1 con 3", body.Items)
  165. }
  166. }