i18n_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package i18n_test
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. "github.com/qor5/x/i18n"
  9. "github.com/theplant/testingutils"
  10. "golang.org/x/text/language"
  11. )
  12. type Messages struct {
  13. Update string
  14. WelcomeToQOR5name string
  15. }
  16. var Messages_zh_CN = &Messages{
  17. Update: "更新",
  18. WelcomeToQOR5name: "欢迎来到QOR5, {name}",
  19. }
  20. var Messages_en_US = &Messages{
  21. Update: "Update",
  22. }
  23. func TestLanguage(t *testing.T) {
  24. var mediaLibraryKey i18n.ModuleKey = "mediaLibraryKey"
  25. b := i18n.New().
  26. SupportLanguages(language.English, language.Japanese, language.SimplifiedChinese).
  27. RegisterForModule(language.SimplifiedChinese, mediaLibraryKey, Messages_zh_CN).
  28. RegisterForModule(language.English, mediaLibraryKey, Messages_en_US)
  29. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  30. msg := i18n.MustGetModuleMessages(r, mediaLibraryKey, Messages_en_US).(*Messages)
  31. _, _ = fmt.Fprintln(w, "")
  32. _, _ = fmt.Fprintln(w, msg.Update)
  33. _, _ = fmt.Fprintln(w, i18n.T(r, mediaLibraryKey, "Welcome Home &!@*#&^*!@^#*(!@ Felix"))
  34. _, _ = fmt.Fprintln(w, i18n.T(r, mediaLibraryKey, "Welcome to QOR5, {name}", "{name}", "Felix"))
  35. _, _ = fmt.Fprintln(w, i18n.PT(r, mediaLibraryKey, "Customer", "Name"))
  36. })
  37. recorder := httptest.NewRecorder()
  38. req, _ := http.NewRequest("GET", "/?lang=zh", nil)
  39. b.EnsureLanguage(h).ServeHTTP(recorder, req)
  40. diff := testingutils.PrettyJsonDiff(`
  41. 更新
  42. Welcome Home &!@*#&^*!@^#*(!@ Felix
  43. 欢迎来到QOR5, Felix
  44. Name
  45. `, recorder.Body.String())
  46. if len(diff) > 0 {
  47. t.Error(diff)
  48. }
  49. if recorder.Header().Get("Set-Cookie") == "" {
  50. t.Error("cookie not set")
  51. }
  52. recorder = httptest.NewRecorder()
  53. req, _ = http.NewRequest("GET", "/", nil)
  54. req.AddCookie(&http.Cookie{Name: "lang", Value: "zh-Hans"})
  55. b.EnsureLanguage(h).ServeHTTP(recorder, req)
  56. if !strings.Contains(recorder.Body.String(), "更新") {
  57. t.Errorf("response is wrong, %s", recorder.Body.String())
  58. }
  59. recorder = httptest.NewRecorder()
  60. req, _ = http.NewRequest("GET", "/", nil)
  61. req.Header.Add("Accept-Language", "zh")
  62. b.EnsureLanguage(h).ServeHTTP(recorder, req)
  63. if !strings.Contains(recorder.Body.String(), "更新") {
  64. t.Errorf("response is wrong, %s", recorder.Body.String())
  65. }
  66. recorder = httptest.NewRecorder()
  67. req, _ = http.NewRequest("GET", "/", nil)
  68. b.EnsureLanguage(h).ServeHTTP(recorder, req)
  69. if !strings.Contains(recorder.Body.String(), "Update") {
  70. t.Errorf("response is wrong, %s", recorder.Body.String())
  71. }
  72. }