Files
usaco/site/internal/explain/explain_test.go
T
adamfandClaude Opus 5.5 cae5ec8e5a
Test and publish the site / test (push) Successful in 2m15s
Test and publish the site / publish (push) Successful in 9m5s
Keep site jobs across restarts, meter Claude spend, harden admin routes
- internal/jobs replaces explain.Jobs: one registry for every kind of
  background job, with records in DATA_DIR/jobs. A job's draft is written
  before its commit, so a failed commit can be saved again (POST
  /jobs/<kind>/<key>/save) and a restart mid-commit resumes it, without
  paying Claude twice.
- Graceful shutdown: SIGTERM stops new jobs and waits SHUTDOWN_GRACE for
  running ones while still serving the pages that poll them.
- internal/usage records every Claude call's tokens and estimated cost in
  DATA_DIR/usage.jsonl; CLAUDE_MONTHLY_BUDGET refuses new jobs (429) once a
  month reaches it. The stats page shows the admin the spend.
- auth.SameOrigin refuses cross-origin writes to admin routes.
- The LeetCode importer runs the clone's script without the server's
  secrets in its environment.
- A sync that leaves HEAD where it was skips the re-index.
- docs_test.go checks README's route table against the routes, and the CLI
  page against the root README's commands.
- The repo is going private: Gitea links on the site are admin-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:10:01 +01:00

108 lines
4.0 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)
}
if !strings.Contains(System, MathRules) || !strings.Contains(System, DiagramRules) {
t.Error("System is missing the rules it shares with concepts")
}
}