Run and lint solutions on the site
Test and publish the site / test (push) Successful in 1m23s
Test and publish the site / publish (push) Failing after 4m22s

A new admin-only solve page, /p/<name>/solve, edits a problem's code in
C++ or Python (a dropdown switches between them), runs it on custom
input or against the saved tests with per-test verdicts (AC, WA, RE,
TLE, unchecked) and compile errors, marks lint diagnostics in the
editor, and saves the code back as a commit ("Edit <name>"). Drafts
stay in the browser per problem and language until saved. LeetCode
problems are C++ only, since their tests run through driver.h.

Code never runs in the site, which holds the Claude, Gitea and S3
secrets. A separate runner service (cmd/usacorunner, Dockerfile.runner)
does it in a container meant to have no environment, an internal-only
network, a read-only root apart from /tmp, and memory, CPU and pids
limits, with tini to reap orphans. Runs copy the CLI: the same g++
flags with -DLOCAL and the repo's headers, <io>.in on disk and on
stdin, <io>.out or stdout as the output, and usaco test's comparison.
Unlike the CLI they have CPU, memory, file and wall-clock limits.

C++ lint is g++'s warnings plus clang-tidy with a new .clang-tidy
(bugprone, performance and a few readability checks; template.cpp is
clean). Python lint is a syntax check plus ruff. template.py is the
Python starter, with a stdio() helper like template.rs's.

