Files
uptimesebi/internal/i18n/i18n_test.go
Sebastian UnterschützandClaude Opus 5.5 52819e64bb
ci / image (pull_request) Successful in 4m24s
ci / build (pull_request) Successful in 5m6s
ci / lint (pull_request) Successful in 12m3s
ci / test (pull_request) Successful in 15m27s
feat(notify): the remaining notification services of Uptime Kuma
Adds 93 services, bringing the total to 109 plus webhook and email:
chat and messengers (DingTalk, Feishu, LINE, Nextcloud Talk, Threema,
WhatsApp gateways, Nostr, Home Assistant, …), push (Bark, Gorush,
ServerChan, …), SMS and calls (Twilio, Plivo, 46elks, Alibaba Cloud,
Teltonika routers, …), email APIs (SendGrid, Brevo, Resend, Microsoft
Graph, …) and incident management (Grafana OnCall, Jira Service
Management, Splunk On-Call, Squadcast, SIGNL4, …). Customers bring
their own credentials; secrets are sealed like the others.

Services pair incidents by their ID where they can resolve alerts.
Signed requests (DingTalk, Nextcloud Talk, Alibaba Cloud) and replies
that report failures with status 200 are handled. Nostr messages are
sealed and gift-wrapped (NIP-17/59) with go-nostr, but sent over our own
WebSocket connections so relays go through the network guard. Messages
now carry the monitor's name, ID and target.

The channel form groups services, the i18n test derives provider keys
from the registry, and channel types may contain digits.

Refs #92

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 17:40:19 +01:00

264 lines
8.6 KiB
Go

