showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
build_test.go
11.6 KB · 308 lines
1package build23import (4 "bytes"5 "context"6 "encoding/json"7 "flag"8 "fmt"9 "image"10 "image/png"11 "io"12 "log/slog"13 "net/http"14 "net/http/cgi"15 "net/http/httptest"16 "os"17 "os/exec"18 "path/filepath"19 "regexp"20 "strconv"21 "strings"22 "testing"23 "time"2425 "daum.dev/showcase/internal/config"26 "daum.dev/showcase/internal/gitea"27)2829var (30 statusRe = regexp.MustCompile(`/commits/[^/]+/status$`)31 // paths the fake Gitea answers with 401, like Gitea 28's packages API32 needToken = map[string]bool{}33 update = flag.Bool("update", false, "rewrite golden files")34 keep = flag.String("keep", "", "also render the fixture site into this directory")35)3637// gitEnv isolates fixture commits from the user's git config (no signing).38var gitEnv = []string{39 "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1",40 "GIT_AUTHOR_NAME=Daniel", "GIT_AUTHOR_EMAIL=d@example.com",41 "GIT_COMMITTER_NAME=Daniel", "GIT_COMMITTER_EMAIL=d@example.com",42}4344func run(t *testing.T, dir, date string, args ...string) {45 t.Helper()46 cmd := exec.Command("git", args...)47 cmd.Dir = dir48 cmd.Env = append(os.Environ(), gitEnv...)49 cmd.Env = append(cmd.Env, "GIT_AUTHOR_DATE="+date, "GIT_COMMITTER_DATE="+date)50 if out, err := cmd.CombinedOutput(); err != nil {51 t.Fatalf("git %v: %v\n%s", args, err, out)52 }53}5455// fixtureRepos creates bare repos under root/daniel: repo-a from56// testdata/repo-a in two commits with fixed dates, and an empty repo-b.57func fixtureRepos(t *testing.T) string {58 root := t.TempDir()59 work := filepath.Join(root, "work")60 if err := os.CopyFS(work, os.DirFS("../../testdata/repo-a")); err != nil {61 t.Fatal(err)62 }63 os.WriteFile(filepath.Join(work, "data.bin"), []byte("bin\x00ary"), 0o644)64 os.WriteFile(filepath.Join(work, "big.txt"), bytes.Repeat([]byte("0123456789abcde\n"), 40<<10), 0o644)65 run(t, work, "", "init", "-q", "-b", "main")66 run(t, work, "", "add", "-A", ":!CHANGELOG.md")67 run(t, work, "2026-06-01T10:00:00Z", "commit", "-q", "--no-gpg-sign", "-m", "Initial commit")68 // a few months of small commits, so the activity views have a shape69 start := time.Date(2026, 6, 8, 9, 0, 0, 0, time.UTC)70 subjects := []string{"Tidy the guide", "Document the flags", "Fix a typo in the notes", "Add a section on deploys", "Explain the image tags"}71 var notes strings.Builder72 for i, day := range []int{0, 1, 9, 23, 30, 31, 58, 59, 61, 86, 100, 114, 115, 116, 128, 135, 142, 149, 156, 156, 156, 156, 157, 158, 160} {73 fmt.Fprintf(¬es, "- note %d\n", i+1)74 os.WriteFile(filepath.Join(work, "docs/notes.md"), []byte("# Notes\n\n"+notes.String()), 0o644)75 run(t, work, "", "add", "docs/notes.md")76 when := start.AddDate(0, 0, day).Add(time.Duration(i) * 7 * time.Minute)77 run(t, work, when.Format(time.RFC3339), "commit", "-q", "--no-gpg-sign", "-m", subjects[i%len(subjects)])78 }79 os.WriteFile(filepath.Join(work, "CHANGELOG.md"), []byte("# Changes\n"), 0o644)80 os.WriteFile(filepath.Join(work, "cmd/hello/main.go"), []byte("package main\n\nimport \"fmt\"\n\nfunc main() { fmt.Println(\"hello, world\") }\n"), 0o644)81 os.WriteFile(filepath.Join(work, "data.bin"), []byte("bin\x00ary2"), 0o644)82 run(t, work, "", "add", "-A")83 run(t, work, "2026-11-21T08:30:00Z", "commit", "-q", "--no-gpg-sign", "-m", "Add changelog", "-m", "With a body.")84 run(t, work, "", "tag", "v0.1.0", "HEAD~26")85 run(t, work, "2026-11-21T09:00:00Z", "tag", "-a", "-m", "v0.2.0", "v0.2.0")86 run(t, work, "", "branch", "feature/flag")87 run(t, root, "", "clone", "-q", "--bare", work, "daniel/repo-a.git")88 run(t, root, "", "init", "-q", "--bare", "-b", "main", "daniel/repo-b.git")89 return root90}9192// fakeGitea serves testdata/gitea/<path>.json, a generated avatar and the93// fixture repos over smart HTTP. It fails the test if a request carries94// credentials.95func fakeGitea(t *testing.T) *httptest.Server {96 t.Helper()97 root := fixtureRepos(t)98 rev, err := exec.Command("git", "--git-dir", filepath.Join(root, "daniel/repo-a.git"), "rev-parse", "main").Output()99 if err != nil {100 t.Fatal(err)101 }102 registry := fakeRegistry(strings.TrimSpace(string(rev)))103 gitBackend := &cgi.Handler{104 Path: "git",105 Args: []string{"http-backend"},106 Env: append([]string{"GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"}, gitEnv...),107 }108 if p, err := exec.LookPath("git"); err == nil {109 gitBackend.Path = p110 }111 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {112 // the registry's own anonymous pull token is the one allowed header113 if a := r.Header.Get("Authorization"); a != "" && !(strings.HasPrefix(r.URL.Path, "/v2/") && a == "Bearer "+anonToken) || r.Header.Get("Cookie") != "" {114 t.Errorf("request to %s carried credentials", r.URL)115 }116 if strings.HasPrefix(r.URL.Path, "/v2/") {117 registry(w, r)118 return119 }120 if needToken[r.URL.Path] {121 http.Error(w, `{"message":"token is required"}`, http.StatusUnauthorized)122 return123 }124 if strings.Contains(r.URL.Path, ".git/") {125 gitBackend.ServeHTTP(w, r)126 return127 }128 if strings.HasPrefix(r.URL.Path, "/avatars/") {129 var buf bytes.Buffer130 png.Encode(&buf, image.NewGray(image.Rect(0, 0, 2, 2)))131 w.Write(buf.Bytes())132 return133 }134 if r.URL.Path == "/api/v1/repos/daniel/repo-a/commits" {135 signedCommits(t, filepath.Join(root, "daniel/repo-a.git"), w, r)136 return137 }138 p := statusRe.ReplaceAllString(r.URL.Path, "/status") // any commit's status139 b, err := os.ReadFile(filepath.Join("../../testdata/gitea", filepath.FromSlash(p)+".json"))140 if err != nil {141 http.NotFound(w, r)142 return143 }144 w.Header().Set("Content-Type", "application/json")145 w.Write(b)146 }))147 t.Cleanup(srv.Close)148 return srv149}150151// signedCommits answers Gitea's commit list for repo-a from the fixture152// repo, with Gitea's verdict on each: the newest commit is verified (SSH),153// the next signed but unverified, the third verified (GPG), the rest154// unsigned. The signer's email must never reach a page.155func signedCommits(t *testing.T, gitDir string, w http.ResponseWriter, r *http.Request) {156 q := r.URL.Query()157 limit, _ := strconv.Atoi(q.Get("limit"))158 page, _ := strconv.Atoi(q.Get("page"))159 if q.Get("verification") != "true" || q.Get("stat") != "false" || limit < 1 || page < 1 {160 t.Errorf("commits query %q", r.URL.RawQuery)161 }162 skip := (page - 1) * limit163 out, err := exec.Command("git", "--git-dir", gitDir, "log", "--format=%H", "--skip", strconv.Itoa(skip), "-n", strconv.Itoa(limit), "--end-of-options", q.Get("sha")).Output()164 if err != nil {165 t.Errorf("commits: %v", err)166 }167 type obj = map[string]any168 signer := obj{"name": "daniel", "email": "signer-should-never-render@example.com"}169 cs := []obj{}170 for i, h := range strings.Fields(string(out)) {171 v := obj{"verified": false, "reason": "gpg.error.not_signed_commit", "signature": ""}172 switch skip + i {173 case 0:174 v = obj{"verified": true, "reason": "daniel / SHA256:Qm9vZ3VzRmluZ2VycHJpbnRGb3JUZXN0c09ubHkxMjM", "signature": "-----BEGIN SSH SIGNATURE-----", "signer": signer}175 case 1:176 v = obj{"verified": false, "reason": "gpg.error.no_gpg_keys_found", "signature": "-----BEGIN SSH SIGNATURE-----"}177 case 2:178 v = obj{"verified": true, "reason": "daniel / 0123456789ABCDEF", "signature": "-----BEGIN PGP SIGNATURE-----", "signer": signer}179 }180 cs = append(cs, obj{"sha": h, "commit": obj{"message": "x", "verification": v}})181 }182 w.Header().Set("Content-Type", "application/json")183 json.NewEncoder(w).Encode(cs)184}185186func testBuilder(t *testing.T) *Builder {187 srv := fakeGitea(t)188 cfg := &config.Config{189 GiteaURL: srv.URL,190 User: "daniel",191 SiteURL: "https://code.danieldaum.net",192 Repos: []string{"repo-b", "leaky", "missing", "repo-a"},193 Images: []string{"repo-a"},194 MaxCommits: 50,195 Theme: "moss",196 }197 now := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC)198 return &Builder{199 Cfg: cfg,200 Gitea: gitea.New(srv.URL, cfg.User),201 Data: t.TempDir(),202 Now: func() time.Time { return now },203 Log: slog.New(slog.NewTextHandler(io.Discard, nil)),204 }205}206207func checkGolden(t *testing.T, dir, rel string) []byte {208 t.Helper()209 got, err := os.ReadFile(filepath.Join(dir, rel))210 if err != nil {211 t.Fatal(err)212 }213 golden := filepath.Join("../../testdata/golden", rel)214 if *update {215 if err := os.MkdirAll(filepath.Dir(golden), 0o755); err != nil {216 t.Fatal(err)217 }218 if err := os.WriteFile(golden, got, 0o644); err != nil {219 t.Fatal(err)220 }221 }222 want, err := os.ReadFile(golden)223 if err != nil {224 t.Fatal(err)225 }226 if !bytes.Equal(got, want) {227 t.Errorf("%s differs from %s; run `just golden` and review the diff", rel, golden)228 }229 bad := []string{"leaky", "should never render", "should-never-render", "unlisted-image", "sha256:0123", "<script>", "tailnet.example"}230 if !strings.Contains(rel, "/blob/") && !strings.Contains(rel, "commit") { // source text, escaped231 bad = append(bad, "javascript:", "tracker.example")232 }233 for _, bad := range bad {234 if bytes.Contains(got, []byte(bad)) {235 t.Errorf("%s contains %q", rel, bad)236 }237 }238 return got239}240241func TestSiteGolden(t *testing.T) {242 dir := t.TempDir()243 if *keep != "" {244 dir = *keep245 os.RemoveAll(dir)246 os.MkdirAll(dir, 0o755)247 }248 if err := testBuilder(t).Render(context.Background(), dir); err != nil {249 t.Fatal(err)250 }251 for _, rel := range []string{252 "index.html", "repos/index.html", "repo-a/index.html", "repo-b/index.html",253 "repo-a/tree/docs/index.html", "repo-a/tree/cmd/hello/index.html",254 "repo-a/blob/cmd/hello/main.go.html", "repo-a/blob/README.md.html",255 "repo-a/blob/docs/logo.png.html", "repo-a/blob/data.bin.html", "repo-a/blob/big.txt.html",256 "repo-a/log/index.html", "repo-b/log/index.html",257 "repo-a/branches/index.html", "repo-a/tags/index.html",258 "repo-a/releases/index.html", "repo-a/issues/index.html", "repo-b/issues/index.html", "repo-a/pulls/index.html", "repo-a/packages/index.html",259 "repo-b/releases/index.html",260 } {261 checkGolden(t, dir, rel)262 }263 commits, _ := filepath.Glob(filepath.Join(dir, "repo-a/commit/*/index.html"))264 if len(commits) != 27 {265 t.Fatalf("want 27 commit pages, got %d", len(commits))266 }267 for _, c := range commits {268 b, _ := os.ReadFile(c)269 switch {270 case bytes.Contains(b, []byte(">Add changelog</h2>")):271 os.WriteFile(filepath.Join(dir, "repo-a/commit-latest.html"), b, 0o644) // hash-free golden name; a copy, so -keep output keeps the page272 checkGolden(t, dir, "repo-a/commit-latest.html")273 case bytes.Contains(b, []byte(">Initial commit</h2>")) && !bytes.Contains(b, []byte("Diff truncated")): // 40k lines of big.txt274 t.Error("initial commit page: big.txt diff should be truncated")275 }276 }277 for _, f := range []string{"docs/logo.png", "go.mod"} {278 want, _ := os.ReadFile(filepath.Join("../../testdata/repo-a", f))279 got, err := os.ReadFile(filepath.Join(dir, "repo-a/raw", f))280 if err != nil || (want != nil && !bytes.Equal(got, want)) {281 t.Errorf("raw %s: wrong or missing (%v)", f, err)282 }283 }284 for _, f := range []string{"static/style.css", "static/avatar-65da4c2ded.png", "static/theme.js", "static/fonts/geistpixel/GeistPixel-Square.woff2", "static/fonts/geistmono/GeistMono-Regular.woff2"} {285 if _, err := os.Stat(filepath.Join(dir, f)); err != nil {286 t.Error(err)287 }288 }289 for _, f := range []string{"leaky", "missing"} {290 if _, err := os.Stat(filepath.Join(dir, f)); err == nil {291 t.Errorf("%s was rendered", f)292 }293 }294}295296func TestPackagesNeedToken(t *testing.T) {297 needToken["/api/v1/packages/daniel"] = true298 defer delete(needToken, "/api/v1/packages/daniel")299 dir := t.TempDir()300 if err := testBuilder(t).Render(context.Background(), dir); err != nil {301 t.Fatalf("build failed when the packages API wants a token: %v", err)302 }303 // images still come from the registry; API-only packages (npm) are gone304 b, _ := os.ReadFile(filepath.Join(dir, "repo-a/packages/index.html"))305 if !bytes.Contains(b, []byte("code.danieldaum.net/daniel/repo-a")) || bytes.Contains(b, []byte("@daniel/repo-a")) {306 t.Error("packages page should list the registry image and nothing from the API")307 }308}