Skip to content

Instantly share code, notes, and snippets.

@richardwu
Last active March 19, 2018 05:37
Show Gist options
  • Save richardwu/aedc8c55d91c79ee01f0682ae88f5c05 to your computer and use it in GitHub Desktop.
Save richardwu/aedc8c55d91c79ee01f0682ae88f5c05 to your computer and use it in GitHub Desktop.
Test harness for CS 341 - drag and drop these files into your source folder, then run `make test` (Go required and c++11 required).
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"testing"
)
// IMPORTANT: Update these to what your actual files are called!
const execFile = "./a4q1"
const testfile = "tests.txt"
const endInputLine = "ENDINPUT\n"
const endOutputLine = "ENDOUTPUT\n"
func TestAll(t *testing.T) {
file, err := os.Open(testfile)
if err != nil {
t.Fatal(err)
}
rd := bufio.NewReader(file)
testI := 0
var input, expected []byte
done := false
for !done {
t.Run(strconv.Itoa(testI), func(t *testing.T) {
input = input[:0]
expected = expected[:0]
// Read in input.
for {
temp, err := rd.ReadBytes('\n')
if err != nil {
t.Fatal(err)
}
if string(temp) == endInputLine {
break
}
input = append(input, temp...)
}
// Read in expected test output.
for {
temp, err := rd.ReadBytes('\n')
if err != nil {
t.Fatal(err)
}
if string(temp) == endOutputLine {
break
}
expected = append(expected, temp...)
}
fmt.Printf("Starting test %d\n", testI)
// Prepare the command and the input.
cmd := exec.Command(execFile)
stdin, err := cmd.StdinPipe()
if err != nil {
t.Fatal(err)
}
if _, err := stdin.Write(input); err != nil {
t.Fatal(err)
}
// Run the command and gather the output.
out, err := cmd.Output()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(expected, out) {
t.Errorf("divergence in outputs\n")
t.Errorf("Input:\n%s\n", string(input))
t.Errorf("Expected output:\n%s\n", string(expected))
t.Errorf("Actual output:\n%s\n", string(out))
t.Errorf("expected (bytes):\n%v\n", expected)
t.Errorf("actual (bytes):\n%v\n", out)
}
testI++
// Read next test.
if _, err := rd.ReadBytes('\n'); err != nil {
if err == io.EOF {
fmt.Println("EOF reached.")
done = true
return
}
t.Fatal(err)
}
})
}
}
EXEC = a4q1
SRC = a4q1.cpp
TEST = a4q1_test.go
${EXEC}: ${SRC}
g++ -std=c++11 ${SRC} -o ${EXEC}
.PHONY: test clean build
build: ${EXEC}
test: ${EXEC} ${TEST}
go test ${TEST}
clean:
rm ${EXEC}
6
9
1 2
1 3
2 3
2 5
3 1
3 4
4 5
4 6
5 4
ENDINPUT
3 2 1 0 0
ENDOUTPUT
6
9
1 2
1 3
2 3
2 5
3 1
3 4
4 5
4 6
5 4
ENDINPUT
3 2 1 0 0
ENDOUTPUT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment