124 lines
2.6 KiB
Go
124 lines
2.6 KiB
Go
package i18n
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestTranslator(t *testing.T) {
|
|
// Create temporary test translations
|
|
tmpDir := t.TempDir()
|
|
|
|
enFile := filepath.Join(tmpDir, "en.json")
|
|
enContent := `{
|
|
"menu": {
|
|
"home": "Home",
|
|
"search": "Search"
|
|
},
|
|
"editor": {
|
|
"confirmDelete": "Are you sure you want to delete {{filename}}?"
|
|
}
|
|
}`
|
|
if err := os.WriteFile(enFile, []byte(enContent), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
frFile := filepath.Join(tmpDir, "fr.json")
|
|
frContent := `{
|
|
"menu": {
|
|
"home": "Accueil",
|
|
"search": "Rechercher"
|
|
},
|
|
"editor": {
|
|
"confirmDelete": "Êtes-vous sûr de vouloir supprimer {{filename}} ?"
|
|
}
|
|
}`
|
|
if err := os.WriteFile(frFile, []byte(frContent), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Test translator
|
|
trans := New("en")
|
|
if err := trans.LoadFromDir(tmpDir); err != nil {
|
|
t.Fatalf("Failed to load translations: %v", err)
|
|
}
|
|
|
|
tests := []struct {
|
|
name string
|
|
lang string
|
|
key string
|
|
args map[string]string
|
|
expected string
|
|
}{
|
|
{
|
|
name: "English simple key",
|
|
lang: "en",
|
|
key: "menu.home",
|
|
expected: "Home",
|
|
},
|
|
{
|
|
name: "French simple key",
|
|
lang: "fr",
|
|
key: "menu.search",
|
|
expected: "Rechercher",
|
|
},
|
|
{
|
|
name: "English with interpolation",
|
|
lang: "en",
|
|
key: "editor.confirmDelete",
|
|
args: map[string]string{"filename": "test.md"},
|
|
expected: "Are you sure you want to delete test.md?",
|
|
},
|
|
{
|
|
name: "French with interpolation",
|
|
lang: "fr",
|
|
key: "editor.confirmDelete",
|
|
args: map[string]string{"filename": "test.md"},
|
|
expected: "Êtes-vous sûr de vouloir supprimer test.md ?",
|
|
},
|
|
{
|
|
name: "Missing key returns key",
|
|
lang: "en",
|
|
key: "missing.key",
|
|
expected: "missing.key",
|
|
},
|
|
{
|
|
name: "Fallback to default language",
|
|
lang: "es", // Spanish not loaded, should fallback to English
|
|
key: "menu.home",
|
|
expected: "Home",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
var result string
|
|
if tt.args != nil {
|
|
result = trans.T(tt.lang, tt.key, tt.args)
|
|
} else {
|
|
result = trans.T(tt.lang, tt.key)
|
|
}
|
|
|
|
if result != tt.expected {
|
|
t.Errorf("T(%s, %s) = %s, want %s", tt.lang, tt.key, result, tt.expected)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Test GetAvailableLanguages
|
|
langs := trans.GetAvailableLanguages()
|
|
if len(langs) != 2 {
|
|
t.Errorf("Expected 2 languages, got %d", len(langs))
|
|
}
|
|
|
|
// Test GetTranslations
|
|
enTrans, ok := trans.GetTranslations("en")
|
|
if !ok {
|
|
t.Error("Expected to find English translations")
|
|
}
|
|
if enTrans == nil {
|
|
t.Error("English translations should not be nil")
|
|
}
|
|
}
|