CI builds, smoke-tests and rolls out the runner image before the site.
The web_server stack needs a usaco-runner service before that rollout
can succeed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-20 11:24:22 +01:00
co-authored by Claude Opus 5.5
parent 107ecab9da
commit c972fa9fd9
33 changed files with 4477 additions and 23 deletions
+26 -9
View File
@@ -1,7 +1,8 @@
// Package handlers is the site's REST API: the problem list and pages (public
// for solved problems, everything for the admin), the admin's edits, the
// Claude explanations (explain.go) and recording reviews (review.go), and
// the Gitea webhook that tells the server to pull.
// Claude explanations (explain.go) and recording reviews (review.go), the
// solve page's code editing and runs (run.go), and the Gitea webhook that
// tells the server to pull.
package handlers
import (
@@ -43,6 +44,9 @@ type Server struct {
// Pull asks for a sync. It must not block: the webhook answers at once
// and the sync runs in the background.
Pull func()
// Dir is the clone's work tree. The solve page reads solutions and tests
// from it rather than the index, which truncates big files.
Dir string
// Claude writes the explanations; nil when CLAUDE_API_KEY is not set,
// which turns only that feature off.
Claude explain.Asker
@@ -55,6 +59,9 @@ type Server struct {
// Audio keeps review recordings for playback; nil when the S3_*
// settings are not given, and the recordings are then thrown away.
Audio AudioStore
// Runner compiles, runs and lints code for the solve page; nil when
// RUNNER_URL is not set, which turns only running and linting off.
Runner Runner
idx atomic.Pointer[index.Index]
// Separate, so a review and an explanation of one problem can run at
@@ -97,6 +104,10 @@ func (s *Server) Routes(api *gin.RouterGroup) {
admin.GET("/problems/:name/review", s.reviewStatus)
admin.GET("/problems/:name/reviews/:id/audio", s.reviewAudio)
admin.DELETE("/problems/:name/reviews/:id", s.deleteReview)
admin.GET("/problems/:name/code", s.getCode)
admin.PUT("/problems/:name/code", s.saveCode)
admin.POST("/problems/:name/run", s.run)
admin.POST("/problems/:name/lint", s.lint)
api.POST("/hooks/gitea", s.webhook)
}
@@ -202,15 +213,21 @@ func (e *requestError) Error() string { return e.msg }
func (s *Server) mutate(ctx *gin.Context, name, message string, edit func(dir string) error) {
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
defer cancel()
err := s.Repo.Mutate(c, message, edit)
if err := s.Repo.Mutate(c, message, edit); err != nil {
editFailed(ctx, message, err)
return
}
if p, ok := s.Index().Problems[name]; ok {
ctx.JSON(http.StatusOK, p)
} else {
ctx.JSON(http.StatusOK, gin.H{})
}
}
// editFailed answers for an edit Mutate refused or could not save.
func editFailed(ctx *gin.Context, message string, err error) {
var re *requestError
switch {
case err == nil:
if p, ok := s.Index().Problems[name]; ok {
ctx.JSON(http.StatusOK, p)
} else {
ctx.JSON(http.StatusOK, gin.H{})
}
case errors.As(err, &re):
ctx.JSON(re.status, gin.H{"error": re.msg})
case errors.Is(err, repo.ErrRejected):
+542
View File
@@ -0,0 +1,542 @@
package handlers
import (
"context"
"errors"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/runner"
)
// Runner is the part of runner.Client the handlers use, so tests can fake
// the runner service.
type Runner interface {
Run(ctx context.Context, req runner.RunRequest) (runner.RunResponse, error)
Lint(ctx context.Context, req runner.LintRequest) (runner.LintResponse, error)
}
// Caps on what the solve page sends. The source cap is far above any real
// solution; the body cap leaves room for a custom input beside it.
const (
maxSource = 256 << 10
maxRunBody = 512 << 10
maxRunTests = 16 << 20
)
// The runner's own deadline is below the client's 90 seconds; these sit
// between, so a slow run comes back as the runner's answer.
const (
runTimeout = 80 * time.Second
lintTimeout = 30 * time.Second
)
// The repo root files a C++ build may include. The CLI builds with the root
// on the include path and LOCAL defined, so a solution may include
// debugging.h, and a LeetCode one leetcode.h and its driver.h; the runner
// gets them all so the same source compiles there.
var rootHeaders = []string{"debugging.h", "leetcode.h"}
// codeFile is one language's source on the solve page.
type codeFile struct {
Path string `json:"path"`
Source string `json:"source"`
// Saved is false for a starter, which exists only in the browser until
// the admin saves it.
Saved bool `json:"saved"`
}
// layout is what the solve page needs to know about a problem dir. It is
// read from the clone each time: the index truncates files, and a solution
// saved here must come back in full.
type layout struct {
dir string
io string
leetcode bool
cpp string // "main.cpp" when it exists
python string // "main.py", else "sol.py", when one exists
}
// readLayout looks at the problem's dir as the CLI would. Reads happen
// outside the repo's lock, so a sync may be resetting the tree underneath;
// at worst a request sees a file missing and the admin retries.
func (s *Server) readLayout(status, name string) (*layout, error) {
l := &layout{dir: filepath.Join(s.Dir, status, name)}
entries, err := os.ReadDir(l.dir)
if err != nil {
return nil, err
}
have := map[string]bool{}
for _, e := range entries {
if e.IsDir() {
continue
}
have[e.Name()] = true
// The first *.in, as detect_io picks it.
if base, ok := strings.CutSuffix(e.Name(), ".in"); ok && l.io == "" {
l.io = base
}
}
// With no sample, `usaco new` wires the source to the problem's name.
if l.io == "" {
l.io = name
}
l.leetcode = have["driver.h"]
if have["main.cpp"] {
l.cpp = "main.cpp"
}
switch {
case have["main.py"]:
l.python = "main.py"
case have["sol.py"]:
l.python = "sol.py"
}
return l, nil
}
func (l *layout) languages() []string {
// A LeetCode problem's tests only run through its C++ driver.h.
if l.leetcode {
return []string{runner.Cpp}
}
return []string{runner.Cpp, runner.Python}
}
func (l *layout) allows(lang string) bool {
for _, x := range l.languages() {
if x == lang {
return true
}
}
return false
}
// getCode is the solve page's starting point: each language's saved source,
// or a starter wired to the problem's io name the way `usaco new` would.
func (s *Server) getCode(ctx *gin.Context) {
p, ok := s.lookup(ctx, true)
if !ok {
return
}
l, err := s.readLayout(p.Status, p.Name)
if err != nil {
log.Printf("[code] %s: %v", p.Name, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
return
}
def := runner.Cpp
if l.cpp == "" && l.python != "" {
def = runner.Python
}
code := map[string]codeFile{}
for _, lang := range l.languages() {
f, err := s.code(l, lang)
if err != nil {
var re *requestError
if errors.As(err, &re) {
ctx.JSON(re.status, gin.H{"error": re.msg})
return
}
log.Printf("[code] %s: %v", p.Name, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
return
}
code[lang] = f
}
ctx.JSON(http.StatusOK, gin.H{
"io": l.io,
"leetcode": l.leetcode,
"languages": l.languages(),
"default": def,
"runner": s.Runner != nil,
"code": code,
})
}
// code is one language's saved source, or its starter.
func (s *Server) code(l *layout, lang string) (codeFile, error) {
saved := l.cpp
if lang == runner.Python {
saved = l.python
}
if saved != "" {
src, err := readCapped(filepath.Join(l.dir, saved), maxSource)
if errors.Is(err, errTooBig) {
return codeFile{}, &requestError{http.StatusUnprocessableEntity, saved + " is over 256 KB, too big to edit here"}
}
return codeFile{Path: saved, Source: src, Saved: true}, err
}
if lang == runner.Python {
return codeFile{Path: "main.py", Source: s.pythonStarter(l.io)}, nil
}
return codeFile{Path: "main.cpp", Source: s.cppStarter(l.io)}, nil
}
// Used only when the repo has no template, which it always should.
const (
fallbackCpp = "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n cin.tie(0)->sync_with_stdio(0);\n}\n"
fallbackPy = "def main():\n n = int(input())\n print(n)\n\n\nmain()\n"
)
// cppStarter is fresh_main's C++ case: template.cpp with the STDIO call
// added as the first line of main. The io name is quoted rather than pasted
// in as sed does, which is the same for every name the CLI makes.
func (s *Server) cppStarter(io string) string {
b, err := os.ReadFile(filepath.Join(s.Dir, "template.cpp"))
if err != nil {
return fallbackCpp
}
lines := strings.SplitAfter(string(b), "\n")
for i, line := range lines {
if strings.TrimSuffix(line, "\n") == "int main() {" {
lines[i] = line + " STDIO(" + strconv.Quote(io) + ");\n"
}
}
return strings.Join(lines, "")
}
// The call in main, indented, and not the stdio("name") in the comment
// that explains it.
var stdioCall = regexp.MustCompile(`(?m)^[ \t]+stdio\("[^"]*"\)`)
// pythonStarter is template.py with its stdio("...") call pointed at io, as
// fresh_main does for template.rs.
func (s *Server) pythonStarter(io string) string {
b, err := os.ReadFile(filepath.Join(s.Dir, "template.py"))
if err != nil {
return fallbackPy
}
return stdioCall.ReplaceAllStringFunc(string(b), func(call string) string {
indent := call[:strings.Index(call, "stdio(")]
return indent + "stdio(" + strconv.Quote(io) + ")"
})
}
var errTooBig = errors.New("file too big")
// readCapped reads a whole file, refusing one over max rather than cutting
// it: a cut solution saved back would lose its end.
func readCapped(path string, max int64) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
b, err := io.ReadAll(io.LimitReader(f, max+1))
if err != nil {
return "", err
}
if int64(len(b)) > max {
return "", errTooBig
}
return string(b), nil
}
type codeBody struct {
Lang string `json:"lang"`
Source string `json:"source"`
// Mode and Input are for runs only.
Mode string `json:"mode"`
Input string `json:"input"`
}
// readCode reads and checks a solve page request against the problem's
// layout. It has answered when ok is false.
func (s *Server) readCode(ctx *gin.Context) (body codeBody, l *layout, ok bool) {
p, ok := s.lookup(ctx, true)
if !ok {
return body, nil, false
}
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxRunBody)
if err := ctx.ShouldBindJSON(&body); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the request is over 512 KB"})
return body, nil, false
}
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return body, nil, false
}
if len(body.Source) > maxSource {
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the source is over 256 KB"})
return body, nil, false
}
if body.Lang != runner.Cpp && body.Lang != runner.Python {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "lang must be cpp or python"})
return body, nil, false
}
l, err := s.readLayout(p.Status, p.Name)
if err != nil {
log.Printf("[code] %s: %v", p.Name, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
return body, nil, false
}
if !l.allows(body.Lang) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "a LeetCode problem runs through its C++ driver only"})
return body, nil, false
}
return body, l, true
}
// headers are the files written next to a C++ source; Python needs none.
func (s *Server) headers(l *layout, lang string) (map[string]string, error) {
if lang != runner.Cpp {
return nil, nil
}
files := map[string]string{}
add := func(path string) error {
src, err := readCapped(path, maxSource)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
files[filepath.Base(path)] = src
return nil
}
for _, h := range rootHeaders {
if err := add(filepath.Join(s.Dir, h)); err != nil {
return nil, err
}
}
if l.leetcode {
if err := add(filepath.Join(l.dir, "driver.h")); err != nil {
return nil, err
}
}
return files, nil
}
// runnerConfigured answers 503 when there is no runner to ask.
func (s *Server) runnerConfigured(ctx *gin.Context) bool {
if s.Runner == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "the code runner is not configured on this server (RUNNER_URL)"})
return false
}
return true
}
// run compiles the source once and runs it on the saved tests or on one
// custom input, and answers with the runner's verdicts as they are.
func (s *Server) run(ctx *gin.Context) {
if !s.runnerConfigured(ctx) {
return
}
body, l, ok := s.readCode(ctx)
if !ok {
return
}
var tests []runner.Test
switch body.Mode {
case "tests":
var err error
if tests, err = readRunTests(l); err != nil {
var re *requestError
if errors.As(err, &re) {
ctx.JSON(re.status, gin.H{"error": re.msg})
return
}
log.Printf("[run] %s: %v", filepath.Base(l.dir), err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the tests could not be read"})
return
}
case "custom":
tests = []runner.Test{{Name: "custom", Input: body.Input}}
default:
ctx.JSON(http.StatusBadRequest, gin.H{"error": "mode must be tests or custom"})
return
}
files, err := s.headers(l, body.Lang)
if err != nil {
log.Printf("[run] %s: %v", filepath.Base(l.dir), err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the headers could not be read"})
return
}
c, cancel := context.WithTimeout(ctx.Request.Context(), runTimeout)
defer cancel()
res, err := s.Runner.Run(c, runner.RunRequest{Lang: body.Lang, Source: body.Source, Files: files, IO: l.io, Tests: tests})
if err != nil {
log.Printf("[run] %s: %v", filepath.Base(l.dir), err)
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, res)
}
// readRunTests is what `usaco test` runs: tests/N.in, with N.out as the
// expected output when it was saved, in sort -V order. A problem with no
// tests runs its sample instead, unchecked: its <io>.out is the last run's
// output, not an answer. Files are read whole, unlike the index's copies.
func readRunTests(l *layout) ([]runner.Test, error) {
tdir := filepath.Join(l.dir, "tests")
entries, err := os.ReadDir(tdir)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
var names []string
for _, e := range entries {
if base, ok := strings.CutSuffix(e.Name(), ".in"); ok && !e.IsDir() {
names = append(names, base)
}
}
sort.Slice(names, func(i, j int) bool { return naturalLess(names[i], names[j]) })
tests := []runner.Test{}
total := 0
read := func(path string) (string, error) {
src, err := readCapped(path, maxRunTests)
if errors.Is(err, errTooBig) || total+len(src) > maxRunTests {
return "", &requestError{http.StatusRequestEntityTooLarge, "the saved tests are over 16 MB, too big to run from the site"}
}
total += len(src)
return src, err
}
for _, name := range names {
in, err := read(filepath.Join(tdir, name+".in"))
if err != nil {
return nil, err
}
t := runner.Test{Name: name, Input: in}
out, err := read(filepath.Join(tdir, name+".out"))
switch {
case err == nil:
t.Output = &out
case !os.IsNotExist(err):
return nil, err
}
tests = append(tests, t)
}
if len(tests) > 0 {
return tests, nil
}
sample, err := read(filepath.Join(l.dir, l.io+".in"))
switch {
case os.IsNotExist(err):
// Nothing to run against: the runner still compiles, which is
// worth seeing.
return tests, nil
case err != nil:
return nil, err
case strings.TrimSpace(sample) == "":
return tests, nil
}
return []runner.Test{{Name: "sample", Input: sample}}, nil
}
// naturalLess orders like sort -V for test names: runs of digits compare as
// numbers, so 2 comes before 10.
func naturalLess(a, b string) bool {
for a != "" && b != "" {
da, db := digitRun(a), digitRun(b)
if da > 0 && db > 0 {
na, nb := strings.TrimLeft(a[:da], "0"), strings.TrimLeft(b[:db], "0")
if len(na) != len(nb) {
return len(na) < len(nb)
}
if na != nb {
return na < nb
}
a, b = a[da:], b[db:]
continue
}
if a[0] != b[0] {
return a[0] < b[0]
}
a, b = a[1:], b[1:]
}
return len(a) < len(b)
}
func digitRun(s string) int {
n := 0
for n < len(s) && s[n] >= '0' && s[n] <= '9' {
n++
}
return n
}
// lint returns the source's diagnostics, for the editor's squiggles.
func (s *Server) lint(ctx *gin.Context) {
if !s.runnerConfigured(ctx) {
return
}
body, l, ok := s.readCode(ctx)
if !ok {
return
}
files, err := s.headers(l, body.Lang)
if err != nil {
log.Printf("[lint] %s: %v", filepath.Base(l.dir), err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the headers could not be read"})
return
}
c, cancel := context.WithTimeout(ctx.Request.Context(), lintTimeout)
defer cancel()
res, err := s.Runner.Lint(c, runner.LintRequest{Lang: body.Lang, Source: body.Source, Files: files})
if err != nil {
log.Printf("[lint] %s: %v", filepath.Base(l.dir), err)
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, res)
}
// saveCode commits the editor's source as the problem's solution. An
// unchanged source makes no commit: Mutate skips an empty diff.
func (s *Server) saveCode(ctx *gin.Context) {
body, _, ok := s.readCode(ctx)
if !ok {
return
}
if strings.TrimSpace(body.Source) == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the source is empty"})
return
}
src := body.Source
if !strings.HasSuffix(src, "\n") {
src += "\n"
}
name := ctx.Param("name")
var saved string
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
defer cancel()
err := s.Repo.Mutate(c, "Edit "+name, func(dir string) error {
status, err := findOnDisk(dir, name)
if err != nil {
return err
}
pdir := filepath.Join(dir, status, name)
// main.cpp is the CLI's; a Python solution keeps the sol.py some
// older ones were written as, and is main.py otherwise.
saved = "main.cpp"
if body.Lang == runner.Python {
saved = "main.py"
if !exists(filepath.Join(pdir, "main.py")) && exists(filepath.Join(pdir, "sol.py")) {
saved = "sol.py"
}
}
return os.WriteFile(filepath.Join(pdir, saved), []byte(src), 0o644)
})
if err != nil {
editFailed(ctx, "Edit "+name, err)
return
}
ctx.JSON(http.StatusOK, gin.H{"path": saved})
}
func exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
+301
View File
@@ -0,0 +1,301 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/runner"
)
// fakeRunner records what the site asked for and answers with a fixed
// result, or err.
type fakeRunner struct {
run *runner.RunRequest
lint *runner.LintRequest
err error
}
func (f *fakeRunner) Run(_ context.Context, req runner.RunRequest) (runner.RunResponse, error) {
f.run = &req
if f.err != nil {
return runner.RunResponse{}, f.err
}
return runner.RunResponse{Compile: runner.Compile{OK: true}, Results: []runner.Result{{Name: "1", Verdict: runner.Accepted}}}, nil
}
func (f *fakeRunner) Lint(_ context.Context, req runner.LintRequest) (runner.LintResponse, error) {
f.lint = &req
if f.err != nil {
return runner.LintResponse{}, f.err
}
return runner.LintResponse{Diagnostics: []runner.Diagnostic{{Line: 1, Col: 1, Severity: "warning", Message: "x", Source: "g++"}}}, nil
}
// setupRun adds the solve page's cases to setup's repo: moocast (solved,
// C++, tests 1, 2 and 10 with one .out missing), cow-tipping (sol.py and a
// sample only) and two-sum (LeetCode, with driver.h), plus the repo root's
// templates and headers.
func setupRun(t *testing.T) (*gin.Engine, *dirRepo, *fakeRunner) {
t.Helper()
r, repo, _ := setup(t)
files := map[string]string{
"template.cpp": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n FASTIO;\n}\n",
"template.py": "# stdio(\"name\") opens name.in\ndef main():\n stdio(\"problem\")\n\n\nmain()\n",
"debugging.h": "// debugging\n",
"leetcode.h": "// leetcode\n",
"solved/moocast/moocast.in": "3\n",
"solved/moocast/tests/1.in": "1\n",
"solved/moocast/tests/1.out": "one\n",
"solved/moocast/tests/2.in": "2\n",
"solved/moocast/tests/10.in": "10\n",
"solved/moocast/tests/10.out": "ten\n",
"solved/cow-tipping/cowtip.in": "2\n01\n10\n",
"solved/cow-tipping/cowtip.out": "3\n",
"solved/cow-tipping/sol.py": "print(1)\n",
"solving/two-sum/main.cpp": "class Solution {};\n",
"solving/two-sum/driver.h": "// driver\n",
"solving/two-sum/two-sum.in": "[1,2]\n3\n",
"solving/two-sum/tests/1.in": "[1,2]\n3\n",
"solving/two-sum/tests/1.out": "[0,1]\n",
"solving/watermelon/notes.md": "hm\n",
"solving/watermelon/watermelon.in": "8\n",
}
for p, c := range files {
os.MkdirAll(filepath.Join(repo.dir, filepath.Dir(p)), 0o755)
os.WriteFile(filepath.Join(repo.dir, p), []byte(c), 0o644)
}
// watermelon is the C++ problem with no saved solution.
os.Remove(filepath.Join(repo.dir, "solving/watermelon/main.cpp"))
if err := repo.srv.Reload(repo.dir); err != nil {
t.Fatal(err)
}
fr := &fakeRunner{}
repo.srv.Dir, repo.srv.Runner = repo.dir, fr
return r, repo, fr
}
type codeReply struct {
IO string `json:"io"`
Leetcode bool `json:"leetcode"`
Languages []string `json:"languages"`
Default string `json:"default"`
Runner bool `json:"runner"`
Code map[string]codeFile `json:"code"`
}
func getCodeReply(t *testing.T, r *gin.Engine, name string) codeReply {
t.Helper()
rec := do(r, "GET", "/usaco/api/problems/"+name+"/code", "", true)
if rec.Code != 200 {
t.Fatalf("GET code of %s = %d %s", name, rec.Code, rec.Body)
}
var out codeReply
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
return out
}
func TestGetCode(t *testing.T) {
r, _, _ := setupRun(t)
c := getCodeReply(t, r, "moocast")
if c.IO != "moocast" || c.Leetcode || c.Default != "cpp" || !c.Runner || strings.Join(c.Languages, ",") != "cpp,python" {
t.Fatalf("moocast = %+v", c)
}
if f := c.Code["cpp"]; f != (codeFile{Path: "main.cpp", Source: "int main() {}\n", Saved: true}) {
t.Fatalf("moocast cpp = %+v, want the saved main.cpp", f)
}
if f := c.Code["python"]; f.Saved || f.Path != "main.py" || !strings.Contains(f.Source, " stdio(\"moocast\")\n") || !strings.Contains(f.Source, `# stdio("name")`) {
t.Fatalf("moocast python = %+v, want the starter wired to moocast", f)
}
c = getCodeReply(t, r, "cow-tipping")
if c.IO != "cowtip" || c.Default != "python" {
t.Fatalf("cow-tipping = %+v, want io cowtip and python by default", c)
}
if f := c.Code["python"]; f != (codeFile{Path: "sol.py", Source: "print(1)\n", Saved: true}) {
t.Fatalf("cow-tipping python = %+v, want the saved sol.py", f)
}
c = getCodeReply(t, r, "two-sum")
if !c.Leetcode || strings.Join(c.Languages, ",") != "cpp" || c.Code["python"] != (codeFile{}) {
t.Fatalf("two-sum = %+v, want a C++-only LeetCode problem", c)
}
// The starter is fresh_main's: STDIO as main's first line.
c = getCodeReply(t, r, "watermelon")
want := "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n STDIO(\"watermelon\");\n FASTIO;\n}\n"
if f := c.Code["cpp"]; f.Saved || f.Path != "main.cpp" || f.Source != want {
t.Fatalf("watermelon cpp = %+v, want the wired template", f)
}
}
func TestRunTests(t *testing.T) {
r, _, fr := setupRun(t)
rec := do(r, "POST", "/usaco/api/problems/moocast/run", `{"lang":"cpp","source":"int main() {}","mode":"tests"}`, true)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"verdict":"AC"`) {
t.Fatalf("run = %d %s", rec.Code, rec.Body)
}
req := fr.run
if req.IO != "moocast" || req.Source != "int main() {}" || req.Lang != "cpp" {
t.Fatalf("request = %+v", req)
}
var got []string
for _, tc := range req.Tests {
out := "-"
if tc.Output != nil {
out = *tc.Output
}
got = append(got, tc.Name+"="+strings.TrimSpace(tc.Input)+"/"+strings.TrimSpace(out))
}
if strings.Join(got, " ") != "1=1/one 2=2/- 10=10/ten" {
t.Fatalf("tests = %v, want 1, 2, 10 in order with 2 unchecked", got)
}
if len(req.Files) != 2 || req.Files["debugging.h"] == "" || req.Files["leetcode.h"] == "" {
t.Fatalf("files = %v, want the root headers", req.Files)
}
// A LeetCode problem also gets its driver; Python gets nothing.
do(r, "POST", "/usaco/api/problems/two-sum/run", `{"lang":"cpp","source":"x","mode":"tests"}`, true)
if fr.run.Files["driver.h"] != "// driver\n" || len(fr.run.Files) != 3 {
t.Fatalf("two-sum files = %v", fr.run.Files)
}
do(r, "POST", "/usaco/api/problems/moocast/run", `{"lang":"python","source":"x","mode":"tests"}`, true)
if len(fr.run.Files) != 0 {
t.Fatalf("python files = %v, want none", fr.run.Files)
}
// No tests dir: the sample, unchecked.
do(r, "POST", "/usaco/api/problems/cow-tipping/run", `{"lang":"python","source":"x","mode":"tests"}`, true)
if ts := fr.run.Tests; len(ts) != 1 || ts[0].Name != "sample" || ts[0].Output != nil || fr.run.IO != "cowtip" {
t.Fatalf("cow-tipping tests = %+v", ts)
}
}
func TestRunCustomAndLint(t *testing.T) {
r, _, fr := setupRun(t)
rec := do(r, "POST", "/usaco/api/problems/moocast/run", `{"lang":"cpp","source":"s","mode":"custom","input":"5 6\n"}`, true)
if rec.Code != 200 {
t.Fatalf("custom run = %d %s", rec.Code, rec.Body)
}
if ts := fr.run.Tests; len(ts) != 1 || ts[0].Name != "custom" || ts[0].Input != "5 6\n" || ts[0].Output != nil {
t.Fatalf("custom tests = %+v", ts)
}
rec = do(r, "POST", "/usaco/api/problems/moocast/lint", `{"lang":"cpp","source":"s"}`, true)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"diagnostics":[`) {
t.Fatalf("lint = %d %s", rec.Code, rec.Body)
}
if fr.lint.Source != "s" || fr.lint.Files["debugging.h"] == "" {
t.Fatalf("lint request = %+v", fr.lint)
}
fr.err = errors.New("runner: compiler exploded")
if rec := do(r, "POST", "/usaco/api/problems/moocast/lint", `{"lang":"cpp","source":"s"}`, true); rec.Code != 502 || !strings.Contains(rec.Body.String(), "compiler exploded") {
t.Fatalf("failed lint = %d %s, want 502 with the runner's message", rec.Code, rec.Body)
}
}
func TestRunRefusals(t *testing.T) {
r, repo, _ := setupRun(t)
for _, c := range []struct{ path, body string }{
{"moocast/run", `{"lang":"rust","source":"x","mode":"tests"}`},
{"moocast/run", `{"lang":"cpp","source":"x","mode":"all"}`},
{"two-sum/run", `{"lang":"python","source":"x","mode":"tests"}`},
{"moocast/lint", `{"lang":"java","source":"x"}`},
{"moocast/code", `{"lang":"cpp","source":" "}`},
} {
method := "POST"
if strings.HasSuffix(c.path, "/code") {
method = "PUT"
}
if rec := do(r, method, "/usaco/api/problems/"+c.path, c.body, true); rec.Code != 400 {
t.Errorf("%s %s = %d %s, want 400", c.path, c.body, rec.Code, rec.Body)
}
}
for _, path := range []string{"code", "run", "lint"} {
method := map[string]string{"code": "GET", "run": "POST", "lint": "POST"}[path]
if rec := do(r, method, "/usaco/api/problems/moocast/"+path, `{"lang":"cpp","source":"x","mode":"tests"}`, false); rec.Code != 401 {
t.Errorf("anonymous %s = %d, want 401", path, rec.Code)
}
}
if rec := do(r, "PUT", "/usaco/api/problems/moocast/code", `{"lang":"cpp","source":"x"}`, false); rec.Code != 401 {
t.Errorf("anonymous save = %d, want 401", rec.Code)
}
repo.srv.Runner = nil
if rec := do(r, "POST", "/usaco/api/problems/moocast/run", `{"lang":"cpp","source":"x","mode":"tests"}`, true); rec.Code != 503 {
t.Fatalf("run without a runner = %d, want 503", rec.Code)
}
if c := getCodeReply(t, r, "moocast"); c.Runner {
t.Fatal("GET code says there is a runner when there is none")
}
if len(repo.msg) != 0 {
t.Fatalf("refusals committed %v", repo.msg)
}
}
func TestSaveCode(t *testing.T) {
r, repo, _ := setupRun(t)
read := func(p string) string {
b, _ := os.ReadFile(filepath.Join(repo.dir, p))
return string(b)
}
rec := do(r, "PUT", "/usaco/api/problems/moocast/code", `{"lang":"python","source":"print(2)"}`, true)
if rec.Code != 200 || rec.Body.String() != `{"path":"main.py"}` {
t.Fatalf("save python = %d %s", rec.Code, rec.Body)
}
if got := read("solved/moocast/main.py"); got != "print(2)\n" {
t.Fatalf("main.py = %q, want the source with a trailing newline", got)
}
if read("solved/moocast/main.cpp") == "" {
t.Fatal("saving Python removed main.cpp")
}
// An existing sol.py is kept as the Python file.
rec = do(r, "PUT", "/usaco/api/problems/cow-tipping/code", `{"lang":"python","source":"print(3)\n"}`, true)
if rec.Code != 200 || rec.Body.String() != `{"path":"sol.py"}` || read("solved/cow-tipping/sol.py") != "print(3)\n" {
t.Fatalf("save sol.py = %d %s", rec.Code, rec.Body)
}
if _, err := os.Stat(filepath.Join(repo.dir, "solved/cow-tipping/main.py")); err == nil {
t.Fatal("saving cow-tipping wrote main.py beside sol.py")
}
rec = do(r, "PUT", "/usaco/api/problems/watermelon/code", `{"lang":"cpp","source":"int main() {}\n"}`, true)
if rec.Code != 200 || rec.Body.String() != `{"path":"main.cpp"}` || read("solving/watermelon/main.cpp") != "int main() {}\n" {
t.Fatalf("save cpp = %d %s", rec.Code, rec.Body)
}
if strings.Join(repo.msg, ",") != "Edit moocast,Edit cow-tipping,Edit watermelon" {
t.Fatalf("commit messages = %v", repo.msg)
}
// The saved source comes back as the page's code.
if f := getCodeReply(t, r, "moocast").Code["python"]; f != (codeFile{Path: "main.py", Source: "print(2)\n", Saved: true}) {
t.Fatalf("python after save = %+v", f)
}
}
func TestNaturalLess(t *testing.T) {
in := []string{"10", "2", "1", "a10", "a2", "1a"}
want := "1 1a 2 10 a2 a10"
sorted := append([]string(nil), in...)
for i := range sorted {
for j := i + 1; j < len(sorted); j++ {
if naturalLess(sorted[j], sorted[i]) {
sorted[i], sorted[j] = sorted[j], sorted[i]
}
}
}
if got := strings.Join(sorted, " "); got != want {
t.Fatalf("sorted = %s, want %s", got, want)
}
}