You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.3 KiB

package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"regexp"
"strings"
"github.com/kylelemons/godebug/diff"
)
func fileExists(f string) bool {
_, err := os.Stat(f);
return err == nil;
}
var inputre = regexp.MustCompile(`\.input$`)
type CPTest struct {
Name string
Input *[]byte
Output *[]byte
}
func runOneTest(dir string, test *CPTest) {
fmt.Println("Running Test", test.Name, "...");
fmt.Println("==========");
fmt.Println("INPUT:")
fmt.Println(string(*test.Input));
fmt.Println("==========");
cmd := exec.Command("go", "run", path.Join(dir, "main.go"));
inpipe, _ := cmd.StdinPipe();
defer inpipe.Close();
fmt.Fprintln(inpipe, string(*test.Input));
out,err := cmd.CombinedOutput();
fmt.Println("OUTPUT:")
if err != nil {
fmt.Println(err);
fmt.Println(string(out));
return
}
fmt.Println(string(out));
if test.Output != nil {
fmt.Println("==========");
fmt.Println("ANSWER:")
fmt.Println(string(*test.Output));
fmt.Println("==========");
fmt.Println("DIFF:")
fmt.Println(diff.Diff(string(out), string(*test.Output)))
}
fmt.Println("==========");
}
func runTests(dir string, selected []string) {
testfolder := path.Join(dir, "cpgo_tests")
info, err := os.Stat(testfolder);
if err != nil {
fmt.Println("Error encountered", err);
os.Exit(1);
}
if !info.IsDir() {
fmt.Println(testfolder, "is not a directory.")
os.Exit(1);
}
entries, err := ioutil.ReadDir(testfolder); if err != nil {
fmt.Println("Error while accessing", testfolder, err);
os.Exit(1);
}
tests := make([]CPTest, 0);
testmap := map[string]*CPTest{};
for _,file := range entries {
if strings.HasSuffix(file.Name(), ".input") {
fpath := path.Join(testfolder, file.Name());
input,_ := ioutil.ReadFile(fpath);
outputfile := string(inputre.ReplaceAll([]byte(fpath), []byte(".output")));
tst := CPTest{
Name: strings.TrimSuffix(file.Name(), ".input"),
Input: &input,
};
if fileExists(outputfile) {
out,_ := ioutil.ReadFile(outputfile);
tst.Output = &out;
}
tests = append(tests, tst);
testmap[tst.Name] = &tst;
}
}
if len(selected) == 0 {
for _, t := range tests {
runOneTest(dir, &t);
}
} else {
for _,name := range selected {
t, exists := testmap[name];
if exists {
runOneTest(dir, t);
} else {
fmt.Println(name, "is not a valid test.");
return
}
}
}
}