go-html/context_test.go
Virgil 669163fcd6
Some checks are pending
Security Scan / security (push) Waiting to run
Test / test (push) Waiting to run
feat(html): make default context locale-aware
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-03 19:13:18 +00:00

89 lines
2.3 KiB
Go

// SPDX-Licence-Identifier: EUPL-1.2
package html
import "testing"
type localeTranslator struct {
language string
}
func (t *localeTranslator) T(key string, args ...any) string {
if key == "prompt.yes" && t.language == "fr" {
return "o"
}
if key == "prompt.yes" && t.language == "en" {
return "y"
}
return key
}
func (t *localeTranslator) SetLanguage(language string) error {
t.language = language
return nil
}
func TestContext_NewContextWithService_AppliesLocale(t *testing.T) {
svc := &localeTranslator{}
ctx := NewContextWithService(svc, "fr-FR")
if svc.language != "fr" {
t.Fatalf("NewContextWithService should apply locale to translator, got %q", svc.language)
}
if got := Text("prompt.yes").Render(ctx); got != "o" {
t.Fatalf("NewContextWithService locale translation = %q, want %q", got, "o")
}
}
func TestContext_NewContext_AppliesLocaleToDefaultService(t *testing.T) {
ctx := NewContext("fr-FR")
if got := Text("prompt.yes").Render(ctx); got != "o" {
t.Fatalf("NewContext(locale) translation = %q, want %q", got, "o")
}
}
func TestContext_NewContextWithService_UsesLocale(t *testing.T) {
svc := &localeTranslator{}
ctx := NewContextWithService(svc, "en-GB")
if svc.language != "en" {
t.Fatalf("NewContextWithService should apply locale to translator, got %q", svc.language)
}
if got := Text("prompt.yes").Render(ctx); got != "y" {
t.Fatalf("NewContextWithService translation = %q, want %q", got, "y")
}
}
func TestContext_SetLocale_ReappliesTranslatorLanguage(t *testing.T) {
svc := &localeTranslator{}
ctx := NewContextWithService(svc, "en-GB")
ctx.SetLocale("fr-FR")
if ctx.Locale != "fr-FR" {
t.Fatalf("SetLocale() Locale = %q, want %q", ctx.Locale, "fr-FR")
}
if svc.language != "fr" {
t.Fatalf("SetLocale() should reapply language to translator, got %q", svc.language)
}
if got := Text("prompt.yes").Render(ctx); got != "o" {
t.Fatalf("SetLocale() translation = %q, want %q", got, "o")
}
}
func TestContext_SetService_AppliesCurrentLocale(t *testing.T) {
svc := &localeTranslator{}
ctx := NewContext("fr-FR")
ctx.SetService(svc)
if ctx.service != svc {
t.Fatal("SetService() should retain the provided service")
}
if svc.language != "fr" {
t.Fatalf("SetService() should apply current locale to translator, got %q", svc.language)
}
}