oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "net/http"
5 "net/http/httptest"
6 "regexp"
7 "strings"
8 "testing"
9)
10
11// Every stylesheet and picture a page links is linked by its content
12// version, and fetching that URL is cached immutably; the bare path and a
13// stale version revalidate, and a matching ETag is a 304.
14func TestAssetsAreLinkedByVersionAndCachedForAYear(t *testing.T) {
15 app := newTestApp(t)
16 get := func(host, path string, header ...string) *httptest.ResponseRecorder {
17 req := httptest.NewRequest(http.MethodGet, "https://"+host+path, nil)
18 for i := 0; i+1 < len(header); i += 2 {
19 req.Header.Set(header[i], header[i+1])
20 }
21 rec := httptest.NewRecorder()
22 app.Router().ServeHTTP(rec, req)
23 return rec
24 }
25 ref := regexp.MustCompile(`(?:href|src)="(/static/[^"]+)"`)
26 for _, page := range []struct{ host, path string }{{directoryHost, "/"}, {credentialHost, "/signin"}} {
27 body := get(page.host, page.path).Body.String()
28 var checked int
29 for _, m := range ref.FindAllStringSubmatch(body, -1) {
30 url := m[1]
31 bare := strings.SplitN(url, "?", 2)[0]
32 if strings.HasSuffix(bare, ".js") || strings.HasSuffix(bare, ".mjs") || strings.HasPrefix(bare, "/static/estilo/sky/") || strings.HasPrefix(bare, "/static/estilo/fonts/") {
33 continue // scripts stay bare on purpose; estilo's URLs carry their version in the path
34 }
35 checked++
36 if !strings.Contains(url, "?v=") {
37 t.Errorf("%s%s links %s without its version", page.host, page.path, url)
38 continue
39 }
40 rec := get(page.host, url)
41 if rec.Code != 200 || rec.Header().Get("Cache-Control") != "public, max-age=31536000, immutable" {
42 t.Errorf("GET %s = %d %q", url, rec.Code, rec.Header().Get("Cache-Control"))
43 }
44 etag := rec.Header().Get("ETag")
45 if b := get(page.host, bare); b.Header().Get("Cache-Control") != "no-cache" || b.Header().Get("ETag") != etag {
46 t.Errorf("GET %s (bare) = %q %q", bare, b.Header().Get("Cache-Control"), b.Header().Get("ETag"))
47 }
48 if n := get(page.host, bare, "If-None-Match", etag); n.Code != http.StatusNotModified || n.Body.Len() != 0 {
49 t.Errorf("GET %s with its ETag = %d, want 304", bare, n.Code)
50 }
51 }
52 if checked < 4 {
53 t.Errorf("%s%s: only %d versioned assets checked", page.host, page.path, checked)
54 }
55 }
56}
57
58func TestIfNoneMatchIsWeakAndListed(t *testing.T) {
59 tag := `"0123456789abcdef"`
60 for header, want := range map[string]bool{
61 tag: true,
62 "W/" + tag: true,
63 `"other", W/` + tag: true,
64 ` "other" , ` + tag + ` `: true,
65 "*": true,
66 `"other"`: false,
67 "": false,
68 `W/"0123456789abcdeX"`: false,
69 } {
70 if got := etagMatches(header, tag); got != want {
71 t.Errorf("etagMatches(%q) = %v, want %v", header, got, want)
72 }
73 }
74}
75