package handlers import ( "context" "encoding/json" "os" "path/filepath" "strings" "testing" "time" "github.com/gin-gonic/gin" "adam-french.co.uk/usaco-site/internal/claude" "adam-french.co.uk/usaco-site/internal/concept" "adam-french.co.uk/usaco-site/internal/explain" ) // fakeConceptClaude explains everything as a Fenwick tree. If gate is set, // it waits for it to close first, so a test can catch a job mid-run. type fakeConceptClaude struct { gate chan struct{} user string } func (f *fakeConceptClaude) Model() string { return "fake-model" } func (f *fakeConceptClaude) JSON(_ context.Context, req claude.Request, out any) error { if f.gate != nil { <-f.gate } f.user = req.User *out.(*concept.Result) = concept.Result{ Slug: "fenwick-tree", Title: "Fenwick tree", Summary: "Prefix sums with updates.", Tags: []string{"range-query"}, Intuition: "Lowbits.", Snippet: "struct BIT {};", } return nil } func waitStatus(t *testing.T, r *gin.Engine, path string) explain.Status { t.Helper() for range 400 { rec := do(r, "GET", path, "", true) var s explain.Status json.Unmarshal(rec.Body.Bytes(), &s) if s.State != explain.Running { return s } time.Sleep(5 * time.Millisecond) } t.Fatalf("%s still running", path) return explain.Status{} } // newConcept starts a concept and returns the slug its job saved it under. func newConcept(t *testing.T, r *gin.Engine, body string) string { t.Helper() rec := do(r, "POST", "/usaco/api/concepts", body, true) if rec.Code != 202 { t.Fatalf("start = %d: %s", rec.Code, rec.Body) } var started struct{ ID string } json.Unmarshal(rec.Body.Bytes(), &started) s := waitStatus(t, r, "/usaco/api/concept-jobs/"+started.ID) if s.State != explain.Done { t.Fatalf("job = %+v, want done", s) } res, _ := s.Result.(map[string]any) slug, _ := res["slug"].(string) return slug } func TestConceptGuards(t *testing.T) { r, repo, _ := setup(t) if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"fenwick"}`, true); rec.Code != 503 { t.Fatalf("without Claude = %d, want 503", rec.Code) } repo.srv.Claude = &fakeConceptClaude{} if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"fenwick"}`, false); rec.Code != 401 { t.Fatalf("public start = %d, want 401", rec.Code) } if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":" "}`, true); rec.Code != 400 { t.Fatalf("empty topic = %d, want 400", rec.Code) } if rec := do(r, "POST", "/usaco/api/concepts", `{"topic":"`+strings.Repeat("a", maxNote+1)+`"}`, true); rec.Code != 400 { t.Fatalf("long topic = %d, want 400", rec.Code) } for _, path := range []string{"/usaco/api/concepts/nope", "/usaco/api/concepts/..", "/usaco/api/concepts/A"} { if rec := do(r, "GET", path, "", false); rec.Code != 404 { t.Errorf("GET %s = %d, want 404", path, rec.Code) } } } func TestConceptWritesAndCommits(t *testing.T) { r, repo, _ := setup(t) fc := &fakeConceptClaude{} repo.srv.Claude = fc code := "bool canSort(vector& nums, int k) {\n return true;\n}" body, _ := json.Marshal(conceptBody{Topic: "help explain fenwick trees", Code: code}) if slug := newConcept(t, r, string(body)); slug != "fenwick-tree" { t.Fatalf("slug = %q", slug) } if !strings.Contains(fc.user, "\nhelp explain fenwick trees\n") || !strings.Contains(fc.user, "canSort") { t.Errorf("prompt is missing the topic or code:\n%s", fc.user) } cdir := filepath.Join(repo.dir, "concepts", "fenwick-tree") snip, _ := os.ReadFile(filepath.Join(cdir, "snippet.cpp")) if string(snip) != "// concept: fenwick-tree\nstruct BIT {};\n" { t.Errorf("snippet.cpp = %q", snip) } req, _ := os.ReadFile(filepath.Join(cdir, "request.md")) if topic, got := concept.ParseRequest(string(req)); topic != "help explain fenwick trees" || got != code { t.Errorf("request.md = %q", req) } if got := repo.msg[len(repo.msg)-1]; got != "Explain concept fenwick-tree" { t.Errorf("commit = %q", got) } // The public sees the library and the page. rec := do(r, "GET", "/usaco/api/concepts", "", false) var list struct { Concepts []map[string]any `json:"concepts"` } json.Unmarshal(rec.Body.Bytes(), &list) if len(list.Concepts) != 1 || list.Concepts[0]["title"] != "Fenwick tree" || list.Concepts[0]["content"] != nil { t.Fatalf("list = %s", rec.Body) } rec = do(r, "GET", "/usaco/api/concepts/fenwick-tree", "", false) if rec.Code != 200 || !strings.Contains(rec.Body.String(), "## Intuition") || !strings.Contains(rec.Body.String(), "struct BIT") { t.Fatalf("page = %d: %s", rec.Code, rec.Body) } // The same answer to a new question never overwrites the saved one. if slug := newConcept(t, r, `{"topic":"fenwick again"}`); slug != "fenwick-tree-2" { t.Fatalf("second slug = %q, want fenwick-tree-2", slug) } if !strings.Contains(fc.user, "- fenwick-tree: Fenwick tree") { t.Errorf("prompt does not list the saved concept:\n%s", fc.user) } if req, _ := os.ReadFile(filepath.Join(cdir, "request.md")); !strings.Contains(string(req), "canSort") { t.Error("the first concept was overwritten") } // Public visitors cannot delete; the admin can. if rec := do(r, "DELETE", "/usaco/api/concepts/fenwick-tree-2", "", false); rec.Code != 401 { t.Fatalf("public delete = %d, want 401", rec.Code) } if rec := do(r, "DELETE", "/usaco/api/concepts/fenwick-tree-2", "", true); rec.Code != 200 { t.Fatalf("delete = %d: %s", rec.Code, rec.Body) } if _, err := os.Stat(filepath.Join(repo.dir, "concepts", "fenwick-tree-2")); !os.IsNotExist(err) { t.Error("the concept's directory is still there") } if got := repo.msg[len(repo.msg)-1]; got != "Forget concept fenwick-tree-2" { t.Errorf("commit = %q", got) } } func TestConceptRewrite(t *testing.T) { r, repo, _ := setup(t) repo.srv.Claude = &fakeConceptClaude{} newConcept(t, r, `{"topic":"help explain fenwick trees"}`) fc := &fakeConceptClaude{gate: make(chan struct{})} repo.srv.Claude = fc path := "/usaco/api/concepts/fenwick-tree/explain" if rec := do(r, "POST", path, `{"note":"step 2 is wrong"}`, true); rec.Code != 202 { t.Fatalf("rewrite = %d: %s", rec.Code, rec.Body) } if rec := do(r, "POST", path, `{}`, true); rec.Code != 409 { t.Fatalf("second rewrite while running = %d, want 409", rec.Code) } close(fc.gate) if s := waitStatus(t, r, path); s.State != explain.Done { t.Fatalf("rewrite job = %+v", s) } for _, want := range []string{"\nhelp explain fenwick trees", "\n# Fenwick tree", "## Snippet", "\nstep 2 is wrong"} { if !strings.Contains(fc.user, want) { t.Errorf("rewrite prompt is missing %q:\n%s", want, fc.user) } } if strings.Contains(fc.user, "") { t.Error("a rewrite should not list the concept as taken") } if _, err := os.Stat(filepath.Join(repo.dir, "concepts", "fenwick-tree-2")); !os.IsNotExist(err) { t.Error("a rewrite saved a new concept instead of replacing its own") } }