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.

107 lines
2.3 KiB

2 years ago
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "os/exec"
  7. "path"
  8. "regexp"
  9. "strings"
  10. "github.com/kylelemons/godebug/diff"
  11. )
  12. func fileExists(f string) bool {
  13. _, err := os.Stat(f);
  14. return err == nil;
  15. }
  16. var inputre = regexp.MustCompile(`\.input$`)
  17. type CPTest struct {
  18. Name string
  19. Input *[]byte
  20. Output *[]byte
  21. }
  22. func runOneTest(dir string, test *CPTest) {
  23. fmt.Println("Running Test", test.Name, "...");
  24. fmt.Println("==========");
  25. fmt.Println("INPUT:")
  26. fmt.Println(string(*test.Input));
  27. fmt.Println("==========");
  28. cmd := exec.Command("go", "run", path.Join(dir, "main.go"));
  29. inpipe, _ := cmd.StdinPipe();
  30. defer inpipe.Close();
  31. fmt.Fprintln(inpipe, string(*test.Input));
  32. out,err := cmd.Output();
  33. if err != nil {
  34. fmt.Println(err);
  35. return
  36. }
  37. fmt.Println("OUTPUT:")
  38. fmt.Println(string(out));
  39. if test.Output != nil {
  40. fmt.Println("==========");
  41. fmt.Println("ANSWER:")
  42. fmt.Println(string(*test.Output));
  43. fmt.Println("==========");
  44. fmt.Println("DIFF:")
  45. fmt.Println(diff.Diff(string(out), string(*test.Output)))
  46. }
  47. fmt.Println("==========");
  48. }
  49. func runTests(dir string, selected []string) {
  50. testfolder := path.Join(dir, "cpgo_tests")
  51. info, err := os.Stat(testfolder);
  52. if err != nil {
  53. fmt.Println("Error encountered", err);
  54. os.Exit(1);
  55. }
  56. if !info.IsDir() {
  57. fmt.Println(testfolder, "is not a directory.")
  58. os.Exit(1);
  59. }
  60. entries, err := ioutil.ReadDir(testfolder); if err != nil {
  61. fmt.Println("Error while accessing", testfolder, err);
  62. os.Exit(1);
  63. }
  64. tests := make([]CPTest, 0);
  65. testmap := map[string]*CPTest{};
  66. for _,file := range entries {
  67. if strings.HasSuffix(file.Name(), ".input") {
  68. fpath := path.Join(testfolder, file.Name());
  69. input,_ := ioutil.ReadFile(fpath);
  70. outputfile := string(inputre.ReplaceAll([]byte(fpath), []byte(".output")));
  71. tst := CPTest{
  72. Name: strings.TrimSuffix(file.Name(), ".input"),
  73. Input: &input,
  74. };
  75. if fileExists(outputfile) {
  76. out,_ := ioutil.ReadFile(outputfile);
  77. tst.Output = &out;
  78. }
  79. tests = append(tests, tst);
  80. testmap[tst.Name] = &tst;
  81. }
  82. }
  83. if len(selected) == 0 {
  84. for _, t := range tests {
  85. runOneTest(dir, &t);
  86. }
  87. } else {
  88. for _,name := range selected {
  89. t, exists := testmap[name];
  90. if exists {
  91. runOneTest(dir, t);
  92. } else {
  93. fmt.Println(name, "is not a valid test.");
  94. return
  95. }
  96. }
  97. }
  98. }