Files
usaco/site/internal/handlers/spa_test.go
T
adamfandClaude Opus 5.5 6d956f1c76 Add the website: Go server + Vue SPA in site/, with CI
A standalone container for web_server, shaped like job-tracker: serves
/usaco/ with solved problems public and solving/skipped plus edits
(status, link, notes) for the site admin. Git is the only store: the
server clones adamf/usaco from Gitea, pulls on the push webhook, and
commits edits back. CI builds the image only when site/ changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 21:51:34 +01:00

62 lines
2.3 KiB
Go

package handlers
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
)
func TestSPA(t *testing.T) {
gin.SetMode(gin.TestMode)
dir := t.TempDir()
os.MkdirAll(filepath.Join(dir, "assets"), 0o755)
os.WriteFile(filepath.Join(dir, "index.html"), []byte("index"), 0o644)
os.WriteFile(filepath.Join(dir, "assets", "app-1a2b.js"), []byte("js"), 0o644)
os.WriteFile(filepath.Join(dir, "robots.txt"), []byte("robots"), 0o644)
// Outside dir: must never be reachable.
os.WriteFile(filepath.Join(filepath.Dir(dir), "secret"), []byte("secret"), 0o644)
r := gin.New()
r.GET("/usaco/api/health", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
r.NoRoute(SPA(dir, "/usaco"))
cases := []struct {
method, path string
code int
body string
cache string
}{
{"GET", "/usaco/", 200, "index", "no-cache"},
{"GET", "/usaco/p/moocast", 200, "index", "no-cache"},
{"GET", "/usaco/stats/anything", 200, "index", "no-cache"},
{"GET", "/usaco/assets/app-1a2b.js", 200, "js", "public, max-age=31536000, immutable"},
{"GET", "/usaco/robots.txt", 200, "robots", "no-cache"},
{"GET", "/usaco/api/health", 200, "ok", ""},
{"GET", "/usaco/api/nope", 404, `{"error":"not found"}`, ""},
{"GET", "/usaco/assets/gone.js", 404, "404 page not found", ""},
// net/http refuses a path that climbs, before anything is read.
{"GET", "/usaco/../secret", 400, "invalid URL path\n", ""},
{"GET", "/usaco/%2e%2e/secret", 400, "invalid URL path\n", ""},
{"POST", "/usaco/p/moocast", 404, `{"error":"not found"}`, ""},
{"GET", "/elsewhere", 404, `{"error":"not found"}`, ""},
}
for _, c := range cases {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(c.method, c.path, nil))
if rec.Code != c.code || rec.Body.String() != c.body || rec.Header().Get("Cache-Control") != c.cache {
t.Errorf("%s %s = %d %q (cache %q), want %d %q (cache %q)",
c.method, c.path, rec.Code, rec.Body, rec.Header().Get("Cache-Control"), c.code, c.body, c.cache)
}
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest("GET", "/usaco", nil))
if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/usaco/" {
t.Errorf("GET /usaco = %d to %q, want a redirect to /usaco/", rec.Code, rec.Header().Get("Location"))
}
}