337 lines
12 KiB
Go
337 lines
12 KiB
Go
package judge
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"lincodex/runner/internal/checker"
|
|
"lincodex/runner/internal/sandbox"
|
|
)
|
|
|
|
// scriptedExecutor answers test runs from a script keyed by the stdin of a
|
|
// test, compile steps from compileResults in order, and custom checker runs
|
|
// from checkerExits keyed by the actual output the checker reads.
|
|
type scriptedExecutor struct {
|
|
root string
|
|
results map[string]sandbox.Result
|
|
errs map[string]error
|
|
compileResults []sandbox.Result
|
|
checkerExits map[string]int
|
|
runs []string
|
|
compileSteps [][]string
|
|
checkerRuns int
|
|
boxes []string
|
|
}
|
|
|
|
func (e *scriptedExecutor) NewBox(fileName string, content []byte) (*sandbox.Box, error) {
|
|
box, err := sandbox.CreateBox(e.root, fileName, content, sandbox.Owner{UID: -1, GID: -1})
|
|
if err == nil {
|
|
e.boxes = append(e.boxes, box.Dir())
|
|
}
|
|
return box, err
|
|
}
|
|
|
|
func (e *scriptedExecutor) Run(_ context.Context, spec sandbox.Spec, _ sandbox.Limits) (sandbox.Result, error) {
|
|
for _, mount := range spec.Mounts {
|
|
if mount.Target == sandbox.CheckPath {
|
|
return e.runChecker(mount)
|
|
}
|
|
if mount.Target == sandbox.OutPath && mount.Writable {
|
|
index := len(e.compileSteps)
|
|
e.compileSteps = append(e.compileSteps, spec.Argv)
|
|
if index < len(e.compileResults) {
|
|
return e.compileResults[index], nil
|
|
}
|
|
return sandbox.Result{}, nil
|
|
}
|
|
}
|
|
key := string(spec.Stdin)
|
|
e.runs = append(e.runs, key)
|
|
if err := e.errs[key]; err != nil {
|
|
return sandbox.Result{}, err
|
|
}
|
|
if result, ok := e.results[key]; ok {
|
|
return result, nil
|
|
}
|
|
return sandbox.Result{}, nil
|
|
}
|
|
|
|
func (e *scriptedExecutor) runChecker(mount sandbox.Mount) (sandbox.Result, error) {
|
|
e.checkerRuns++
|
|
actual, err := os.ReadFile(filepath.Join(mount.Source, "actual"))
|
|
if err != nil {
|
|
return sandbox.Result{}, err
|
|
}
|
|
exit, ok := e.checkerExits[string(actual)]
|
|
if !ok {
|
|
exit = 3
|
|
}
|
|
return sandbox.Result{ExitCode: exit}, nil
|
|
}
|
|
|
|
func newScripted(t *testing.T) *scriptedExecutor {
|
|
t.Helper()
|
|
return &scriptedExecutor{root: t.TempDir(), results: map[string]sandbox.Result{}, errs: map[string]error{}, checkerExits: map[string]int{}}
|
|
}
|
|
|
|
func output(text string) sandbox.Result {
|
|
return sandbox.Result{Stdout: []byte(text), CPUTime: 20 * time.Millisecond, WallTime: 30 * time.Millisecond, PeakMemoryKB: 9000}
|
|
}
|
|
|
|
func discardLogger() *slog.Logger {
|
|
return slog.New(slog.DiscardHandler)
|
|
}
|
|
|
|
func twoGroupRequest() Request {
|
|
return Request{
|
|
Language: "python3",
|
|
Source: "print(sum(map(int, input().split())))",
|
|
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
|
|
Groups: []Group{
|
|
{ID: "public", Visibility: Public, Checker: checker.Spec{Kind: checker.Exact}, Tests: []Test{
|
|
{ID: "t1", Input: "1 2", ExpectedOutput: "3\n"},
|
|
{ID: "t2", Input: "2 2", ExpectedOutput: "4\n"},
|
|
}},
|
|
{ID: "hidden-1", Visibility: Hidden, Checker: checker.Spec{Kind: checker.Tokens}, Tests: []Test{
|
|
{ID: "t1", Input: "5 5", ExpectedOutput: "10"},
|
|
{ID: "t2", Input: "6 6", ExpectedOutput: "12"},
|
|
}},
|
|
},
|
|
}
|
|
}
|
|
|
|
func TestRunAcceptsCorrectOutputAndRecordsUsage(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
executor := newScripted(t)
|
|
executor.results["1 2"] = output("3\n")
|
|
executor.results["2 2"] = output("4")
|
|
executor.results["5 5"] = output("10\n")
|
|
executor.results["6 6"] = output(" 12 ")
|
|
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
|
|
|
if result.Outcome != Accepted || result.Compile == nil || result.Compile.Outcome != Accepted {
|
|
t.Fatalf("result = %+v, want accepted with a passed compile step", result)
|
|
}
|
|
for _, group := range result.Groups {
|
|
if group.Outcome != Accepted || group.Passed != 2 || group.Total != 2 {
|
|
t.Fatalf("group %+v, want 2 of 2 accepted", group)
|
|
}
|
|
if group.MaxCPUTime != 20*time.Millisecond || group.MaxMemoryKB != 9000 {
|
|
t.Fatalf("group usage %v %d, want the recorded usage", group.MaxCPUTime, group.MaxMemoryKB)
|
|
}
|
|
}
|
|
assertBoxesRemoved(t, executor)
|
|
}
|
|
|
|
func TestRunStopsAGroupAtItsFirstFailureAndKeepsDiagnosticsPublicOnly(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
executor := newScripted(t)
|
|
crash := sandbox.Result{ExitCode: 1, Stderr: []byte("Traceback: ValueError")}
|
|
executor.results["1 2"] = crash
|
|
executor.results["5 5"] = crash
|
|
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
|
|
|
if result.Outcome != RuntimeError {
|
|
t.Fatalf("outcome = %s, want runtime_error", result.Outcome)
|
|
}
|
|
public, hidden := result.Groups[0], result.Groups[1]
|
|
if len(public.Tests) != 1 || public.Passed != 0 || public.Tests[0].Diagnostic != "Traceback: ValueError" {
|
|
t.Fatalf("public group %+v, want one failed test with its diagnostic", public)
|
|
}
|
|
if len(hidden.Tests) != 1 || hidden.Tests[0].Diagnostic != "" {
|
|
t.Fatalf("hidden group %+v, want one failed test without a diagnostic", hidden)
|
|
}
|
|
if slices.Contains(executor.runs, "2 2") || slices.Contains(executor.runs, "6 6") {
|
|
t.Fatalf("runs %q include tests after a failure", executor.runs)
|
|
}
|
|
}
|
|
|
|
func TestRunMapsSandboxTerminationsToOutcomes(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
cases := []struct {
|
|
name string
|
|
result sandbox.Result
|
|
outcome Outcome
|
|
}{
|
|
{"cpu time", sandbox.Result{Termination: sandbox.TerminationCPUTime, Signal: 9}, TimeLimitExceeded},
|
|
{"wall time", sandbox.Result{Termination: sandbox.TerminationWallTime, Signal: 9}, TimeLimitExceeded},
|
|
{"memory", sandbox.Result{Termination: sandbox.TerminationMemory, Signal: 9}, MemoryLimitExceeded},
|
|
{"output", sandbox.Result{Termination: sandbox.TerminationOutput, Signal: 9, Stdout: []byte("3\n")}, OutputLimitExceeded},
|
|
{"processes", sandbox.Result{Termination: sandbox.TerminationProcesses, ExitCode: 1}, RuntimeError},
|
|
{"signal", sandbox.Result{Signal: 31, ExitCode: -1}, RuntimeError},
|
|
{"wrong answer", output("4\n"), WrongAnswer},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
executor := newScripted(t)
|
|
executor.results["1 2"] = tc.result
|
|
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
|
got := result.Groups[0].Tests[0]
|
|
if got.Outcome != tc.outcome || got.Limit != tc.result.Termination {
|
|
t.Fatalf("test result %+v, want %s with limit %q", got, tc.outcome, tc.result.Termination)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRunReportsCompileErrorsWithoutRunningTests(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
executor := newScripted(t)
|
|
executor.compileResults = []sandbox.Result{{ExitCode: 1, Stderr: []byte("SyntaxError: invalid syntax\n")}}
|
|
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
|
|
|
if result.Outcome != CompileError || result.Compile.Diagnostic != "SyntaxError: invalid syntax\n" {
|
|
t.Fatalf("result = %+v, want compile_error with the diagnostic", result)
|
|
}
|
|
if len(executor.runs) != 0 || len(executor.compileSteps) != 1 {
|
|
t.Fatalf("runs = %q after %d compile steps, want only the compile step", executor.runs, len(executor.compileSteps))
|
|
}
|
|
for _, group := range result.Groups {
|
|
if group.Outcome != CompileError || len(group.Tests) != 0 || group.Total != 2 {
|
|
t.Fatalf("group %+v, want compile_error without tests", group)
|
|
}
|
|
}
|
|
assertBoxesRemoved(t, executor)
|
|
}
|
|
|
|
func TestRunTurnsSandboxFailuresIntoInfrastructureFailure(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
executor := newScripted(t)
|
|
executor.results["1 2"] = output("3\n")
|
|
executor.errs["2 2"] = errors.New("nsjail failed")
|
|
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), twoGroupRequest())
|
|
|
|
if result.Outcome != InfrastructureFailure {
|
|
t.Fatalf("outcome = %s, want infrastructure_failure", result.Outcome)
|
|
}
|
|
for _, group := range result.Groups {
|
|
if group.Outcome != InfrastructureFailure || len(group.Tests) != 0 {
|
|
t.Fatalf("group %+v, want infrastructure_failure without partial tests", group)
|
|
}
|
|
}
|
|
assertBoxesRemoved(t, executor)
|
|
}
|
|
|
|
func TestExcerptKeepsTheTailAsValidUTF8(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
text := append(bytes.Repeat([]byte("ж"), 10), 0xff, 'x')
|
|
if got := excerpt(text, 7); got != "ж\uFFFDx" {
|
|
t.Fatalf("excerpt = %q, want the last whole runes within 7 bytes", got)
|
|
}
|
|
}
|
|
|
|
func assertBoxesRemoved(t *testing.T, executor *scriptedExecutor) {
|
|
t.Helper()
|
|
for _, dir := range executor.boxes {
|
|
if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatalf("box %s still exists: %v", dir, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func goRequest(groups ...Group) Request {
|
|
return Request{
|
|
Language: "go",
|
|
Source: "package main\nfunc main() {}\n",
|
|
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
|
|
Groups: groups,
|
|
}
|
|
}
|
|
|
|
func TestGoCompilesAndLinksBeforeTheTests(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
executor := newScripted(t)
|
|
executor.results["1"] = output("1\n")
|
|
group := Group{ID: "public", Visibility: Public, Checker: checker.Spec{Kind: checker.Exact}, Tests: []Test{{ID: "t1", Input: "1", ExpectedOutput: "1\n"}}}
|
|
result := New(executor, discardLogger(), Go("/usr/local/lib/lincodex-runner/go")).Run(t.Context(), goRequest(group))
|
|
|
|
if result.Outcome != Accepted || len(executor.compileSteps) != 2 {
|
|
t.Fatalf("result %+v after %d compile steps, want accepted after compile and link", result, len(executor.compileSteps))
|
|
}
|
|
if !strings.HasSuffix(executor.compileSteps[0][0], "/compile") || !strings.HasSuffix(executor.compileSteps[1][0], "/link") {
|
|
t.Fatalf("compile steps = %q", executor.compileSteps)
|
|
}
|
|
}
|
|
|
|
func TestGoCompileErrorRunsNoTest(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
for _, failing := range []int{0, 1} {
|
|
executor := newScripted(t)
|
|
executor.compileResults = make([]sandbox.Result, failing+1)
|
|
executor.compileResults[failing] = sandbox.Result{ExitCode: 2, Stderr: []byte("main.go:2:14: declared and not used: x\n")}
|
|
group := Group{ID: "hidden-1", Visibility: Hidden, Checker: checker.Spec{Kind: checker.Exact}, Tests: []Test{{ID: "t1", Input: "1", ExpectedOutput: "1"}}}
|
|
result := New(executor, discardLogger(), Go("/go")).Run(t.Context(), goRequest(group))
|
|
|
|
if result.Outcome != CompileError || !strings.Contains(result.Compile.Diagnostic, "declared and not used") {
|
|
t.Fatalf("step %d: result %+v, want compile_error with the diagnostic", failing, result)
|
|
}
|
|
if len(executor.runs) != 0 || len(result.Groups[0].Tests) != 0 || result.Groups[0].Outcome != CompileError {
|
|
t.Fatalf("step %d: tests ran after a compile error: %q", failing, executor.runs)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCustomCheckerDecidesByExitStatusAndIsCompiledOnce(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
executor := newScripted(t)
|
|
executor.results["a"] = output("good\n")
|
|
executor.results["b"] = output("bad\n")
|
|
executor.checkerExits["good\n"] = 0
|
|
executor.checkerExits["bad\n"] = 1
|
|
custom := checker.Spec{Kind: checker.Custom, Program: &checker.Program{Language: "python3", Source: "import sys\n"}}
|
|
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), Request{
|
|
Language: "python3",
|
|
Source: "print('x')",
|
|
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
|
|
Groups: []Group{
|
|
{ID: "public", Visibility: Public, Checker: custom, Tests: []Test{{ID: "t1", Input: "a", ExpectedOutput: "e"}}},
|
|
{ID: "hidden-1", Visibility: Hidden, Checker: custom, Tests: []Test{{ID: "t1", Input: "b", ExpectedOutput: "e"}}},
|
|
},
|
|
})
|
|
|
|
if result.Groups[0].Outcome != Accepted || result.Groups[1].Outcome != WrongAnswer {
|
|
t.Fatalf("groups = %+v, want accepted then wrong_answer", result.Groups)
|
|
}
|
|
// One syntax check for the solution and one for the shared checker.
|
|
if len(executor.compileSteps) != 2 || executor.checkerRuns != 2 {
|
|
t.Fatalf("compile steps %d, checker runs %d; want 2 and 2", len(executor.compileSteps), executor.checkerRuns)
|
|
}
|
|
assertBoxesRemoved(t, executor)
|
|
}
|
|
|
|
func TestFailingCustomCheckerIsAnInfrastructureFailure(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
executor := newScripted(t)
|
|
executor.results["a"] = output("unknown\n")
|
|
custom := checker.Spec{Kind: checker.Custom, Program: &checker.Program{Language: "python3", Source: "raise SystemExit(3)\n"}}
|
|
result := New(executor, discardLogger(), Python3("/usr/local/bin/python3")).Run(t.Context(), Request{
|
|
Language: "python3",
|
|
Source: "print('x')",
|
|
Limits: Limits{TimeLimit: time.Second, MemoryBytes: 64 << 20, OutputBytes: 64 << 10},
|
|
Groups: []Group{{ID: "public", Visibility: Public, Checker: custom, Tests: []Test{{ID: "t1", Input: "a", ExpectedOutput: "e"}}}},
|
|
})
|
|
if result.Outcome != InfrastructureFailure {
|
|
t.Fatalf("outcome = %s, want infrastructure_failure", result.Outcome)
|
|
}
|
|
assertBoxesRemoved(t, executor)
|
|
}
|