Files
usaco/site/internal/explain/explain_test.go
T
adamfandClaude Opus 5.5 995b44a57a
Test and publish the site / publish (push) Successful in 8m15s
Test and publish the site / test (push) Successful in 5m51s
Add an Explain button that has Claude explain a problem
When stuck, the admin can ask Claude for an intuitive explanation of a
problem. It is committed as explain.md and shown as folded sections, so
the reader opens only as much as they need: the key observation, hints
that get stronger, the approach, a walkthrough with an SVG diagram per
step, complexity, pitfalls and a pseudocode sketch.

- internal/claude: streamed call with a JSON-schema reply, high effort,
  the server-side refusal fallback, fixed error messages and logged
  token usage. CLAUDE_API_KEY and CLAUDE_MODEL (default claude-opus-5-5);
  without a key only this feature is off.
- internal/explain: the prompt, the schema, rendering to markdown, and
  a per-problem job tracker. The request starts a job and the page polls,
  since a call outlasts nginx's 120s timeout.
- internal/statement: fetches statements from LeetCode's GraphQL API and
  USACO's problem pages. Others (Codeforces is behind Cloudflare) are
  pasted.
- problem.md holds the statement, editable from the meta editor and
  shown only to the admin. Diagrams are sanitized with DOMPurify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 20:38:15 +01:00

139 lines
4.8 KiB
Go

package explain
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/index"
)
func TestRender(t *testing.T) {
r := Result{
Observation: "The answer is monotone in the effort limit.",
Hints: []string{"Fix a limit.", "Binary search it, or run Dijkstra on max-edge."},
Approach: "Dijkstra where a path costs its largest step.",
Walkthrough: []Step{
{Caption: "Start at (0,0).", SVG: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"></svg>`},
{Caption: "Relax neighbours.", SVG: "```<svg></svg>"},
},
Complexity: "O(RC log RC).",
Pitfalls: []string{"Effort is the max, not the sum.", ""},
Sketch: "dist[0][0] = 0\npop smallest",
}
got := Render(r, "claude-opus-5-5", time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC))
want := "_Explained by claude-opus-5-5 on 19 October 2026._\n" +
"\n## Key observation\n\nThe answer is monotone in the effort limit.\n" +
"\n## Hint 1\n\nFix a limit.\n" +
"\n## Hint 2\n\nBinary search it, or run Dijkstra on max-edge.\n" +
"\n## Approach\n\nDijkstra where a path costs its largest step.\n" +
"\n## Walkthrough\n\n**Step 1.** Start at (0,0).\n\n```svg\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\"></svg>\n```\n\n" +
"**Step 2.** Relax neighbours.\n\n```svg\n<svg></svg>\n```\n" +
"\n## Complexity\n\nO(RC log RC).\n" +
"\n## Pitfalls\n\n- Effort is the max, not the sum.\n" +
"\n## Solution sketch\n\n```text\ndist[0][0] = 0\npop smallest\n```\n"
if got != want {
t.Errorf("Render =\n%s\nwant\n%s", got, want)
}
}
func TestPrompt(t *testing.T) {
p := Prompt(Input{
Name: "min-effort-path",
Statement: "# Path With Minimum Effort\n\nA hiker...",
Note: " my BFS is wrong ",
Code: &index.File{Name: "main.rs", Content: "fn main() {}\n"},
Examples: []Example{{In: "1 2\n", Out: "3\n"}, {In: "5\n"}},
})
for _, want := range []string{
"<problem name=\"min-effort-path\">\n# Path With Minimum Effort",
"<example n=\"1\">\n<input>\n1 2\n</input>\n<output>\n3\n</output>",
"<example n=\"2\">\n<input>\n5\n</input>\n</example>",
"<my_attempt file=\"main.rs\">\nfn main() {}\n</my_attempt>",
"<where_i_am_stuck>\nmy BFS is wrong\n</where_i_am_stuck>",
} {
if !strings.Contains(p, want) {
t.Errorf("prompt is missing %q:\n%s", want, p)
}
}
if q := Prompt(Input{Name: "x", Statement: "s"}); strings.Contains(q, "my_attempt") || strings.Contains(q, "stuck") {
t.Errorf("empty code and note should leave their blocks out:\n%s", q)
}
}
// The schema must describe exactly Result, or the reply would not decode.
func TestSchemaMatchesResult(t *testing.T) {
props := Schema["properties"].(map[string]any)
b, _ := json.Marshal(Result{Hints: []string{}, Walkthrough: []Step{{}}, Pitfalls: []string{}})
var fields map[string]any
json.Unmarshal(b, &fields)
for f := range fields {
if _, ok := props[f]; !ok {
t.Errorf("Result field %q is not in the schema", f)
}
}
if len(props) != len(fields) || len(Schema["required"].([]string)) != len(fields) {
t.Errorf("schema has %d properties (%d required), Result has %d fields", len(props), len(Schema["required"].([]string)), len(fields))
}
}
type fakeAsker struct{ req claude.Request }
func (f *fakeAsker) Model() string { return "fake" }
func (f *fakeAsker) JSON(_ context.Context, req claude.Request, out any) error {
f.req = req
*out.(*Result) = Result{Observation: "obs"}
return nil
}
func TestGenerate(t *testing.T) {
a := &fakeAsker{}
md, err := Generate(context.Background(), a, Input{Name: "x", Statement: "s"}, time.Now())
if err != nil {
t.Fatal(err)
}
if !strings.Contains(md, "_Explained by fake on") || !strings.Contains(md, "## Key observation\n\nobs") {
t.Errorf("unexpected markdown:\n%s", md)
}
if a.req.System != System || a.req.MaxTokens == 0 || a.req.Schema == nil {
t.Errorf("request not filled in: %+v", a.req)
}
}
func TestJobsOneAtATime(t *testing.T) {
var j Jobs
if s := j.Get("a"); s.State != Idle {
t.Fatalf("fresh state = %q, want idle", s.State)
}
release := make(chan struct{})
if !j.Start("a", func() error { <-release; return nil }) {
t.Fatal("first start refused")
}
if j.Start("a", func() error { return nil }) {
t.Fatal("second start while running accepted")
}
if !j.Start("b", func() error { return context.Canceled }) {
t.Fatal("another problem's job refused")
}
close(release)
wait := func(name string) Status {
for range 200 {
if s := j.Get(name); s.State != Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatalf("%s still running", name)
return Status{}
}
if s := wait("a"); s.State != Done || s.Finished == nil {
t.Errorf("a = %+v, want done", s)
}
if s := wait("b"); s.State != Failed || s.Error != context.Canceled.Error() {
t.Errorf("b = %+v, want the error", s)
}
}