alertlang_test.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // alertlang_test.go - localización server-side de pushes (#888/#889) contra
  2. // los catálogos reales de la app (mismo enfoque que alerts_i18n_test.go).
  3. // Dirección #1014: los literales del server son INGLÉS canónico; el catálogo
  4. // ES traduce cuando alerts.lang=es y el fallback es siempre el literal EN.
  5. package alertlang
  6. import (
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "testing"
  11. "github.com/gnacho/netpulse/server-go/internal/alerts"
  12. )
  13. type mapKV map[string]string
  14. func (m mapKV) Get(key string) (string, bool) { v, ok := m[key]; return v, ok }
  15. func localesFromApp(t *testing.T) {
  16. t.Helper()
  17. root, err := filepath.Abs("../../..")
  18. if err != nil {
  19. t.Fatal(err)
  20. }
  21. SetLocalesFS(os.DirFS(filepath.Join(root, "app", "dist", "locales")))
  22. if len(Supported()) == 0 {
  23. t.Fatal("no se detectaron idiomas (¿falta npm run build en app/?)")
  24. }
  25. }
  26. // agentDownEv: evento tal y como lo compone el motor tras #1014: literales
  27. // en inglés canónico + Type/Vars para la localización por catálogo.
  28. func agentDownEv() alerts.AlertEvent {
  29. return alerts.AlertEvent{
  30. ID: "alert-agent-down-gateway",
  31. Category: alerts.CatRouter,
  32. Type: "agent-down",
  33. Title: "Agent down on gateway",
  34. Description: "No data from the agent on gateway for more than 5m - using cached data",
  35. Hint: alerts.HintFor(alerts.HintAgentDown),
  36. Vars: map[string]string{"router": "gateway", "confirm": "5m"},
  37. }
  38. }
  39. // (a) Default (sin ajuste alerts.lang) = inglés: texto EN nativo del
  40. // catálogo, interpolado con las vars del evento.
  41. func TestLocalizeDefaultIsEnglish(t *testing.T) {
  42. localesFromApp(t)
  43. out := Localize(agentDownEv(), mapKV{})
  44. if out.Title != "Agent down on gateway" {
  45. t.Fatalf("title = %q", out.Title)
  46. }
  47. // La descripción sale del catálogo EN interpolado (no del literal).
  48. for _, part := range []string{"No data from the agent on gateway for more than 5m", "using cached data"} {
  49. if !strings.Contains(out.Description, part) {
  50. t.Fatalf("description sin %q: %q", part, out.Description)
  51. }
  52. }
  53. if strings.Contains(out.Description, "{{") || containsES(out.Description) {
  54. t.Fatalf("description sin interpolar o en español: %q", out.Description)
  55. }
  56. }
  57. func containsES(s string) bool {
  58. return strings.Contains(s, "Agente") || strings.Contains(s, "caído") || strings.Contains(s, "Sin datos")
  59. }
  60. // (b) lang=es produce el castellano del catálogo (título, descripción e
  61. // hint), no el literal EN.
  62. func TestLocalizeSpanishExplicit(t *testing.T) {
  63. localesFromApp(t)
  64. out := Localize(agentDownEv(), mapKV{KeyLang: "es"})
  65. if out.Title != "Agente caído en gateway" {
  66. t.Fatalf("title = %q", out.Title)
  67. }
  68. if !strings.Contains(out.Description, "Sin datos del agente de gateway") {
  69. t.Fatalf("description no viene del catálogo ES: %q", out.Description)
  70. }
  71. if !strings.Contains(out.Hint, "Comprueba la alimentación") {
  72. t.Fatalf("hint no viene del catálogo ES: %q", out.Hint)
  73. }
  74. }
  75. // (c) Tipo desconocido (sin clave en el catálogo): cae al literal EN sin
  76. // romperse, incluso con lang=es.
  77. func TestLocalizeUnknownTypeKeepsEnglishLiteral(t *testing.T) {
  78. localesFromApp(t)
  79. ev := agentDownEv()
  80. ev.Type = "no-existe-este-slug"
  81. for _, lang := range []string{"en", "es"} {
  82. out := Localize(ev, mapKV{KeyLang: lang})
  83. if out.Title != ev.Title || out.Description != ev.Description {
  84. t.Fatalf("lang=%s: un type sin clave i18n debe conservar el literal EN: %+v", lang, out)
  85. }
  86. }
  87. // Sin type: tampoco se toca.
  88. ev.Type = ""
  89. if out := Localize(ev, mapKV{KeyLang: "es"}); out.Title != ev.Title {
  90. t.Fatal("un evento sin type no debe cambiar")
  91. }
  92. }
  93. // (d) Plantilla con valores interpolados: las vars caen en su sitio en ambos
  94. // idiomas y no queda ningún placeholder {{...}} sin resolver.
  95. func TestLocalizeInterpolatesBothLanguages(t *testing.T) {
  96. localesFromApp(t)
  97. ev := alerts.AlertEvent{
  98. ID: "alert-agent-outdated-rt1",
  99. Type: "agent-outdated",
  100. Title: "Agent outdated on rt1",
  101. Vars: map[string]string{"router": "rt1", "version": "3.0.4", "kind": "native", "latest": "3.0.5"},
  102. }
  103. en := Localize(ev, mapKV{KeyLang: "en"})
  104. if en.Description != "rt1 pushes version 3.0.4; the latest available for the native agent is 3.0.5" {
  105. t.Fatalf("EN description = %q", en.Description)
  106. }
  107. es := Localize(ev, mapKV{KeyLang: "es"})
  108. for _, out := range []alerts.AlertEvent{en, es} {
  109. if strings.Contains(out.Title, "{{") || strings.Contains(out.Description, "{{") {
  110. t.Fatalf("placeholder sin resolver: %+v", out)
  111. }
  112. for _, v := range []string{"rt1", "3.0.4", "3.0.5"} {
  113. if !strings.Contains(out.Description, v) {
  114. t.Fatalf("description sin el valor %q: %q", v, out.Description)
  115. }
  116. }
  117. }
  118. }
  119. func TestLangDefaults(t *testing.T) {
  120. localesFromApp(t)
  121. // Idioma no configurado → default en.
  122. if got := Lang(mapKV{}); got != DefaultLang {
  123. t.Fatalf("Lang default = %q", got)
  124. }
  125. // Idioma inválido en kv → default en.
  126. if got := Lang(mapKV{KeyLang: "xx"}); got != DefaultLang {
  127. t.Fatalf("Lang inválido = %q", got)
  128. }
  129. }
  130. // El notifier entrega al canal el evento ya localizado: con lang=es el push
  131. // sale en castellano aunque el motor compuso en inglés.
  132. func TestNotifierWrapsNext(t *testing.T) {
  133. localesFromApp(t)
  134. var got alerts.AlertEvent
  135. n := Notifier(mapKV{KeyLang: "es"}, notifierFunc(func(ev alerts.AlertEvent) { got = ev }))
  136. n.Notify(agentDownEv())
  137. if got.Title != "Agente caído en gateway" {
  138. t.Fatalf("el notifier no localizó: %q", got.Title)
  139. }
  140. // next nil no debe explotar.
  141. Notifier(mapKV{}, nil).Notify(agentDownEv())
  142. }
  143. type notifierFunc func(alerts.AlertEvent)
  144. func (f notifierFunc) Notify(ev alerts.AlertEvent) { f(ev) }
  145. // #1334: LocalizeLang fuerza el idioma por suscriptor, independiente del
  146. // ajuste global: misma composición por catálogo que Localize.
  147. func TestLocalizeLangPerSubscriber(t *testing.T) {
  148. localesFromApp(t)
  149. ev := agentDownEv()
  150. es := LocalizeLang(ev, "es")
  151. if es.Title == ev.Title || !strings.Contains(es.Title, "gateway") {
  152. t.Fatalf("esperaba título ES interpolado: %q", es.Title)
  153. }
  154. if es.Description == ev.Description || !strings.Contains(es.Description, "5m") {
  155. t.Fatalf("esperaba descripción ES interpolada: %q", es.Description)
  156. }
  157. // Idioma no soportado: cae al literal del evento (nunca peor que nativo).
  158. if out := LocalizeLang(ev, "fr"); out.Title != ev.Title {
  159. t.Fatalf("idioma no soportado debe devolver el evento tal cual: %q", out.Title)
  160. }
  161. // Sin type: no se toca.
  162. bare := alerts.AlertEvent{Title: "Raw", Description: "raw"}
  163. if out := LocalizeLang(bare, "es"); out.Title != "Raw" {
  164. t.Fatalf("evento sin type no se localiza: %q", out.Title)
  165. }
  166. }