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 \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 \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) } }