feat: release v0.26 portable i18n and presentation adapters
This commit is contained in:
59
i18n/httpi18n/http_test.go
Normal file
59
i18n/httpi18n/http_test.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package httpi18n_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.yuntuo.hk/k2safe/go-omni/i18n"
|
||||
"git.yuntuo.hk/k2safe/go-omni/i18n/httpi18n"
|
||||
)
|
||||
|
||||
func TestNegotiationAndExplicitResolvers(t *testing.T) {
|
||||
b, err := i18n.New(i18n.Config{SourceLocale: "en", DefaultLocale: "en", Locales: []string{"en", "fr", "zh-Hans", "zh-Hant"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := httpi18n.New(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, test := range []struct{ header, explicit, want string }{{"fr;q=0.8,en;q=0.1", "", "fr"}, {"fr;q=0,en;q=1", "", "en"}, {"zh-TW", "", "zh-Hant"}, {"zh-CN", "", "zh-Hans"}, {"invalid;garbage", "", "en"}, {strings.Repeat("x", 8193), "", "en"}, {"fr", "en", "en"}} {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.Header.Set("Accept-Language", test.header)
|
||||
if test.explicit != "" {
|
||||
r = r.WithContext(i18n.WithLocale(r.Context(), test.explicit))
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
w.Header().Set("Vary", "Origin")
|
||||
p.Wrap(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
if got := i18n.Locale(r.Context()); got != test.want {
|
||||
t.Errorf("got %s want %s", got, test.want)
|
||||
}
|
||||
})).ServeHTTP(w, r)
|
||||
if strings.Join(w.Header().Values("Vary"), ",") != "Origin,Accept-Language" {
|
||||
t.Fatal(w.Header())
|
||||
}
|
||||
if test.explicit != "" && !strings.Contains(w.Header().Get("Cache-Control"), "private") {
|
||||
t.Fatal(w.Header())
|
||||
}
|
||||
}
|
||||
custom, err := httpi18n.New(b, httpi18n.WithResolver(func(*http.Request) []string { return []string{"fr"} }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
r := custom.Apply(w, httptest.NewRequest("GET", "/", nil))
|
||||
if i18n.Locale(r.Context()) != "fr" || w.Header().Get("Cache-Control") != "private" {
|
||||
t.Fatal(r, w.Header())
|
||||
}
|
||||
broken, err := httpi18n.New(b, httpi18n.WithResolver(func(*http.Request) []string { panic("preference lookup failed") }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r = broken.Apply(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
|
||||
if i18n.Locale(r.Context()) != "en" {
|
||||
t.Fatal("resolver panic must preserve default selection")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user