internal/httpd/fonts_test.go

v1.33.0
gitbay/internal/httpd/fonts_test.go history · blame · raw

79 lines · 2253 bytes

 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)
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 type and the stylesheet's cache policy.
51func TestLandingImagesAreServed(t *testing.T) {
52	s := New(config.Default(), 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		if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Header().Get("Content-Type"), "image/") {
76			t.Errorf("%s: %d %s", e.Name(), rec.Code, rec.Header().Get("Content-Type"))
77		}
78	}
79}