locale_test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. package locale
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "testing"
  10. "golang.org/x/image/font/gofont/goregular"
  11. "imuslab.com/arozos/mod/database"
  12. "imuslab.com/arozos/mod/locale/fonts"
  13. )
  14. const settingsJSON = `{
  15. "author": "test",
  16. "keys": {
  17. "zh-hk": {
  18. "name": "繁體中文(香港)",
  19. "fontFamily": "\"Microsoft JhengHei\"",
  20. "strings": {"a": "系統設定"}
  21. },
  22. "en-us": {
  23. "name": "English (US)",
  24. "strings": {"a": "Settings <b>now</b>"}
  25. }
  26. }
  27. }`
  28. // newTestServer builds a locale folder with the Go font defaulting for en-us
  29. func newTestServer(t *testing.T) (*Server, string) {
  30. t.Helper()
  31. root := filepath.Join(t.TempDir(), "locale")
  32. write := func(rel, content string) {
  33. full := filepath.Join(root, filepath.FromSlash(rel))
  34. if err := os.MkdirAll(filepath.Dir(full), 0755); err != nil {
  35. t.Fatal(err)
  36. }
  37. if err := os.WriteFile(full, []byte(content), 0644); err != nil {
  38. t.Fatal(err)
  39. }
  40. }
  41. write("system_settings.json", settingsJSON)
  42. write("sub/page.json", "\xef\xbb\xbf"+`{"keys": {"en-us": {"name": "English", "fontFamily": "Arial", "strings": {}}, "zh-hk": {"strings": {}}}}`)
  43. write("broken.json", `{"keys": {,}`)
  44. write("notes.txt", "hello")
  45. write("secret.db", "nope")
  46. write(".hidden/x.json", "{}")
  47. write("fonts/defaults.json", `{"defaults": {"en-us": "Go"}, "fallback": {"en-us": "Arial, sans-serif"}}`)
  48. write("fonts/Go/Go-Regular.ttf", string(goregular.TTF))
  49. db, err := database.NewDatabase(filepath.Join(t.TempDir(), "test.db"), false)
  50. if err != nil {
  51. t.Fatalf("NewDatabase: %v", err)
  52. }
  53. t.Cleanup(func() { db.Close() })
  54. lib, err := fonts.NewLibrary(fonts.Options{Root: filepath.Join(root, "fonts"), CacheDir: filepath.Join(t.TempDir(), "cache"), DB: db})
  55. if err != nil {
  56. t.Fatalf("NewLibrary: %v", err)
  57. }
  58. srv, err := NewServer(Options{Root: root, Fonts: lib})
  59. if err != nil {
  60. t.Fatalf("NewServer: %v", err)
  61. }
  62. return srv, root
  63. }
  64. func get(srv *Server, path, user string, header map[string]string) *httptest.ResponseRecorder {
  65. r := httptest.NewRequest(http.MethodGet, path, nil)
  66. for k, v := range header {
  67. r.Header.Set(k, v)
  68. }
  69. w := httptest.NewRecorder()
  70. srv.Serve(w, r, user)
  71. return w
  72. }
  73. func TestLanguagesComeFromSystemSettings(t *testing.T) {
  74. srv, _ := newTestServer(t)
  75. langs := srv.Languages()
  76. if len(langs) != 2 || langs[0].Code != "en-us" || langs[1].Code != "zh-hk" || langs[1].Name != "繁體中文(香港)" {
  77. t.Errorf("languages = %+v", langs)
  78. }
  79. }
  80. func TestRenderAddsTheLibraryFont(t *testing.T) {
  81. srv, _ := newTestServer(t)
  82. w := get(srv, URLPrefix+"system_settings.json", "alice", nil)
  83. if w.Code != http.StatusOK {
  84. t.Fatalf("status %d", w.Code)
  85. }
  86. body := w.Body.String()
  87. if strings.Index(body, `"zh-hk"`) > strings.Index(body, `"en-us"`) {
  88. t.Error("language order changed")
  89. }
  90. if !strings.Contains(body, "Settings <b>now</b>") {
  91. t.Error("HTML in strings was escaped")
  92. }
  93. var doc struct {
  94. Keys map[string]map[string]interface{} `json:"keys"`
  95. }
  96. if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {
  97. t.Fatalf("response is not JSON: %v", err)
  98. }
  99. en := doc.Keys["en-us"]
  100. if en["fontFamily"] != `"Go", Arial, sans-serif` || en["systemFont"] != "Go" || en["fontCSS"] != "fonts/fonts.css" {
  101. t.Errorf("en-us block = %v", en)
  102. }
  103. if _, ok := doc.Keys["zh-hk"]["systemFont"]; ok || doc.Keys["zh-hk"]["fontFamily"] != `"Microsoft JhengHei"` {
  104. t.Errorf("zh-hk block changed: %v", doc.Keys["zh-hk"])
  105. }
  106. // a file in a sub folder keeps its own fonts after the library one
  107. w = get(srv, URLPrefix+"sub/page.json", "alice", nil)
  108. if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {
  109. t.Fatalf("sub/page.json is not JSON: %v", err)
  110. }
  111. if doc.Keys["en-us"]["fontFamily"] != `"Go", Arial` || doc.Keys["en-us"]["fontCSS"] != "../fonts/fonts.css" {
  112. t.Errorf("sub/page.json en-us = %v", doc.Keys["en-us"])
  113. }
  114. }
  115. func TestFilesWithoutLibraryFontsAreSentAsTheyAre(t *testing.T) {
  116. srv, root := newTestServer(t)
  117. srv.opts.Fonts.SetChoice("bob", "en-us", fonts.SystemFont)
  118. raw, _ := os.ReadFile(filepath.Join(root, "system_settings.json"))
  119. if w := get(srv, URLPrefix+"system_settings.json", "bob", nil); w.Body.String() != string(raw) {
  120. t.Errorf("file changed for a user without library fonts:\n%s", w.Body.String())
  121. }
  122. if w := get(srv, URLPrefix+"broken.json", "alice", nil); w.Code != http.StatusOK || w.Body.String() != `{"keys": {,}` {
  123. t.Errorf("invalid JSON not sent as is: %d %q", w.Code, w.Body.String())
  124. }
  125. }
  126. func TestOnlyLocaleFilesAreServed(t *testing.T) {
  127. srv, _ := newTestServer(t)
  128. tests := []struct {
  129. path string
  130. code int
  131. }{
  132. {"notes.txt", http.StatusOK},
  133. {"secret.db", http.StatusNotFound},
  134. {"../locale/system_settings.json", http.StatusNotFound},
  135. {"sub/../system_settings.json", http.StatusNotFound},
  136. {"sub/..\\..\\x.json", http.StatusNotFound},
  137. {".hidden/x.json", http.StatusNotFound},
  138. {"fonts/Go/Go-Regular.ttf", http.StatusNotFound},
  139. {"fonts/defaults.json", http.StatusOK},
  140. {"missing.json", http.StatusNotFound},
  141. {"", http.StatusNotFound},
  142. {"sub/", http.StatusNotFound},
  143. }
  144. for _, tt := range tests {
  145. if w := get(srv, URLPrefix+tt.path, "alice", nil); w.Code != tt.code {
  146. t.Errorf("GET %q = %d, want %d", tt.path, w.Code, tt.code)
  147. }
  148. }
  149. r := httptest.NewRequest(http.MethodPost, URLPrefix+"notes.txt", nil)
  150. w := httptest.NewRecorder()
  151. srv.Serve(w, r, "alice")
  152. if w.Code != http.StatusMethodNotAllowed {
  153. t.Errorf("POST = %d", w.Code)
  154. }
  155. }
  156. func TestStyleSheetRevalidates(t *testing.T) {
  157. srv, _ := newTestServer(t)
  158. w := get(srv, URLPrefix+"fonts/fonts.css", "alice", nil)
  159. if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `font-family: "Go";`) {
  160. t.Fatalf("fonts.css: %d\n%s", w.Code, w.Body.String())
  161. }
  162. etag := w.Header().Get("ETag")
  163. if etag == "" {
  164. t.Fatal("no ETag")
  165. }
  166. if w := get(srv, URLPrefix+"fonts/fonts.css", "alice", map[string]string{"If-None-Match": etag}); w.Code != http.StatusNotModified {
  167. t.Errorf("revalidation = %d, want 304", w.Code)
  168. }
  169. if w := get(srv, URLPrefix+"fonts/fonts.css?preview=1&lang=en-us", "alice", nil); !strings.Contains(w.Body.String(), "AO Preview Go") {
  170. t.Errorf("preview style sheet:\n%s", w.Body.String())
  171. }
  172. if w := get(srv, URLPrefix+"fonts/slice/nope/c00.woff2", "alice", nil); w.Code != http.StatusNotFound {
  173. t.Errorf("unknown slice = %d", w.Code)
  174. }
  175. }
  176. func TestLegacyRootFallback(t *testing.T) {
  177. srv, _ := newTestServer(t)
  178. legacy := t.TempDir()
  179. os.WriteFile(filepath.Join(legacy, "old.json"), []byte(`{"keys": {}}`), 0644)
  180. srv.opts.LegacyRoot = legacy
  181. if w := get(srv, URLPrefix+"old.json", "alice", nil); w.Code != http.StatusOK {
  182. t.Errorf("legacy file = %d", w.Code)
  183. }
  184. }