scheduler1066_test.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. // scheduler1066_test.go — #1066: programación "auto" (diaria a la hora de
  2. // menos tráfico del histórico propio), hora por defecto 03:00 y picker de
  3. // hora valle sobre la tabla metrics (misma BD que el scheduler).
  4. package speedtest
  5. import (
  6. "testing"
  7. "time"
  8. )
  9. // seedMetrics inserta filas en la tabla metrics del scheduler (ts epoch ms).
  10. func seedMetrics(t *testing.T, sched *Scheduler, rows [][3]int64) {
  11. t.Helper()
  12. for _, r := range rows {
  13. if _, err := sched.db.Exec(
  14. "INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES ('rt1', ?, 0, 0, 0, 0, ?, ?)",
  15. r[0], r[1], r[2]); err != nil {
  16. t.Fatalf("seed metrics: %v", err)
  17. }
  18. }
  19. }
  20. // atLocal construye el ts epoch ms de una fecha en la zona local del test.
  21. func atLocal(y int, m time.Month, day, h, min int) int64 {
  22. return time.Date(y, m, day, h, min, 0, 0, time.Local).UnixMilli()
  23. }
  24. func TestDefaultSchedTime0300(t *testing.T) {
  25. if DefaultSchedTime != "03:00" {
  26. t.Fatalf("DefaultSchedTime = %q, want 03:00", DefaultSchedTime)
  27. }
  28. // LoadSettings con kv vacío debe traer la hora por defecto nueva (era 01:00).
  29. _, sched := openStore(t)
  30. if got := sched.LoadSettings().Time; got != "03:00" {
  31. t.Fatalf("LoadSettings().Time = %q, want 03:00", got)
  32. }
  33. }
  34. func TestQuietHourPicksArgmin(t *testing.T) {
  35. _, sched := openStore(t)
  36. // Junio (sin DST en Europa): 7 días con tráfico alto de 12:00 a 14:00
  37. // y un valle claro a las 04:00. El picker debe elegir el valle.
  38. now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.Local)
  39. sched.now = func() time.Time { return now }
  40. var rows [][3]int64
  41. for d := 0; d < 7; d++ {
  42. day := now.AddDate(0, 0, -d)
  43. y, m, dd := day.Date()
  44. for _, h := range []int{12, 13, 14} {
  45. rows = append(rows, [3]int64{atLocal(y, m, dd, h, 0), 80_000_000, 20_000_000})
  46. }
  47. rows = append(rows, [3]int64{atLocal(y, m, dd, 4, 0), 100_000, 50_000})
  48. rows = append(rows, [3]int64{atLocal(y, m, dd, 22, 0), 30_000_000, 5_000_000})
  49. }
  50. seedMetrics(t, sched, rows)
  51. if got := sched.quietHour(now); got != 4 {
  52. t.Fatalf("quietHour = %d, want 4 (el valle del histórico)", got)
  53. }
  54. // resolveAutoTime expone la hora elegida en formato HH:00 para Status.
  55. if got := sched.resolveAutoTime(); got != "04:00" {
  56. t.Fatalf("resolveAutoTime = %q, want 04:00", got)
  57. }
  58. }
  59. func TestQuietHourFallbackSinDatos(t *testing.T) {
  60. _, sched := openStore(t)
  61. now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.Local)
  62. if got := sched.quietHour(now); got != defaultQuietHour {
  63. t.Fatalf("quietHour sin datos = %d, want %d (fallback)", got, defaultQuietHour)
  64. }
  65. // Datos fuera de la ventana de 7 días tampoco sirven.
  66. _, sched2 := openStore(t)
  67. seedMetrics(t, sched2, [][3]int64{{atLocal(2026, 5, 1, 4, 0), 1000, 1000}})
  68. if got := sched2.quietHour(now); got != defaultQuietHour {
  69. t.Fatalf("quietHour con datos antiguos = %d, want %d (fallback)", got, defaultQuietHour)
  70. }
  71. }
  72. func TestSaveSettingsAutoRoundtrip(t *testing.T) {
  73. _, sched := openStore(t)
  74. if err := sched.SaveSettings(Settings{Enabled: true, ScheduleKind: "auto"}); err != nil {
  75. t.Fatalf("auto debe aceptarse sin day/time: %v", err)
  76. }
  77. if got := sched.LoadSettings().ScheduleKind; got != "auto" {
  78. t.Fatalf("roundtrip scheduleKind = %q, want auto", got)
  79. }
  80. err := sched.SaveSettings(Settings{Enabled: true, ScheduleKind: "diario"})
  81. if err == nil {
  82. t.Fatal("scheduleKind inválido debe rechazarse")
  83. }
  84. }
  85. func TestTestDueAutoDiario(t *testing.T) {
  86. st := Settings{Enabled: true, ScheduleKind: "auto", Time: "04:00"}
  87. at := func(h, m int) time.Time { return time.Date(2026, 6, 15, h, m, 0, 0, time.Local) }
  88. cases := []struct {
  89. name string
  90. now time.Time
  91. last *Result
  92. want bool
  93. }{
  94. {"05:00 sin histórico", at(5, 0), nil, true},
  95. {"05:00 con run de hoy 04:30", at(5, 0), &Result{TS: at(4, 30)}, false},
  96. {"03:59 (antes de la hora)", at(3, 59), nil, false},
  97. {"04:00 en punto", at(4, 0), nil, true},
  98. {"día siguiente con run de ayer", at(5, 0).AddDate(0, 0, 1), &Result{TS: at(4, 30)}, true},
  99. }
  100. for _, tc := range cases {
  101. t.Run(tc.name, func(t *testing.T) {
  102. if got := testDue(st, tc.last, tc.now); got != tc.want {
  103. t.Fatalf("testDue = %v, want %v", got, tc.want)
  104. }
  105. })
  106. }
  107. // Time vacío cae al default (03:00).
  108. stEmpty := Settings{Enabled: true, ScheduleKind: "auto"}
  109. if !testDue(stEmpty, nil, at(3, 30)) {
  110. t.Fatal("auto sin Time debe usar el default 03:00")
  111. }
  112. }
  113. func TestStatusAutoExponeHoraElegida(t *testing.T) {
  114. _, sched := openStore(t)
  115. // 02:00 local: antes del slot elegido (04:00), así nextRun cae hoy a esa
  116. // hora en vez de al clamp genérico de Status.
  117. now := time.Date(2026, 6, 15, 2, 0, 0, 0, time.Local)
  118. sched.now = func() time.Time { return now }
  119. var rows [][3]int64
  120. for d := 0; d < 7; d++ {
  121. day := now.AddDate(0, 0, -d)
  122. y, m, dd := day.Date()
  123. rows = append(rows, [3]int64{atLocal(y, m, dd, 12, 0), 80_000_000, 20_000_000})
  124. rows = append(rows, [3]int64{atLocal(y, m, dd, 4, 0), 100_000, 50_000})
  125. }
  126. seedMetrics(t, sched, rows)
  127. if err := sched.SaveSettings(Settings{Enabled: true, ScheduleKind: "auto"}); err != nil {
  128. t.Fatalf("save auto: %v", err)
  129. }
  130. st := sched.Status()
  131. if st.AutoTime != "04:00" {
  132. t.Fatalf("Status.AutoTime = %q, want 04:00", st.AutoTime)
  133. }
  134. if st.NextRun == nil {
  135. t.Fatal("Status.NextRun no debe ser nil con auto activado")
  136. }
  137. next := time.UnixMilli(*st.NextRun).In(time.Local)
  138. if next.Hour() != 4 {
  139. t.Fatalf("nextRun debe caer a las 04:xx local, cayó a las %02d:%02d", next.Hour(), next.Minute())
  140. }
  141. }