app/router_test.go
60 lines · 1593 bytes
1package app
2
3import (
4 "errors"
5 "net/http"
6 "net/http/httptest"
7 "testing"
8)
9
10// serve runs one request through the real handler.
11func serve(t *testing.T, target string) *httptest.ResponseRecorder {
12 t.Helper()
13 loadTemplates()
14 rec := httptest.NewRecorder()
15 req := httptest.NewRequest(http.MethodGet, target, nil)
16 Handler()(rec, req)
17 return rec
18}
19
20// TestCacheControlByRoute pins the header each kind of response carries, and
21// that error responses carry none, so a proxy or browser never keeps a
22// failure.
23func TestCacheControlByRoute(t *testing.T) {
24 uri := CFG.URI
25 CFG.URI = "/"
26 defer func() { CFG.URI = uri }()
27
28 orig := fetchAvatar
29 fetchAvatar = func(name string, _ rune) (string, error) {
30 if name == "missing" {
31 return "", errors.New("user not exists")
32 }
33 return "png-bytes", nil
34 }
35 defer func() { fetchAvatar = orig }()
36
37 cases := []struct {
38 target, want string
39 status int
40 }{
41 {"/stylesheet", cacheControlAssets, 200},
42 {"/favicon.ico", cacheControlAssets, 200},
43 {"/about", cacheControlPage, 200},
44 {"/api/instance", cacheControlPage, 200},
45 {"/media/emojitar/alice?type=a", cacheControlAssets, 200},
46 {"/media/emojitar/missing?type=a", "", 404},
47 {"/media/file/x@evil/f.png", "", 400},
48 {"/api/nonexistent", "", 404},
49 {"/nonexistent", "", 404},
50 }
51 for _, c := range cases {
52 rec := serve(t, c.target)
53 if rec.Code != c.status {
54 t.Errorf("%s: status %d, want %d", c.target, rec.Code, c.status)
55 }
56 if got := rec.Header().Get("Cache-Control"); got != c.want {
57 t.Errorf("%s: Cache-Control %q, want %q", c.target, got, c.want)
58 }
59 }
60}