main_test.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // main_test.go — primeros tests del collector (contrato C4, Fase 2).
  2. package main
  3. import (
  4. "context"
  5. "reflect"
  6. "strings"
  7. "testing"
  8. "time"
  9. )
  10. // Bug C4.3: colisión de slug → sufijo -2, -3… (nunca ignorar el segundo target).
  11. func TestDedupeSlugs(t *testing.T) {
  12. targets := []Target{
  13. {Name: slug("Router A"), Addr: "10.0.0.1:22"}, // "router-a"
  14. {Name: slug("router_a"), Addr: "10.0.0.2:22"}, // colisiona: "router-a"
  15. {Name: slug("ROUTER A"), Addr: "10.0.0.3:22"}, // colisiona otra vez
  16. {Name: slug("Router A 2"), Addr: "10.0.0.4:22"}, // "router-a-2": colisiona con el sufijo
  17. {Name: slug("ap"), Addr: "10.0.0.5:22"},
  18. }
  19. got := dedupeSlugs(targets)
  20. var names []string
  21. for _, tg := range got {
  22. names = append(names, tg.Name)
  23. }
  24. want := []string{"router-a", "router-a-2", "router-a-3", "router-a-2-2", "ap"}
  25. if !reflect.DeepEqual(names, want) {
  26. t.Errorf("slugs = %v, quiero %v", names, want)
  27. }
  28. // Las direcciones se conservan (no se pierde ningún target).
  29. for i, tg := range got {
  30. if tg.Addr != targets[i].Addr {
  31. t.Errorf("target[%d].Addr = %s, quiero %s", i, tg.Addr, targets[i].Addr)
  32. }
  33. }
  34. }
  35. // spyReconcile monta callbacks que simulan el supervisor real sin DB ni red.
  36. type spyReconcile struct {
  37. started []Target
  38. stopped []string
  39. canceled []string
  40. }
  41. func (s *spyReconcile) children(entries ...Target) map[string]childProc {
  42. m := map[string]childProc{}
  43. for _, e := range entries {
  44. name := e.Name
  45. m[name] = childProc{
  46. addr: e.Addr,
  47. cancel: func() { s.canceled = append(s.canceled, name) },
  48. }
  49. }
  50. return m
  51. }
  52. func (s *spyReconcile) onStart(children map[string]childProc) func(Target) {
  53. return func(t Target) {
  54. s.started = append(s.started, t)
  55. children[t.Name] = childProc{addr: t.Addr, cancel: func() {}}
  56. }
  57. }
  58. func (s *spyReconcile) onStop() func(string) {
  59. return func(name string) { s.stopped = append(s.stopped, name) }
  60. }
  61. // Bug C4.2: un router que cambia de host reinicia su sonda (cancel + start).
  62. func TestReconcileHostChange(t *testing.T) {
  63. s := &spyReconcile{}
  64. children := s.children(Target{Name: "gw", Addr: "192.168.1.1:22"})
  65. targets := []Target{{Name: "gw", Addr: "192.168.1.254:22"}} // mismo nombre, host nuevo
  66. reconcileTargets(children, targets, s.onStart(children), s.onStop())
  67. if !reflect.DeepEqual(s.canceled, []string{"gw"}) {
  68. t.Errorf("canceladas = %v, quiero [gw]", s.canceled)
  69. }
  70. if len(s.started) != 1 || s.started[0].Addr != "192.168.1.254:22" {
  71. t.Errorf("arrancadas = %+v, quiero gw con el host nuevo", s.started)
  72. }
  73. if children["gw"].addr != "192.168.1.254:22" {
  74. t.Errorf("children[gw].addr = %s, quiero el host nuevo", children["gw"].addr)
  75. }
  76. if len(s.stopped) != 0 {
  77. t.Errorf("eliminadas = %v, quiero ninguna (el target sigue existiendo)", s.stopped)
  78. }
  79. }
  80. // Sin cambios de host ni de lista: no se toca ninguna sonda.
  81. func TestReconcileNoChanges(t *testing.T) {
  82. s := &spyReconcile{}
  83. children := s.children(Target{Name: "gw", Addr: "192.168.1.1:22"})
  84. reconcileTargets(children, []Target{{Name: "gw", Addr: "192.168.1.1:22"}}, s.onStart(children), s.onStop())
  85. if len(s.started)+len(s.stopped)+len(s.canceled) != 0 {
  86. t.Errorf("sin cambios no debe haber acciones: %+v", s)
  87. }
  88. }
  89. // Bug C4.4: al eliminar un target se para la sonda y se purga `last` (vía onStop).
  90. func TestReconcileRemovePurges(t *testing.T) {
  91. s := &spyReconcile{}
  92. children := s.children(
  93. Target{Name: "gw", Addr: "192.168.1.1:22"},
  94. Target{Name: "ap", Addr: "192.168.1.2:22"},
  95. )
  96. last := map[string]probeResult{"gw": {OK: true}, "ap": {OK: true}}
  97. onStop := func(name string) {
  98. delete(last, name) // como hace el onStop real de main
  99. s.onStop()(name)
  100. }
  101. reconcileTargets(children, []Target{{Name: "gw", Addr: "192.168.1.1:22"}}, s.onStart(children), onStop)
  102. if !reflect.DeepEqual(s.canceled, []string{"ap"}) {
  103. t.Errorf("canceladas = %v, quiero [ap]", s.canceled)
  104. }
  105. if !reflect.DeepEqual(s.stopped, []string{"ap"}) {
  106. t.Errorf("onStop = %v, quiero [ap]", s.stopped)
  107. }
  108. if _, ok := children["ap"]; ok {
  109. t.Error("children aún contiene ap")
  110. }
  111. if _, ok := last["ap"]; ok {
  112. t.Error("last aún contiene ap (stale en /healthz y state.json)")
  113. }
  114. if _, ok := last["gw"]; !ok {
  115. t.Error("last perdió gw, que sigue activo")
  116. }
  117. }
  118. // F-23: antes de purgar `last` hay que esperar a que la sonda cancelada
  119. // termine. Si no, la sonda puede resucitar el target eliminado.
  120. func TestReconcileWaitsForProbeBeforeStop(t *testing.T) {
  121. s := &spyReconcile{}
  122. done := make(chan struct{})
  123. children := map[string]childProc{
  124. "ap": {addr: "192.168.1.2:22", cancel: func() {}, done: done},
  125. }
  126. returned := make(chan struct{})
  127. go func() {
  128. reconcileTargets(children, nil, s.onStart(children), s.onStop())
  129. close(returned)
  130. }()
  131. select {
  132. case <-returned:
  133. t.Fatal("reconcileTargets terminó antes de que la sonda acabara")
  134. case <-time.After(50 * time.Millisecond):
  135. }
  136. if len(s.stopped) != 0 {
  137. t.Fatalf("onStop se llamó con la sonda viva: %v", s.stopped)
  138. }
  139. close(done)
  140. select {
  141. case <-returned:
  142. case <-time.After(2 * time.Second):
  143. t.Fatal("reconcileTargets no terminó tras acabar la sonda")
  144. }
  145. if !reflect.DeepEqual(s.stopped, []string{"ap"}) {
  146. t.Errorf("onStop = %v, quiero [ap]", s.stopped)
  147. }
  148. }
  149. // F-23: al cambiar de host, la sonda vieja debe terminar antes de arrancar la
  150. // nueva, para que no escriba una muestra del endpoint anterior.
  151. func TestReconcileWaitsForOldProbeBeforeStart(t *testing.T) {
  152. s := &spyReconcile{}
  153. done := make(chan struct{})
  154. children := map[string]childProc{
  155. "gw": {addr: "192.168.1.1:22", cancel: func() {}, done: done},
  156. }
  157. returned := make(chan struct{})
  158. go func() {
  159. reconcileTargets(children, []Target{{Name: "gw", Addr: "192.168.1.254:22"}}, s.onStart(children), s.onStop())
  160. close(returned)
  161. }()
  162. select {
  163. case <-returned:
  164. t.Fatal("reconcileTargets arrancó la sonda nueva antes de acabar la vieja")
  165. case <-time.After(50 * time.Millisecond):
  166. }
  167. if len(s.started) != 0 {
  168. t.Fatalf("onStart se llamó con la sonda vieja viva: %+v", s.started)
  169. }
  170. close(done)
  171. select {
  172. case <-returned:
  173. case <-time.After(2 * time.Second):
  174. t.Fatal("reconcileTargets no terminó tras acabar la sonda vieja")
  175. }
  176. if len(s.started) != 1 || s.started[0].Addr != "192.168.1.254:22" {
  177. t.Errorf("arrancadas = %+v, quiero gw con el host nuevo", s.started)
  178. }
  179. }
  180. // El slug base no cambia con la dedup (regresión del helper slug()).
  181. func TestSlug(t *testing.T) {
  182. cases := map[string]string{
  183. "Router A": "router-a",
  184. "AP_Patio 2": "ap-patio-2",
  185. "gw.local!": "gwlocal",
  186. "Ya-Slug-Ok-1": "yaslugok1", // los guiones se eliminan (comportamiento actual)
  187. }
  188. for in, want := range cases {
  189. if got := slug(in); got != want {
  190. t.Errorf("slug(%q) = %q, quiero %q", in, got, want)
  191. }
  192. }
  193. }
  194. // EXTRA_TARGETS pasa por slug + dedup igual que los routers de la DB.
  195. func TestExtraTargetsDedup(t *testing.T) {
  196. var targets []Target
  197. for _, extra := range []string{"internet=1.1.1.1:443", "Internet=8.8.8.8:443"} {
  198. name, addr, _ := strings.Cut(extra, "=")
  199. targets = append(targets, Target{Name: slug(name), Addr: addr})
  200. }
  201. got := dedupeSlugs(targets)
  202. if got[0].Name != "internet" || got[1].Name != "internet-2" {
  203. t.Errorf("extras dedup = %v, quiero [internet internet-2]", got)
  204. }
  205. }
  206. // smoke: reconcileTargets arranca targets nuevos con ctx real cancelable.
  207. func TestReconcileStartsNew(t *testing.T) {
  208. children := map[string]childProc{}
  209. var started []string
  210. onStart := func(tg Target) {
  211. started = append(started, tg.Name)
  212. _, cancel := context.WithCancel(context.Background())
  213. children[tg.Name] = childProc{cancel: cancel, addr: tg.Addr}
  214. }
  215. reconcileTargets(children, []Target{{Name: "a", Addr: "1.1.1.1:22"}, {Name: "b", Addr: "2.2.2.2:22"}}, onStart, func(string) {})
  216. if len(started) != 2 || len(children) != 2 {
  217. t.Errorf("started=%v children=%d, quiero 2 y 2", started, len(children))
  218. }
  219. }
  220. // #1893: la cadencia y el puerto de la sonda son configurables, porque cada
  221. // sonda abre una conexión TCP que el router registra en su log.
  222. func TestApplyProbeEnv(t *testing.T) {
  223. restore := func() {
  224. probeInterval = 5 * time.Second
  225. probePort = "22"
  226. }
  227. defer restore()
  228. for _, tc := range []struct {
  229. name string
  230. vars map[string]string
  231. interval time.Duration
  232. port string
  233. wantErr bool
  234. }{
  235. {name: "sin entorno mantiene los defaults", vars: map[string]string{}, interval: 5 * time.Second, port: "22"},
  236. {name: "cadencia y puerto", vars: map[string]string{"PROBE_INTERVAL": "30s", "PROBE_PORT": "80"}, interval: 30 * time.Second, port: "80"},
  237. {name: "cadencia con espacios", vars: map[string]string{"PROBE_INTERVAL": " 1m "}, interval: time.Minute, port: "22"},
  238. {name: "cadencia invalida", vars: map[string]string{"PROBE_INTERVAL": "pronto"}, wantErr: true},
  239. {name: "cadencia demasiado corta", vars: map[string]string{"PROBE_INTERVAL": "100ms"}, wantErr: true},
  240. {name: "cadencia demasiado larga", vars: map[string]string{"PROBE_INTERVAL": "2h"}, wantErr: true},
  241. {name: "puerto no numerico", vars: map[string]string{"PROBE_PORT": "ssh"}, wantErr: true},
  242. {name: "puerto fuera de rango", vars: map[string]string{"PROBE_PORT": "70000"}, wantErr: true},
  243. } {
  244. t.Run(tc.name, func(t *testing.T) {
  245. restore()
  246. err := applyProbeEnv(func(k string) string { return tc.vars[k] })
  247. if tc.wantErr {
  248. if err == nil {
  249. t.Fatalf("applyProbeEnv(%v) sin error", tc.vars)
  250. }
  251. return
  252. }
  253. if err != nil {
  254. t.Fatalf("applyProbeEnv(%v): %v", tc.vars, err)
  255. }
  256. if probeInterval != tc.interval || probePort != tc.port {
  257. t.Fatalf("intervalo/puerto = %s/%s, quiero %s/%s", probeInterval, probePort, tc.interval, tc.port)
  258. }
  259. })
  260. }
  261. }