65 lines
2.0 KiB
Go
65 lines
2.0 KiB
Go
// Package testcommon provides re-usable unit testing functionality.
|
|
package testcommon
|
|
|
|
import "testing"
|
|
import "strings"
|
|
import "strconv"
|
|
import "encoding/hex"
|
|
|
|
// LogColumns logs columns of text side by side, each column 80 characters wide.
|
|
func LogColumns (test *testing.T, width int, columns ...any) {
|
|
LogColumnsStyle(test, width, "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, width int, style string, columns ...any) {
|
|
formatString := ""
|
|
for index := range columns {
|
|
if index > 0 { formatString += " | " }
|
|
|
|
if index == len(columns) - 1 {
|
|
formatString += "%v"
|
|
} else {
|
|
formatString += "%-" + strconv.Itoa(width) + "v"
|
|
}
|
|
}
|
|
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) }
|
|
|
|
width := 80
|
|
LogColumns(test, width, "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, width, "31m", left, right)
|
|
} else {
|
|
LogColumns(test, width, left, right)
|
|
}
|
|
}
|
|
}
|
|
|
|
// CompareHex is like compare, but it prits out the differences in
|
|
func CompareHex (test *testing.T, correct, got string) {
|
|
correct = hex.Dump([]byte(correct))
|
|
got = hex.Dump([]byte(got))
|
|
Compare(test, correct, got)
|
|
}
|