reports_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // reports_test.go — contrato de GET /api/reports/weekly: agregación por
  2. // router y semana ISO desde metrics_daily, validación de weeks y upPct.
  3. package httpapi_test
  4. import (
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "testing"
  9. )
  10. // insertDaily siembra un daily del router r para una fecha dada. nSamples es
  11. // el nº de muestras recolectadas (poll 5 s; día completo ≈ 17280 → 1440 min).
  12. func insertDaily(t *testing.T, ts *testServer, routerID, date string, nSamples int, lat sqlNull, rx, tx, cpu, ram float64) {
  13. t.Helper()
  14. var latV any
  15. if lat.valid {
  16. latV = lat.f
  17. }
  18. _, err := ts.db.Exec(
  19. "INSERT OR REPLACE INTO metrics_daily (router_id, date, n, cpu_avg, ram_avg, temp_avg, lat_avg, rx_avg, tx_avg, rx_total, tx_total, up_min, up_count) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
  20. routerID, date, nSamples, cpu, ram, 40, latV, rx, tx, rx*float64(nSamples), tx*float64(nSamples), 0, nSamples)
  21. if err != nil {
  22. t.Fatalf("insert daily %s/%s: %v", routerID, date, err)
  23. }
  24. }
  25. // sqlNull emula sql.NullFloat64 para el test (sin importar database/sql).
  26. type sqlNull struct {
  27. valid bool
  28. f float64
  29. }
  30. // weeklyReportEntry espeja la respuesta (solo los campos que usa el test).
  31. type weeklyReportEntry struct {
  32. RouterID string `json:"routerId"`
  33. Week string `json:"week"`
  34. Days int `json:"days"`
  35. UpMin int64 `json:"upMin"`
  36. UpPct float64 `json:"upPct"`
  37. LatAvg *float64 `json:"latAvg"`
  38. }
  39. func getWeekly(t *testing.T, ts *testServer, weeks string) (int, []weeklyReportEntry) {
  40. t.Helper()
  41. _, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
  42. url := ts.URL + "/api/reports/weekly"
  43. if weeks != "" {
  44. url += "?weeks=" + weeks
  45. }
  46. req, _ := http.NewRequest("GET", url, nil)
  47. req.Header.Set("Cookie", "session="+cookie)
  48. res, err := http.DefaultClient.Do(req)
  49. if err != nil {
  50. t.Fatalf("GET weekly: %v", err)
  51. }
  52. defer res.Body.Close()
  53. body, _ := io.ReadAll(res.Body)
  54. var env struct {
  55. Items []weeklyReportEntry `json:"items"`
  56. }
  57. if res.StatusCode == http.StatusOK {
  58. if err := json.Unmarshal(body, &env); err != nil {
  59. t.Fatalf("decode: %v (%s)", err, body)
  60. }
  61. }
  62. return res.StatusCode, env.Items
  63. }
  64. func TestWeeklyReportAgrupaPorRouterYSemana(t *testing.T) {
  65. ts := makeTestServer(t)
  66. // Dos routers en la misma semana ISO 2026-W32 (2026-08-03..09).
  67. // Día completo = 17280 muestras = 1440 min. latAvg null en prod real.
  68. insertDaily(t, ts, "gw", "2026-08-03", 17280, sqlNull{true, 1.2}, 1e8, 5e7, 20, 60)
  69. insertDaily(t, ts, "gw", "2026-08-04", 17280, sqlNull{true, 1.4}, 1e8, 5e7, 22, 61)
  70. insertDaily(t, ts, "ap2", "2026-08-03", 8640, sqlNull{false, 0}, 1e7, 1e7, 10, 40) // medio día, sin latencia
  71. // Otra semana distinta (2026-W31 = 2026-07-27..08-02) para el mismo router.
  72. insertDaily(t, ts, "gw", "2026-07-27", 17280, sqlNull{true, 1.0}, 9e7, 4e7, 19, 59)
  73. status, items := getWeekly(t, ts, "4")
  74. if status != http.StatusOK {
  75. t.Fatalf("status %d, esperaba 200", status)
  76. }
  77. // 3 filas: gw en 2 semanas + ap2 en 1.
  78. if len(items) != 3 {
  79. t.Fatalf("items = %d, esperaba 3: %+v", len(items), items)
  80. }
  81. // La semana más reciente primero (ORDER BY week DESC).
  82. if items[0].Week != "2026-W32" {
  83. t.Fatalf("items[0].week = %q, esperaba 2026-W32", items[0].Week)
  84. }
  85. if items[0].RouterID != "ap2" { // orden alfabético dentro de la semana: ap2 < gw
  86. t.Fatalf("items[0].routerId = %q, esperaba ap2", items[0].RouterID)
  87. }
  88. // gw en W32: 2 días completos = 2*1440 = 2880 min, 100%.
  89. var gwW32, gwW31, ap2W32 *weeklyReportEntry
  90. for i := range items {
  91. switch {
  92. case items[i].RouterID == "gw" && items[i].Week == "2026-W32":
  93. gwW32 = &items[i]
  94. case items[i].RouterID == "gw" && items[i].Week == "2026-W31":
  95. gwW31 = &items[i]
  96. case items[i].RouterID == "ap2" && items[i].Week == "2026-W32":
  97. ap2W32 = &items[i]
  98. }
  99. }
  100. if gwW32 == nil || gwW31 == nil || ap2W32 == nil {
  101. t.Fatalf("faltan filas esperadas: gwW32=%v gwW31=%v ap2W32=%v", gwW32, gwW31, ap2W32)
  102. }
  103. if gwW32.Days != 2 || gwW32.UpMin != 2880 {
  104. t.Fatalf("gw W32: days=%d upMin=%d, esperaba 2/2880", gwW32.Days, gwW32.UpMin)
  105. }
  106. if gwW32.UpPct < 99.9 || gwW32.UpPct > 100.1 {
  107. t.Fatalf("gw W32 upPct=%v, esperaba ~100", gwW32.UpPct)
  108. }
  109. if gwW32.LatAvg == nil || *gwW32.LatAvg < 1.29 || *gwW32.LatAvg > 1.31 {
  110. t.Fatalf("gw W32 latAvg=%v, esperaba ~1.3 (media de 1.2/1.4)", gwW32.LatAvg)
  111. }
  112. // ap2: medio día = 720 min sobre 1 día → 50%; latencia null (sin datos).
  113. if ap2W32.Days != 1 || ap2W32.UpMin != 720 {
  114. t.Fatalf("ap2 W32: days=%d upMin=%d, esperaba 1/720", ap2W32.Days, ap2W32.UpMin)
  115. }
  116. if ap2W32.UpPct < 49.9 || ap2W32.UpPct > 50.1 {
  117. t.Fatalf("ap2 W32 upPct=%v, esperaba ~50 (medio día: 720 de 1440 min)", ap2W32.UpPct)
  118. }
  119. if ap2W32.LatAvg != nil {
  120. t.Fatalf("ap2 W32 latAvg=%v, esperaba null (sin datos de latencia)", *ap2W32.LatAvg)
  121. }
  122. if gwW31.Days != 1 || gwW31.UpMin != 1440 {
  123. t.Fatalf("gw W31: days=%d upMin=%d, esperaba 1/1440", gwW31.Days, gwW31.UpMin)
  124. }
  125. }
  126. // TestWeeklyReportUpPctClamp: un bucket sobre-poblado (más muestras que
  127. // minutos del día) no puede superar el 100% de disponibilidad (issue #207).
  128. // El weekly clampa igual que availability: divergía porque availability sí
  129. // clavaba y weekly no.
  130. func TestWeeklyReportUpPctClamp(t *testing.T) {
  131. ts := makeTestServer(t)
  132. // Día completo = 17280 muestras = 1440 min. El doble (34560) da
  133. // upMin = 2880 sobre 1440 min → 200% sin el clamp.
  134. insertDaily(t, ts, "gw", "2026-08-03", 34560, sqlNull{false, 0}, 0, 0, 20, 60)
  135. status, items := getWeekly(t, ts, "4")
  136. if status != http.StatusOK {
  137. t.Fatalf("status %d, esperaba 200", status)
  138. }
  139. if len(items) != 1 {
  140. t.Fatalf("items = %d, esperaba 1 (un bucket): %+v", len(items), items)
  141. }
  142. if items[0].UpPct != 100 {
  143. t.Fatalf("bucket sobre-poblado upPct=%v, esperaba 100 (clamp)", items[0].UpPct)
  144. }
  145. }
  146. func TestWeeklyReportValidaWeeks(t *testing.T) {
  147. ts := makeTestServer(t)
  148. for _, bad := range []string{"0", "53", "abc", "-1"} {
  149. status, _ := getWeekly(t, ts, bad)
  150. if status != http.StatusBadRequest {
  151. t.Fatalf("weeks=%q → status %d, esperaba 400", bad, status)
  152. }
  153. }
  154. // Por defecto (sin query) → 200.
  155. status, _ := getWeekly(t, ts, "")
  156. if status != http.StatusOK {
  157. t.Fatalf("sin weeks → status %d, esperaba 200", status)
  158. }
  159. }
  160. func TestWeeklyReportRequiereSesion(t *testing.T) {
  161. ts := makeTestServer(t)
  162. res, err := http.Get(ts.URL + "/api/reports/weekly")
  163. if err != nil {
  164. t.Fatalf("GET: %v", err)
  165. }
  166. defer res.Body.Close()
  167. io.Copy(io.Discard, res.Body)
  168. if res.StatusCode != http.StatusUnauthorized {
  169. t.Fatalf("status %d, esperaba 401", res.StatusCode)
  170. }
  171. }