sources_test.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package fonts
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "net/http"
  6. "net/http/httptest"
  7. "os"
  8. "path/filepath"
  9. "testing"
  10. )
  11. // withFsType returns the Go font with its OS/2 embedding permissions set
  12. func withFsType(t *testing.T, fsType uint16) []byte {
  13. t.Helper()
  14. font, err := ParseSFNT(goFont(t))
  15. if err != nil {
  16. t.Fatalf("ParseSFNT: %v", err)
  17. }
  18. os2 := append([]byte(nil), font.Tables["OS/2"]...)
  19. binary.BigEndian.PutUint16(os2[8:], fsType)
  20. font.Tables["OS/2"] = os2
  21. out, err := AssembleSFNT(font.Flavor, font.Tables)
  22. if err != nil {
  23. t.Fatalf("AssembleSFNT: %v", err)
  24. }
  25. return out
  26. }
  27. func TestNoEmbed(t *testing.T) {
  28. cases := []struct {
  29. name string
  30. fsType uint16
  31. want bool
  32. }{
  33. {"installable", 0x0000, false},
  34. {"restricted", 0x0002, true},
  35. {"preview and print", 0x0004, false},
  36. {"editable", 0x0008, false},
  37. {"restricted with a looser bit (old fonts)", 0x0006, false},
  38. {"no subsetting", 0x0100, false},
  39. {"bitmaps only", 0x0208, true},
  40. }
  41. for _, c := range cases {
  42. if got := noEmbed(c.fsType); got != c.want {
  43. t.Errorf("%s: noEmbed(%#04x) = %v, want %v", c.name, c.fsType, got, c.want)
  44. }
  45. }
  46. }
  47. func TestSourcesListsFaces(t *testing.T) {
  48. lib, _ := newTestLibrary(t)
  49. src := lib.Sources()
  50. if len(src) != 1 || src[0].Name != "Go" || len(src[0].Faces) != 1 {
  51. t.Fatalf("sources = %+v, want the one Go face", src)
  52. }
  53. f := src[0].Faces[0]
  54. if !f.Embed || f.File != "file/"+f.Key+".ttf" {
  55. t.Errorf("face = %+v, want an embeddable .ttf", f)
  56. }
  57. if len(f.Slices) != 1 || f.Slices[0].Name != "all" || f.Slices[0].Range != "" {
  58. t.Errorf("slices = %+v, want the whole font", f.Slices)
  59. }
  60. if f.WeightMin != 400 || f.Italic {
  61. t.Errorf("weight %d italic %v", f.WeightMin, f.Italic)
  62. }
  63. }
  64. func TestSourcesListsSlices(t *testing.T) {
  65. saved, savedSize := sliceMinBytes, sliceSize
  66. sliceMinBytes, sliceSize = 1, 300 // slice even the small Go font
  67. t.Cleanup(func() { sliceMinBytes, sliceSize = saved, savedSize })
  68. lib, _ := newTestLibrary(t)
  69. f := lib.Sources()[0].Faces[0]
  70. if len(f.Slices) < 2 {
  71. t.Fatalf("slices = %+v, want the cold slices", f.Slices)
  72. }
  73. for _, s := range f.Slices {
  74. if !slicePattern.MatchString(s.Name) || s.Range == "" {
  75. t.Errorf("slice %+v: want a cNN name and a unicode-range", s)
  76. }
  77. if _, err := lib.SlicePath(f.Key, s.Name); err != nil {
  78. t.Errorf("slice %s cannot be served: %v", s.Name, err)
  79. }
  80. }
  81. }
  82. func TestRestrictedFontIsNotHandedOver(t *testing.T) {
  83. lib, root := newTestLibrary(t)
  84. if err := os.WriteFile(filepath.Join(root, "Go", "Go-Regular.ttf"), withFsType(t, 0x0002), 0644); err != nil {
  85. t.Fatal(err)
  86. }
  87. if err := lib.Rescan(); err != nil {
  88. t.Fatal(err)
  89. }
  90. f := lib.Sources()[0].Faces[0]
  91. if f.Embed || f.File != "" {
  92. t.Errorf("a restricted font is offered for embedding: %+v", f)
  93. }
  94. if len(f.Slices) == 0 {
  95. t.Error("a restricted font must still be usable on screen")
  96. }
  97. if _, _, err := lib.FileData(f.Key); err != ErrNotFound {
  98. t.Errorf("FileData(restricted) = %v, want ErrNotFound", err)
  99. }
  100. rec := httptest.NewRecorder()
  101. lib.ServeFile(rec, httptest.NewRequest(http.MethodGet, "/x", nil), f.Key+".ttf")
  102. if rec.Code != http.StatusNotFound {
  103. t.Errorf("ServeFile(restricted): status %d", rec.Code)
  104. }
  105. }
  106. func TestServeFile(t *testing.T) {
  107. lib, _ := newTestLibrary(t)
  108. key := lib.Sources()[0].Faces[0].Key
  109. cases := []struct {
  110. name string
  111. want int
  112. }{
  113. {key + ".ttf", http.StatusOK},
  114. {key + ".otf", http.StatusNotFound}, // a TrueType font is not served as CFF
  115. {key, http.StatusNotFound}, // no extension
  116. {"0123456789abcdef.ttf", http.StatusNotFound},
  117. {"../../Go/Go-Regular.ttf", http.StatusNotFound},
  118. }
  119. for _, c := range cases {
  120. rec := httptest.NewRecorder()
  121. lib.ServeFile(rec, httptest.NewRequest(http.MethodGet, "/x", nil), c.name)
  122. if rec.Code != c.want {
  123. t.Errorf("%s: status %d, want %d", c.name, rec.Code, c.want)
  124. continue
  125. }
  126. if c.want != http.StatusOK {
  127. continue
  128. }
  129. if rec.Header().Get("Content-Type") != "font/ttf" {
  130. t.Errorf("%s: type %q", c.name, rec.Header().Get("Content-Type"))
  131. }
  132. if !bytes.Equal(rec.Body.Bytes(), goFont(t)) {
  133. t.Errorf("%s: the served font is not the installed file", c.name)
  134. }
  135. }
  136. }
  137. // oddGlyphs returns the Go font with every glyph one byte longer and no
  138. // padding between them, as some large fonts are stored
  139. func oddGlyphs(t *testing.T) ([]byte, int) {
  140. t.Helper()
  141. font, err := ParseSFNT(goFont(t))
  142. if err != nil {
  143. t.Fatal(err)
  144. }
  145. n := int(binary.BigEndian.Uint16(font.Tables["maxp"][4:]))
  146. offsets, err := glyphOffsets(font, n)
  147. if err != nil {
  148. t.Fatal(err)
  149. }
  150. var glyf []byte
  151. loca := make([]byte, 4*(n+1))
  152. for i := 0; i < n; i++ {
  153. binary.BigEndian.PutUint32(loca[4*i:], uint32(len(glyf)))
  154. glyf = append(glyf, font.Tables["glyf"][offsets[i]:offsets[i+1]]...)
  155. glyf = append(glyf, 0x5A) // trailing data a parser never reads
  156. }
  157. binary.BigEndian.PutUint32(loca[4*n:], uint32(len(glyf)))
  158. head := append([]byte(nil), font.Tables["head"]...)
  159. binary.BigEndian.PutUint16(head[50:], 1)
  160. font.Tables["glyf"], font.Tables["loca"], font.Tables["head"] = glyf, loca, head
  161. out, err := AssembleSFNT(font.Flavor, font.Tables)
  162. if err != nil {
  163. t.Fatal(err)
  164. }
  165. return out, n
  166. }
  167. func TestFileDataPadsOddGlyphs(t *testing.T) {
  168. lib, root := newTestLibrary(t)
  169. odd, n := oddGlyphs(t)
  170. if err := os.WriteFile(filepath.Join(root, "Go", "Go-Regular.ttf"), odd, 0644); err != nil {
  171. t.Fatal(err)
  172. }
  173. if err := lib.Rescan(); err != nil {
  174. t.Fatal(err)
  175. }
  176. key := lib.Sources()[0].Faces[0].Key
  177. file, _, err := lib.FilePath(key)
  178. if err != nil {
  179. t.Fatalf("FilePath: %v", err)
  180. }
  181. if file == filepath.Join(root, "Go", "Go-Regular.ttf") {
  182. t.Fatal("an unpadded font was handed over as it is")
  183. }
  184. data, _, err := lib.FileData(key)
  185. if err != nil {
  186. t.Fatalf("FileData: %v", err)
  187. }
  188. got, err := ParseSFNT(data)
  189. if err != nil {
  190. t.Fatalf("the padded font does not parse: %v", err)
  191. }
  192. if !glyphsAligned(got, n) {
  193. t.Fatal("the handed over font still has unaligned glyphs")
  194. }
  195. src, _ := ParseSFNT(odd)
  196. srcOff, _ := glyphOffsets(src, n)
  197. gotOff, err := glyphOffsets(got, n)
  198. if err != nil {
  199. t.Fatal(err)
  200. }
  201. for i := 0; i < n; i++ {
  202. was := src.Tables["glyf"][srcOff[i]:srcOff[i+1]]
  203. now := got.Tables["glyf"][gotOff[i]:gotOff[i+1]]
  204. if gotOff[i]%4 != 0 || !bytes.HasPrefix(now, was) || len(now)-len(was) > 3 {
  205. t.Fatalf("glyph %d: %d bytes at %d, was %d bytes", i, len(now), gotOff[i], len(was))
  206. }
  207. }
  208. if _, _, err := Inspect(got); err != nil {
  209. t.Errorf("the padded font fails inspection: %v", err)
  210. }
  211. // made once, then served from the cache
  212. again, _, _ := lib.FilePath(key)
  213. if again != file {
  214. t.Errorf("second FilePath = %q, want the cached %q", again, file)
  215. }
  216. }
  217. func TestGlyphsAligned(t *testing.T) {
  218. plain, err := ParseSFNT(goFont(t))
  219. if err != nil {
  220. t.Fatal(err)
  221. }
  222. n := int(binary.BigEndian.Uint16(plain.Tables["maxp"][4:]))
  223. odd, _ := oddGlyphs(t)
  224. oddFont, _ := ParseSFNT(odd)
  225. cases := []struct {
  226. name string
  227. font *Font
  228. want bool
  229. }{
  230. {"padded TrueType", plain, true},
  231. {"odd glyph lengths", oddFont, false},
  232. {"no glyf (CFF)", &Font{Tables: map[string][]byte{"head": plain.Tables["head"]}}, true},
  233. }
  234. for _, c := range cases {
  235. if got := glyphsAligned(c.font, n); got != c.want {
  236. t.Errorf("%s: glyphsAligned = %v, want %v", c.name, got, c.want)
  237. }
  238. }
  239. }
  240. func TestFileDataUnpacksWOFF2(t *testing.T) {
  241. lib, root := newTestLibrary(t)
  242. font, err := ParseSFNT(goFont(t))
  243. if err != nil {
  244. t.Fatal(err)
  245. }
  246. woff2, err := EncodeWOFF2(font.Flavor, font.Tables, 5)
  247. if err != nil {
  248. t.Fatalf("EncodeWOFF2: %v", err)
  249. }
  250. // a WOFF2 upload is kept as it is
  251. os.Remove(filepath.Join(root, "Go", "Go-Regular.ttf"))
  252. if err := os.WriteFile(filepath.Join(root, "Go", "Go-Regular.woff2"), woff2, 0644); err != nil {
  253. t.Fatal(err)
  254. }
  255. if err := lib.Rescan(); err != nil {
  256. t.Fatal(err)
  257. }
  258. f := lib.Sources()[0].Faces[0]
  259. if !f.Embed {
  260. t.Fatalf("an untransformed WOFF2 should be embeddable: %+v", f)
  261. }
  262. data, ext, err := lib.FileData(f.Key)
  263. if err != nil || ext != ".ttf" {
  264. t.Fatalf("FileData = %v, %q", err, ext)
  265. }
  266. got, err := ParseSFNT(data)
  267. if err != nil {
  268. t.Fatalf("the unpacked font does not parse: %v", err)
  269. }
  270. for tag, want := range font.Tables {
  271. if tag == "head" || tag == "DSIG" {
  272. continue // checkSumAdjustment is rewritten; EncodeWOFF2 may drop a signature
  273. }
  274. if !bytes.Equal(got.Tables[tag], want) {
  275. t.Errorf("table %q differs after unpacking", tag)
  276. }
  277. }
  278. }