fspl/testcommon/common.go

56 lines
1.6 KiB
Go

// Package testcommon provides re-usable unit testing functionality.
package testcommon
import "testing"
import "strings"
// LogColumns logs columns of text side by side, each column 80 characters wide.
func LogColumns (test *testing.T, columns ...any) {
LogColumnsStyle(test, "0m", columns...)
}
// LogColumnsStyle is like LogColumns, but accepts an ANSI escape code as an
// argument (without the \033[). For example, passing 31m causes the text to be
// red.
func LogColumnsStyle (test *testing.T, style string, columns ...any) {
formatString := ""
for index := range columns {
if index > 0 { formatString += " | " }
if index == len(columns) - 1 {
formatString += "%v"
} else {
formatString += "%-80v"
}
}
test.Logf("\033[" + style + formatString + "\033[0m", columns...)
}
// Compare compares a correct string with a result string and produces formatted
// output showing them side-by-side with their differences highlighted.
func Compare (test *testing.T, correct, got string) {
got = strings.ReplaceAll(got, "\t", " ")
correct = strings.ReplaceAll(correct, "\t", " ")
correctLines := strings.Split(correct, "\n")
gotLines := strings.Split(got, "\n")
length := len(gotLines)
if len(correctLines) > len(gotLines) { length = len(correctLines) }
LogColumns(test, "CORRECT:", "GOT:")
test.Log()
for index := 0; index < length; index ++ {
left := ""
right := ""
if index < len(correctLines) { left = correctLines[index] }
if index < len(gotLines) { right = gotLines[index] }
if left != right {
LogColumnsStyle(test, "31m", left, right)
} else {
LogColumns(test, left, right)
}
}
}