reason_test.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. package rintegration
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/gnacho/netpulse/server-go/internal/db"
  11. )
  12. func TestClassifyPollError(t *testing.T) {
  13. cases := []struct {
  14. msg string
  15. want string
  16. }{
  17. {"", ""},
  18. // REST 401 y login fallido por la API binaria.
  19. {`routeros: GET /rest/system/resource: 401 Unauthorized: {"message":"bad username and password"}`, ReasonAuthFailed},
  20. {`routeros api: login: invalid user name or password`, ReasonAuthFailed},
  21. // Endpoint ausente: firmware sin REST (RouterOS 6 con solo www).
  22. {`routeros: GET /rest/system/resource: 404 Not Found: <html>`, ReasonAPINotFound},
  23. // Familia de conexión.
  24. {`routeros api: dial tcp 10.0.0.1:8728: connect: connection refused; rest: dial tcp: connection refused`, ReasonConnRefused},
  25. {`routeros: GET /rest/system/resource: context deadline exceeded (i/o timeout)`, ReasonConnRefused},
  26. // Cualquier otro error no vacío cae al genérico.
  27. {"routeros: no rows from /system/resource/print", ReasonError},
  28. }
  29. for _, c := range cases {
  30. if got := ClassifyPollError(c.msg); got != c.want {
  31. t.Errorf("ClassifyPollError(%q) = %q, want %q", c.msg, got, c.want)
  32. }
  33. }
  34. }
  35. // writeTestLog añade body al log del slug, igual que hace el Manager.
  36. func writeTestLog(t *testing.T, dir, slug, body string) {
  37. t.Helper()
  38. p := filepath.Join(dir, slug+".log")
  39. f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
  40. if err != nil {
  41. t.Fatalf("open log: %v", err)
  42. }
  43. if _, err := f.WriteString(body); err != nil {
  44. t.Fatalf("write log: %v", err)
  45. }
  46. if err := f.Close(); err != nil {
  47. t.Fatalf("close log: %v", err)
  48. }
  49. }
  50. func setTestLastPush(t *testing.T, d *sql.DB, slug string, sec int64) {
  51. t.Helper()
  52. _, err := d.Exec(
  53. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  54. "agent.last_push_ts."+slug, fmt.Sprintf("%d", sec),
  55. )
  56. if err != nil {
  57. t.Fatalf("setLastPush: %v", err)
  58. }
  59. }
  60. func TestLastPollError(t *testing.T) {
  61. dir := t.TempDir()
  62. m := NewManager(dir)
  63. // Sin log: vacío y sin error.
  64. if got := m.LastPollError("hex"); got != "" {
  65. t.Fatalf("empty log: got %q", got)
  66. }
  67. // Log con una línea limpia y la última de fallo con escapes de slog.
  68. writeTestLog(t, dir, "hex", strings.Join([]string{
  69. `2026-10-31T09:00:00Z INF routeros-pusher: pushed slug=hex`,
  70. `2026-10-31T09:01:00Z ERR routeros-pusher: collection failed err="routeros api: dial tcp: connection refused; rest: 401 Unauthorized"`,
  71. }, "\n")+"\n")
  72. got := m.LastPollError("hex")
  73. want := `routeros api: dial tcp: connection refused; rest: 401 Unauthorized`
  74. if got != want {
  75. t.Fatalf("LastPollError = %q, want %q", got, want)
  76. }
  77. // Varias líneas de fallo: gana la ÚLTIMA.
  78. writeTestLog(t, dir, "hex", `2026-10-31T09:02:00Z ERR routeros-pusher: collection failed err="routeros: GET /rest/system/resource: 404 Not Found"`+"\n")
  79. if got := m.LastPollError("hex"); !strings.Contains(got, "404") {
  80. t.Fatalf("LastPollError = %q, want the latest 404 line", got)
  81. }
  82. // Escapes de slog dentro del valor (comillas y barra invertida).
  83. writeTestLog(t, dir, "esc", `2026-10-31T09:03:00Z ERR routeros-pusher: collection failed err="rest: bad reply \"x\" + \\ tail"`+"\n")
  84. if got := m.LastPollError("esc"); got != `rest: bad reply "x" + \ tail` {
  85. t.Fatalf("unescape: got %q", got)
  86. }
  87. }
  88. func TestStatusReasons(t *testing.T) {
  89. d, err := db.Open(t.TempDir())
  90. if err != nil {
  91. t.Fatalf("db.Open: %v", err)
  92. }
  93. t.Cleanup(func() { _ = d.Close() })
  94. st := NewStore(d.DB)
  95. dir := t.TempDir()
  96. m := NewManager(dir)
  97. // pusher parado: motivo propio, sin mirar el log.
  98. if err := st.Upsert(Row{Slug: "hex", Vendor: "routeros", IntervalS: 30, Enabled: true, State: "stopped"}); err != nil {
  99. t.Fatalf("Upsert: %v", err)
  100. }
  101. // integración deshabilitada: se omite.
  102. if err := st.Upsert(Row{Slug: "off", Vendor: "routeros", IntervalS: 30, Enabled: false, State: "running"}); err != nil {
  103. t.Fatalf("Upsert: %v", err)
  104. }
  105. // integración con push fresco: se omite aunque el log tenga fallos.
  106. if err := st.Upsert(Row{Slug: "fresh", Vendor: "routeros", IntervalS: 30, Enabled: true, State: "running"}); err != nil {
  107. t.Fatalf("Upsert: %v", err)
  108. }
  109. setTestLastPush(t, d.DB, "fresh", time.Now().Unix())
  110. writeTestLog(t, dir, "fresh", `2026-10-31T09:00:00Z ERR routeros-pusher: collection failed err="x: 401 Unauthorized"`+"\n")
  111. // integración stale con fallo de poll en el log: clasifica.
  112. if err := st.Upsert(Row{Slug: "hexbad", Vendor: "routeros", IntervalS: 30, Enabled: true, State: "running"}); err != nil {
  113. t.Fatalf("Upsert: %v", err)
  114. }
  115. setTestLastPush(t, d.DB, "hexbad", time.Now().Add(-time.Hour).Unix())
  116. writeTestLog(t, dir, "hexbad", `2026-10-31T09:00:00Z ERR routeros-pusher: collection failed err="routeros: GET /rest/system/resource: 401 Unauthorized"`+"\n")
  117. // integración stale sin log ni LastError: sin motivo (no está en el mapa).
  118. if err := st.Upsert(Row{Slug: "silent", Vendor: "routeros", IntervalS: 30, Enabled: true, State: "running"}); err != nil {
  119. t.Fatalf("Upsert: %v", err)
  120. }
  121. got := StatusReasons(d.DB, m)
  122. if got["hex"] != ReasonStopped {
  123. t.Errorf("hex: got %q, want %q", got["hex"], ReasonStopped)
  124. }
  125. if _, ok := got["off"]; ok {
  126. t.Errorf("disabled integration must be skipped, got %q", got["off"])
  127. }
  128. if _, ok := got["fresh"]; ok {
  129. t.Errorf("fresh integration must be skipped, got %q", got["fresh"])
  130. }
  131. if got["hexbad"] != ReasonAuthFailed {
  132. t.Errorf("hexbad: got %q, want %q", got["hexbad"], ReasonAuthFailed)
  133. }
  134. if _, ok := got["silent"]; ok {
  135. t.Errorf("silent stale integration must have no reason, got %q", got["silent"])
  136. }
  137. // nil-safety: sin db o sin manager no hay mapa.
  138. if StatusReasons(nil, m) != nil || StatusReasons(d.DB, nil) != nil {
  139. t.Error("nil db/manager must return nil map")
  140. }
  141. }