internal/httpd/fonts_test.go

e6cd75b5f28bacf51620bb531320c30fd4e66bfd
gitbay/internal/httpd/fonts_test.go history · blame · raw

89 lines · 2621 bytes

2 symbols in this file
 1package httpd
 2
 3import (
 4	"io/fs"
 5	"net/http"
 6	"net/http/httptest"
 7	"regexp"
 8	"strings"
 9	"testing"
10
11	"gitbay.org/gitbay/internal/config"
12	"gitbay.org/gitbay/internal/web"
13)
14
15// TestStylesheetFontsAreServed: every font URL the embedded stylesheet asks
16// for has a route, and that route answers with the file. The route names
17// and the @font-face URLs were once maintained by hand and drifted, so
18// gitbay.org served no web font at all (#102).
19func TestStylesheetFontsAreServed(t *testing.T) {
20	s := New(config.Default(), nil, nil)
21	byPattern := map[string]http.HandlerFunc{}
22	for _, r := range s.Routes() {
23		if r.Method == "GET" {
24			byPattern[r.Pattern] = r.Handler
25		}
26	}
27	urls := regexp.MustCompile(`url\((/static/fonts/[^)]+)\)`).FindAllSubmatch(web.StyleCSS, -1)
28	if len(urls) == 0 {
29		t.Fatal("stylesheet declares no font URLs")
30	}
31	for _, m := range urls {
32		u := string(m[1])
33		h, ok := byPattern[u]
34		if !ok {
35			t.Errorf("%s: stylesheet asks for it, route table has no route", u)
36			continue
37		}
38		rec := httptest.NewRecorder()
39		h(rec, httptest.NewRequest("GET", u, nil))
40		if rec.Code != http.StatusOK || rec.Body.Len() == 0 {
41			t.Errorf("%s: status %d, %d bytes", u, rec.Code, rec.Body.Len())
42		}
43		if ct := rec.Header().Get("Content-Type"); ct != "font/woff2" {
44			t.Errorf("%s: content-type %q", u, ct)
45		}
46	}
47}
48
49// TestLandingImagesAreServed: every file under static/img has a route
50// that answers 200 with an image or video type, and a video answers Range.
51func TestLandingImagesAreServed(t *testing.T) {
52	s := New(config.Default(), nil, nil)
53	byPattern := map[string]http.HandlerFunc{}
54	for _, r := range s.Routes() {
55		if r.Method == "GET" {
56			byPattern[r.Pattern] = r.Handler
57		}
58	}
59	entries, err := fs.ReadDir(web.ImageFS, "static/img")
60	if err != nil {
61		t.Fatal(err)
62	}
63	if len(entries) == 0 {
64		t.Fatal("no images embedded")
65	}
66	for _, e := range entries {
67		u := "/static/img/" + e.Name()
68		h, ok := byPattern[u]
69		if !ok {
70			t.Errorf("%s: no route", u)
71			continue
72		}
73		rec := httptest.NewRecorder()
74		h(rec, httptest.NewRequest("GET", u, nil))
75		ct := rec.Header().Get("Content-Type")
76		if rec.Code != http.StatusOK || !(strings.HasPrefix(ct, "image/") || strings.HasPrefix(ct, "video/")) {
77			t.Errorf("%s: %d %q", e.Name(), rec.Code, ct)
78		}
79		if strings.HasPrefix(ct, "video/") {
80			rec := httptest.NewRecorder()
81			req := httptest.NewRequest("GET", u, nil)
82			req.Header.Set("Range", "bytes=0-1")
83			h(rec, req)
84			if rec.Code != http.StatusPartialContent || rec.Body.Len() != 2 {
85				t.Errorf("%s: Range answered %d with %d bytes", e.Name(), rec.Code, rec.Body.Len())
86			}
87		}
88	}
89}