mqttpub_test.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package mqttpub
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/gnacho/netpulse/server-go/internal/adapters"
  7. )
  8. func lookupFrom(m map[string]string) func(string) (string, bool) {
  9. return func(k string) (string, bool) {
  10. v, ok := m[k]
  11. return v, ok
  12. }
  13. }
  14. func TestConfigFromEnv(t *testing.T) {
  15. // Disabled by default.
  16. if cfg := ConfigFromEnv(lookupFrom(nil)); cfg.Enabled {
  17. t.Fatal("config must be disabled by default")
  18. }
  19. // Enabled without host stays disabled.
  20. cfg := ConfigFromEnv(lookupFrom(map[string]string{"NETPULSE_MQTT_ENABLED": "1"}))
  21. if cfg.Enabled {
  22. t.Fatal("enabled without a host must be disabled")
  23. }
  24. // Full config.
  25. cfg = ConfigFromEnv(lookupFrom(map[string]string{
  26. "NETPULSE_MQTT_ENABLED": "true",
  27. "NETPULSE_MQTT_HOST": "broker.local",
  28. "NETPULSE_MQTT_PORT": "1884",
  29. "NETPULSE_MQTT_USER": "netpulse",
  30. "NETPULSE_MQTT_PASS": "s3cret",
  31. "NETPULSE_MQTT_INSTANCE": "home",
  32. "NETPULSE_MQTT_INTERVAL": "15",
  33. }))
  34. if !cfg.Enabled || cfg.Host != "broker.local" || cfg.Port != 1884 ||
  35. cfg.User != "netpulse" || cfg.Pass != "s3cret" || cfg.Instance != "home" {
  36. t.Fatalf("unexpected config: %+v", cfg)
  37. }
  38. if cfg.Interval.Seconds() != 15 {
  39. t.Fatalf("interval = %v, want 15s", cfg.Interval)
  40. }
  41. // Instance is sanitized for MQTT topics.
  42. cfg = ConfigFromEnv(lookupFrom(map[string]string{
  43. "NETPULSE_MQTT_ENABLED": "1",
  44. "NETPULSE_MQTT_HOST": "b",
  45. "NETPULSE_MQTT_INSTANCE": "home/#1",
  46. }))
  47. if cfg.Instance != "home--1" {
  48. t.Fatalf("instance = %q, want home--1", cfg.Instance)
  49. }
  50. }
  51. func sampleOverview() *adapters.Overview {
  52. cpu, ram, temp := 12, 40, 55
  53. return &adapters.Overview{
  54. Health: adapters.HealthScore{Score: 92, Label: "Excelente"},
  55. DeviceTotals: adapters.DeviceTotals{Total: 30, Online: 27},
  56. UnreadAlerts: 2,
  57. WAN: adapters.WAN{Plan: "600/600"},
  58. Routers: []adapters.Router{
  59. {ID: "gw", Name: "Gateway", Model: "MT6000", Status: "online", Health: 100,
  60. CPU: &cpu, RAM: &ram, Temp: &temp, Clients: 18, Uptime: "3d 4h"},
  61. {ID: "ap-1", Name: "AP 1", Status: "offline", Health: 0},
  62. },
  63. Alerts: []adapters.AlertEvent{{ID: "a1", Severity: "warn", Title: "Temp",
  64. RouterID: "gw", Ts: 1000}},
  65. }
  66. }
  67. func TestBuildStatus(t *testing.T) {
  68. st := buildStatus("home", "v1.2.3", sampleOverview())
  69. if st.HealthScore != 92 || st.ClientsOnline != 27 || st.ClientsTotal != 30 {
  70. t.Fatalf("unexpected status: %+v", st)
  71. }
  72. if st.RoutersOnline != 1 || st.RoutersTotal != 2 {
  73. t.Fatalf("router counts = %d/%d, want 1/2", st.RoutersOnline, st.RoutersTotal)
  74. }
  75. if st.UnreadAlerts != 2 || st.Plan != "600/600" {
  76. t.Fatalf("unexpected status: %+v", st)
  77. }
  78. }
  79. func TestBuildRouterState(t *testing.T) {
  80. r := sampleOverview().Routers[0]
  81. rs := buildRouterState(r)
  82. if rs.Slug != "gw" || rs.Status != "online" || rs.Clients != 18 {
  83. t.Fatalf("unexpected router state: %+v", rs)
  84. }
  85. if rs.CPU == nil || *rs.CPU != 12 || rs.Temp == nil || *rs.Temp != 55 {
  86. t.Fatalf("vitals not carried over: %+v", rs)
  87. }
  88. }
  89. func TestRouterSlugFallsBackToName(t *testing.T) {
  90. if got := routerSlug(adapters.Router{Name: "AP 1"}); got != "AP-1" {
  91. t.Fatalf("slug = %q, want AP-1", got)
  92. }
  93. }
  94. func TestRouterSetKeyIsStable(t *testing.T) {
  95. ov := sampleOverview()
  96. k1 := routerSetKey(ov)
  97. // Reorder the routers: the key must not change.
  98. ov.Routers[0], ov.Routers[1] = ov.Routers[1], ov.Routers[0]
  99. if k2 := routerSetKey(ov); k2 != k1 {
  100. t.Fatalf("routerSetKey changed with order: %q vs %q", k1, k2)
  101. }
  102. }
  103. func TestHAEntities(t *testing.T) {
  104. ents := haEntities("home", "v1.2.3", sampleOverview())
  105. if len(ents) == 0 {
  106. t.Fatal("no discovery entities")
  107. }
  108. seen := map[string]bool{}
  109. var instanceEntities, routerEntities int
  110. for _, e := range ents {
  111. uid, _ := e.config["unique_id"].(string)
  112. if uid == "" {
  113. t.Fatalf("%s/%s: no unique_id", e.nodeID, e.objectID)
  114. }
  115. if seen[uid] {
  116. t.Fatalf("duplicate unique_id %q", uid)
  117. }
  118. seen[uid] = true
  119. if got, _ := e.config["availability_topic"].(string); got != availabilityTopic("home") {
  120. t.Fatalf("%s: availability_topic = %q", uid, got)
  121. }
  122. if e.nodeID == "netpulse_home" {
  123. instanceEntities++
  124. } else {
  125. routerEntities++
  126. }
  127. }
  128. if instanceEntities == 0 || routerEntities == 0 {
  129. t.Fatalf("expected instance and router entities, got %d/%d", instanceEntities, routerEntities)
  130. }
  131. // The per-router state topic must be the one we publish.
  132. for _, e := range ents {
  133. if e.nodeID == "netpulse_home_gw" && e.objectID == "cpu_usage" {
  134. if got, _ := e.config["state_topic"].(string); got != "netpulse/home/router/gw/state" {
  135. t.Fatalf("router state_topic = %q", got)
  136. }
  137. return
  138. }
  139. }
  140. t.Fatal("no cpu_usage entity for the gw router")
  141. }
  142. func TestStartIsNoopWhenDisabled(t *testing.T) {
  143. p := New(Config{}, "v1", func() *adapters.Overview { return nil }, false)
  144. if p.Enabled() {
  145. t.Fatal("publisher must be disabled")
  146. }
  147. p.Start(context.Background()) // must not panic nor block
  148. }
  149. func TestHAEntitiesSelfExposeMarkedForRemoval(t *testing.T) {
  150. ov := sampleOverview()
  151. self := true
  152. ov.Routers[1].SelfExpose = &self // ap-1 se expone solo
  153. ents := haEntities("home", "v1.2.3", ov)
  154. var removed, kept int
  155. for _, e := range ents {
  156. if e.nodeID == "netpulse_home_ap-1" {
  157. if !e.remove {
  158. t.Fatalf("ap-1 %s must be marked for removal", e.objectID)
  159. }
  160. removed++
  161. continue
  162. }
  163. if e.remove {
  164. t.Fatalf("%s/%s must not be marked for removal", e.nodeID, e.objectID)
  165. }
  166. kept++
  167. }
  168. if removed != 6 || kept != 11 {
  169. t.Fatalf("removed=%d kept=%d, want 6/11", removed, kept)
  170. }
  171. // La marca forma parte de la clave de conjunto: un cambio republica discovery.
  172. if routerSetKey(ov) == routerSetKey(sampleOverview()) {
  173. t.Fatal("routerSetKey must change when a router starts self-exposing")
  174. }
  175. }
  176. // #1158: Apply debe esperar al publisher viejo (bounded) antes de arrancar el
  177. // nuevo, sin colgarse aunque el broker sea inalcanzable (el goroutine viejo
  178. // sale en cuanto procesa el cancel).
  179. func TestManagerApplyReplacesPublisher(t *testing.T) {
  180. snapshot := func() *adapters.Overview { return &adapters.Overview{} }
  181. m := NewManager(Config{Enabled: true, Host: "127.0.0.1", Port: 1, Instance: "t"}, "test", snapshot, false)
  182. m.Start()
  183. if !m.Running() {
  184. t.Fatal("publisher should be running after Start")
  185. }
  186. start := time.Now()
  187. m.Apply(Config{Enabled: true, Host: "127.0.0.1", Port: 2, Instance: "t"})
  188. if elapsed := time.Since(start); elapsed > shutdownWait+2*time.Second {
  189. t.Fatalf("Apply took %v, the old publisher shutdown must be bounded", elapsed)
  190. }
  191. if !m.Running() {
  192. t.Fatal("publisher should still be running after Apply")
  193. }
  194. if got := m.Config(); got.Port != 2 {
  195. t.Fatalf("config port = %d, want 2", got.Port)
  196. }
  197. // Misma config: no-op (no rearranca ni cuelga).
  198. m.Apply(Config{Enabled: true, Host: "127.0.0.1", Port: 2, Instance: "t"})
  199. if !m.Running() {
  200. t.Fatal("publisher must keep running after a no-op Apply")
  201. }
  202. // Deshabilitar: el publisher para.
  203. m.Apply(Config{Enabled: false, Host: "127.0.0.1", Port: 2, Instance: "t"})
  204. if m.Running() {
  205. t.Fatal("publisher must stop when disabled")
  206. }
  207. }