package i18n
import (
"context"
"encoding/json"
"io/fs"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"testing"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
)
func catalogKeys(t *testing.T) map[string]map[string]bool {
t.Helper()
files, err := fs.Glob(locales, "locales/*.json")
if err != nil {
t.Fatal(err)
}
out := map[string]map[string]bool{}
for _, f := range files {
data, err := locales.ReadFile(f)
if err != nil {
t.Fatal(err)
}
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
t.Fatalf("%s: %v", f, err)
}
keys := map[string]bool{}
for k := range m {
keys[k] = true
}
out[strings.TrimSuffix(filepath.Base(f), ".json")] = keys
}
return out
}
func TestCatalogsHaveSameKeys(t *testing.T) {
cats := catalogKeys(t)
en := cats["en"]
for lang, keys := range cats {
for k := range en {
if !keys[k] {
t.Errorf("%s.json is missing %q", lang, k)
}
}
for k := range keys {
if !en[k] {
t.Errorf("%s.json has %q which en.json lacks", lang, k)
}
}
}
}
var usagePatterns = []struct {
re *regexp.Regexp
prefix string
// dir limits the pattern to files below this directory.
dir string
}{
{re: regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`)},
{re: regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), prefix: "error."},
{re: regexp.MustCompile(`\b(?:pageFor\(c|s\.page\(|s\.orgPage\()(?:, )?"([a-z0-9_.]+)"`)},
{re: regexp.MustCompile(`[^(:]"(sso_[a-z_]+)"`), prefix: "error.", dir: "api"},
{re: regexp.MustCompile(`return "(invalid_[a-z_]+)"`), prefix: "error."},
{re: regexp.MustCompile(`code = "([a-z_]+)"`), prefix: "error."},
{re: regexp.MustCompile(`\binvalid\("([a-z_]+)"\)`), prefix: "error."},
{re: regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`)},
{re: regexp.MustCompile(`@labeled\("([a-z0-9_.]+)"\)`)},
{re: regexp.MustCompile(`@checkerFact\("([a-z0-9_.]+)"`)},
{re: regexp.MustCompile(`@(?:settingsHeading|sectionHeading)\("([a-z0-9_.]+)"`)},
{re: regexp.MustCompile(`@settingsHeading\("[a-z0-9_.]+", "([a-z0-9_.]+)"`)},
{re: regexp.MustCompile(`@policyBanner\("([a-z0-9_.]+)", "([a-z0-9_.]+)"`)},
}
// TestUsedKeysExist scans the source tree for literal message IDs so a typo
// fails the build instead of showing a raw ID in production.
func TestUsedKeysExist(t *testing.T) {
en := catalogKeys(t)["en"]
var missing []string
err := filepath.WalkDir("..", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
if !strings.HasSuffix(p, ".go") && !strings.HasSuffix(p, ".templ") {
return nil
}
if strings.HasSuffix(p, "_templ.go") || strings.HasSuffix(p, "_test.go") {
return nil
}
src, err := os.ReadFile(p)
if err != nil {
return err
}
for _, u := range usagePatterns {
if u.dir != "" && !strings.Contains(filepath.ToSlash(p), "/"+u.dir+"/") {
continue
}
for _, m := range u.re.FindAllStringSubmatch(string(src), -1) {
for _, id := range m[1:] {
if id := u.prefix + id; !en[id] {
missing = append(missing, p+": "+id)
}
}
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
sort.Strings(missing)
for _, m := range missing {
t.Errorf("unknown message ID %s", m)
}
}
// Permission and scope labels are looked up as "perm.<name>" and
// "scope.<type>".
func TestEveryPermissionHasALabel(t *testing.T) {
en := catalogKeys(t)["en"]
for _, p := range authz.All {
if !en["perm."+string(p)] {
t.Errorf("en.json is missing %q", "perm."+string(p))
}
}
for _, rt := range []authz.ResourceType{authz.MonitorGroup, authz.StatusPage} {
if !en["scope."+string(rt)] {
t.Errorf("en.json is missing %q", "scope."+string(rt))
}
}
}
// Notification mails are looked up as "email.<event>.subject|body".
func TestEveryMailEventHasTexts(t *testing.T) {
en := catalogKeys(t)["en"]
for _, ev := range []string{"opened", "resolved", "test"} {
for _, part := range []string{"subject", "body"} {
if id := "email." + ev + "." + part; !en[id] {
t.Errorf("en.json is missing %q", id)
}
}
}
}
// Templates build these IDs from a prefix and a value.
func TestDynamicFamilies(t *testing.T) {
en := catalogKeys(t)["en"]
families := map[string][]string{
"status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"},
"monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "prometheus", "postgres", "mysql", "mssql", "mongodb", "redis", "mqtt", "kafka", "rabbitmq", "grpc", "smtp", "radius", "snmp", "steam", "minecraft", "docker", "heartbeat", "alertmanager"},
"agents.kind_": {"checker", "statuspage"},
"page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"},
"page.component.": {"operational", "degraded", "outage", "unknown", "maintenance"},
"storage.level_": {"raw", "1h", "1d"},
"legal.": {"imprint", "privacy"},
"monitors.op_": {"eq", "ne", "gt", "ge", "lt", "le", "contains", "exists", "absent"},
"evidence.stage_": {"dns", "connect", "tls", "response", "body"},
"evidence.phase_": {"dns", "connect", "tls", "wait", "download"},
"monitors.db_database_": {"postgres", "mysql", "mssql", "mongodb", "redis"},
"monitors.broker_hint_": {"mqtt", "kafka", "rabbitmq"},
"monitors.snmp_cond_": {"any", "eq", "ne", "contains", "gt", "ge", "lt", "le"},
"monitors.minecraft_": {"java", "bedrock", "hint", "edition"},
"monitors.db_tls_": {"require", "verify", "disable"},
"weekday.": {"0", "1", "2", "3", "4", "5", "6"},
"md.": {"heading", "bold", "italic", "strike", "link", "ul", "ol", "quote", "code", "codeblock", "table", "hr"},
"maintenance.recurrence_": {"none", "daily", "weekly", "monthly"},
"storage.job_": {"compression", "retention", "refresh_continuous_aggregate", "job_stat_history_retention"},
}
// Notification services name their type, group and settings.
families["channels.type_"] = []string{"webhook", "email"}
seenGroup, seenField := map[string]bool{}, map[string]bool{}
for _, p := range notify.Providers {
families["channels.type_"] = append(families["channels.type_"], p.Type)
if !seenGroup[p.Group] {
seenGroup[p.Group] = true
families["channels.group_"] = append(families["channels.group_"], p.Group)
}
for _, f := range p.Fields {
if !seenField[f.Name] {
seenField[f.Name] = true
families["channels.field_"] = append(families["channels.field_"], f.Name)
}
}
if en["channels.help_"+p.Type] {
families["channels.help_"] = append(families["channels.help_"], p.Type)
}
}
for prefix, values := range families {
for _, v := range values {
if !en[prefix+v] {
t.Errorf("en.json is missing %q", prefix+v)
}
}
}
}
// The language switcher builds "lang.<code>" dynamically.
func TestEveryLanguageHasAName(t *testing.T) {
c, err := Load()
if err != nil {
t.Fatal(err)
}
en := catalogKeys(t)["en"]
for _, l := range c.Supported() {
if !en["lang."+l] {
t.Errorf("en.json is missing %q", "lang."+l)
}
}
}
func TestMatch(t *testing.T) {
c, err := Load()
if err != nil {
t.Fatal(err)
}
tests := []struct {
prefs []string
want string
}{
{nil, "en"},
{[]string{"de"}, "de"},
{[]string{"", "de-AT,en;q=0.5"}, "de"},
{[]string{"fr-FR,fr;q=0.9"}, "en"},
{[]string{"en", "de"}, "en"},
{[]string{"garbage", "de"}, "de"},
}
for _, tt := range tests {
if got := c.Match(tt.prefs...).Lang(); got != tt.want {
t.Errorf("Match(%q) = %q, want %q", tt.prefs, got, tt.want)
}
}
}
func TestT(t *testing.T) {
c, err := Load()
if err != nil {
t.Fatal(err)
}
ctx := NewContext(context.Background(), c.Match("de"))
if got, want := T(ctx, "error.password_too_short", "Min", 12), "Das Passwort braucht mindestens 12 Zeichen."; got != want {
t.Errorf("T(de, password_too_short) = %q, want %q", got, want)
}
for n, want := range map[int]string{1: "1 Wiederherstellungscode übrig", 3: "3 Wiederherstellungscodes übrig"} {
if got := T(ctx, "security.recovery.left", "Count", n); got != want {
t.Errorf("T(de, recovery.left, %d) = %q, want %q", n, got, want)
}
}
if got, want := T(ctx, "error.token_lifetime_exceeds_policy", "Count", 30), "Tokens in dieser Organisation müssen innerhalb von 30 Tagen ablaufen."; got != want {
t.Errorf("T(de, token_lifetime_exceeds_policy, 30) = %q, want %q", got, want)
}
if got, want := T(ctx, "no.such.key"), "no.such.key"; got != want {
t.Errorf("T(missing) = %q, want %q", got, want)
}
if got, want := T(context.Background(), "auth.login.title"), "auth.login.title"; got != want {
t.Errorf("T(no localizer) = %q, want %q", got, want)
}
}