|
| 1 | +// The program read the environment `TEST_CASE_DIR`, |
| 2 | +// accepts the tompiled executable from stdin |
| 3 | +// If the test case passes, it exit with status 0 |
| 4 | +// In case error occurred, it output the error message |
| 5 | +// to stderr, and exit with status 1. |
| 6 | + |
1 | 7 | package main
|
2 | 8 |
|
| 9 | +import ( |
| 10 | + "bufio" |
| 11 | + "encoding/json" |
| 12 | + "io" |
| 13 | + "log" |
| 14 | + "os" |
| 15 | + "os/exec" |
| 16 | + "path/filepath" |
| 17 | + |
| 18 | + "github.com/markhuang1212/code-grader/types" |
| 19 | +) |
| 20 | + |
3 | 21 | func main() {
|
4 | 22 |
|
| 23 | + prog, err := os.OpenFile("/tmp/a.out", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) |
| 24 | + if err != nil { |
| 25 | + panic(err) |
| 26 | + } |
| 27 | + |
| 28 | + io.Copy(prog, os.Stdin) |
| 29 | + prog.Close() |
| 30 | + |
| 31 | + testCaseDir := os.Getenv("TEST_CASE_DIR") |
| 32 | + testCaseJson, err := os.ReadFile(filepath.Join(testCaseDir, "testcase.json")) |
| 33 | + if err != nil { |
| 34 | + panic(err) |
| 35 | + } |
| 36 | + |
| 37 | + var testCaseOpt types.TestCaseOptions |
| 38 | + json.Unmarshal(testCaseJson, &testCaseOpt) |
| 39 | + |
| 40 | + inputFile, err := os.Open(filepath.Join(testCaseDir, testCaseOpt.RuntimeOptions.StdinPath)) |
| 41 | + if err != nil { |
| 42 | + panic(err) |
| 43 | + } |
| 44 | + |
| 45 | + answerFile, err := os.Open(filepath.Join(testCaseDir, testCaseOpt.RuntimeOptions.StdoutPath)) |
| 46 | + if err != nil { |
| 47 | + panic(err) |
| 48 | + } |
| 49 | + answerScanner := bufio.NewScanner(answerFile) |
| 50 | + answerScanner.Split(bufio.ScanWords) |
| 51 | + |
| 52 | + cmd := exec.Command("/tmp/a.out") |
| 53 | + |
| 54 | + progOutput, err := cmd.StdoutPipe() |
| 55 | + if err != nil { |
| 56 | + panic(err) |
| 57 | + } |
| 58 | + progOutputScanner := bufio.NewScanner(progOutput) |
| 59 | + progOutputScanner.Split(bufio.ScanWords) |
| 60 | + |
| 61 | + cmd.Stdin = inputFile |
| 62 | + err = cmd.Start() |
| 63 | + if err != nil { |
| 64 | + panic(err) |
| 65 | + } |
| 66 | + |
| 67 | + for { |
| 68 | + |
| 69 | + r1 := answerScanner.Scan() |
| 70 | + r2 := progOutputScanner.Scan() |
| 71 | + |
| 72 | + if r1 == false && r2 == false { |
| 73 | + os.Exit(0) |
| 74 | + } |
| 75 | + |
| 76 | + if r1 == false || r2 == false { |
| 77 | + log.Println("Wrong Answer!") |
| 78 | + os.Exit(1) |
| 79 | + } |
| 80 | + |
| 81 | + w1 := answerScanner.Text() |
| 82 | + w2 := progOutputScanner.Text() |
| 83 | + |
| 84 | + if w1 != w2 { |
| 85 | + log.Println("Wrong Answer!") |
| 86 | + os.Exit(1) |
| 87 | + } |
| 88 | + |
| 89 | + } |
| 90 | + |
5 | 91 | }
|
0 commit comments