clientbw_test.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. // clientbw_test.go — parser de `nlbw -c json -g mac` (issue #551) y
  2. // comportamiento de la sonda probeClientBw con runner fake.
  3. package probe
  4. import (
  5. "context"
  6. "encoding/json"
  7. "strings"
  8. "testing"
  9. )
  10. // Fixture del formato real de nlbwmon (handle_json en client.c): agrupación
  11. // por MAC (-g mac) emite columnas mac, conns, rx_bytes, rx_pkts, tx_bytes,
  12. // tx_pkts en ese orden, con los contadores acumulados del periodo.
  13. const nlbwFixture = `{"columns":["mac","conns","rx_bytes","rx_pkts","tx_bytes","tx_pkts"],"data":[
  14. ["aa:bb:cc:dd:ee:01", 34, 123456789, 98765, 111222333, 121314],
  15. ["aa:bb:cc:dd:ee:02", 2, 1000, 5, 2000, 9]
  16. ]}`
  17. func TestParseNlbwJSONFixture(t *testing.T) {
  18. hosts, err := ParseNlbwJSON([]byte(nlbwFixture))
  19. if err != nil {
  20. t.Fatalf("parse: %v", err)
  21. }
  22. if len(hosts) != 2 {
  23. t.Fatalf("hosts: %d", len(hosts))
  24. }
  25. h := hosts["AA:BB:CC:DD:EE:01"] // normalizada a mayúsculas
  26. if h.RxBytes != 123456789 || h.TxBytes != 111222333 {
  27. t.Fatalf("contadores aa:bb:...:01: %+v", h)
  28. }
  29. if h2 := hosts["AA:BB:CC:DD:EE:02"]; h2.RxBytes != 1000 || h2.TxBytes != 2000 {
  30. t.Fatalf("contadores aa:bb:...:02: %+v", h2)
  31. }
  32. }
  33. func TestParseNlbwJSONColumnasPorNombre(t *testing.T) {
  34. // El parser mapea por NOMBRE de columna: orden distinto o columnas
  35. // extra no deben romper (p.ej. versiones del CLI que añadan campos).
  36. reordered := `{"columns":["conns","tx_bytes","mac","rx_bytes","foo"],"data":[
  37. [7, 999, "aa:bb:cc:dd:ee:03", 555, "irrelevante"]
  38. ]}`
  39. hosts, err := ParseNlbwJSON([]byte(reordered))
  40. if err != nil {
  41. t.Fatalf("parse reordenado: %v", err)
  42. }
  43. if len(hosts) != 1 {
  44. t.Fatalf("hosts: %d", len(hosts))
  45. }
  46. if h := hosts["AA:BB:CC:DD:EE:03"]; h.RxBytes != 555 || h.TxBytes != 999 {
  47. t.Fatalf("contadores reordenado: %+v", h)
  48. }
  49. }
  50. func TestParseNlbwJSONDefensivo(t *testing.T) {
  51. // JSON no válido → error.
  52. if _, err := ParseNlbwJSON([]byte("nlbw: connect failed")); err == nil {
  53. t.Fatal("no JSON debería dar error")
  54. }
  55. // Sin datos → vacío, sin error.
  56. hosts, err := ParseNlbwJSON([]byte(`{"columns":["mac","rx_bytes"],"data":[]}`))
  57. if err != nil || len(hosts) != 0 {
  58. t.Fatalf("sin datos: %v %v", hosts, err)
  59. }
  60. // Sin columna mac → sin hosts, sin error (formato inesperado, no pánico).
  61. if hosts, err := ParseNlbwJSON([]byte(`{"columns":["ip"],"data":[["1.2.3.4"]]}`)); err != nil || hosts != nil {
  62. t.Fatalf("sin columna mac: %v %v", hosts, err)
  63. }
  64. // Filas con tipos raros: no pánico, se saltan.
  65. weird := `{"columns":["mac","rx_bytes","tx_bytes"],"data":[[null, 1, 2],["aa:bb:cc:dd:ee:04","no-num",null],42]}`
  66. hosts, err = ParseNlbwJSON([]byte(weird))
  67. if err != nil {
  68. t.Fatalf("filas raras: %v", err)
  69. }
  70. if len(hosts) != 1 {
  71. t.Fatalf("hosts de filas raras: %d", len(hosts))
  72. }
  73. if h := hosts["AA:BB:CC:DD:EE:04"]; h.RxBytes != 0 || h.TxBytes != 0 {
  74. t.Fatalf("contadores no numéricos: %+v", h)
  75. }
  76. }
  77. // TestProberClientBw: contrato de disponibilidad de la sonda (#551).
  78. func TestProberClientBw(t *testing.T) {
  79. ctx := context.Background()
  80. // nlbw NO instalado: command -v falla → Available=false (el server usa
  81. // entonces hostapd bytes por estación).
  82. p := NewProber(fakeRunner{outs: map[string]string{}}, Options{})
  83. cb := p.probeClientBw(ctx)
  84. if cb == nil || cb.Available || cb.Hosts != nil {
  85. t.Fatalf("sin nlbw: %+v", cb)
  86. }
  87. // Instalado con datos: fixture completo.
  88. p = NewProber(fakeRunner{outs: map[string]string{
  89. CmdNlbwmonCheck: "/usr/sbin/nlbw\n",
  90. CmdNlbwmonJSON: nlbwFixture,
  91. }}, Options{})
  92. cb = p.probeClientBw(ctx)
  93. if cb == nil || !cb.Available || len(cb.Hosts) != 2 {
  94. t.Fatalf("con datos: %+v", cb)
  95. }
  96. // Instalado, daemon caído: check OK pero nlbw sin salida →
  97. // Available=true con Hosts nil (sonda fallida, no "no instalado").
  98. p = NewProber(fakeRunner{outs: map[string]string{
  99. CmdNlbwmonCheck: "/usr/sbin/nlbw\n",
  100. }}, Options{})
  101. cb = p.probeClientBw(ctx)
  102. if cb == nil || !cb.Available || cb.Hosts != nil {
  103. t.Fatalf("daemon caído: %+v", cb)
  104. }
  105. // Instalado, cero hosts: data [] → vacío honesto, no nil.
  106. p = NewProber(fakeRunner{outs: map[string]string{
  107. CmdNlbwmonCheck: "/usr/sbin/nlbw\n",
  108. CmdNlbwmonJSON: `{"columns":["mac","rx_bytes"],"data":[]}`,
  109. }}, Options{})
  110. cb = p.probeClientBw(ctx)
  111. if cb == nil || !cb.Available || cb.Hosts == nil || len(cb.Hosts) != 0 {
  112. t.Fatalf("cero hosts: %+v", cb)
  113. }
  114. }
  115. // TestPayloadClientBwWire: nil vs vacío viaja distinto en el JSON (contrato
  116. // del anti-parpadeo del server). Sin omitempty en Hosts a propósito.
  117. func TestPayloadClientBwWire(t *testing.T) {
  118. mustJSON := func(v any) string {
  119. b, err := json.Marshal(v)
  120. if err != nil {
  121. t.Fatalf("marshal: %v", err)
  122. }
  123. return string(b)
  124. }
  125. // Sección presente con hosts
  126. if s := mustJSON(PayloadData{ClientBw: &ClientBwData{Available: true, Hosts: map[string]NlbwCounter{"AA:BB:CC:DD:EE:01": {RxBytes: 1}}}}); !strings.Contains(s, `"hosts":{`) {
  127. t.Fatalf("wire con hosts: %s", s)
  128. }
  129. // Sección presente, sonda fallida: hosts null (no ausente)
  130. if s := mustJSON(PayloadData{ClientBw: &ClientBwData{Available: true}}); !strings.Contains(s, `"hosts":null`) {
  131. t.Fatalf("wire sonda fallida: %s", s)
  132. }
  133. // No instalado: available false, hosts null
  134. if s := mustJSON(PayloadData{ClientBw: &ClientBwData{Available: false}}); !strings.Contains(s, `"available":false`) {
  135. t.Fatalf("wire no instalado: %s", s)
  136. }
  137. // Sección ausente (push event-driven): nada de clientBw en el JSON
  138. if s := mustJSON(PayloadData{}); strings.Contains(s, "clientBw") {
  139. t.Fatalf("wire sin sección: %s", s)
  140. }
  141. // Disponible sin hosts (vacío honesto): "hosts":{}
  142. if s := mustJSON(PayloadData{ClientBw: &ClientBwData{Available: true, Hosts: map[string]NlbwCounter{}}}); !strings.Contains(s, `"hosts":{}`) {
  143. t.Fatalf("wire vacío honesto: %s", s)
  144. }
  145. }