go-parsekit/parsekit_test.go

102 lines
2.9 KiB
Go

package parsekit_test
// This file only provides building blocks for writing tests.
// No actual tests belong in this file.
import (
"regexp"
"testing"
"git.makaay.nl/mauricem/go-parsekit"
)
// Easy access to the parsekit definitions.
var c, a, m, tok = parsekit.C, parsekit.A, parsekit.M, parsekit.T
type TokenHandlerTest struct {
Input string
TokenHandler parsekit.TokenHandler
MustMatch bool
Expected string
}
func RunTokenHandlerTests(t *testing.T, testSet []TokenHandlerTest) {
for _, test := range testSet {
RunTokenHandlerTest(t, test)
}
}
func RunTokenHandlerTest(t *testing.T, test TokenHandlerTest) {
result, err := parsekit.NewMatcher(test.TokenHandler, "a match").Execute(test.Input)
if test.MustMatch {
if err != nil {
t.Errorf("Test %q failed with error: %s", test.Input, err)
} else if output := result.String(); output != test.Expected {
t.Errorf("Test %q failed: not expected output:\nexpected: %q\nactual: %q\n", test.Input, test.Expected, output)
}
} else {
if err == nil {
t.Errorf("Test %q failed: should not match, but it did", test.Input)
}
}
}
type TokenMakerTest struct {
Input string
TokenHandler parsekit.TokenHandler
Expected []parsekit.Token
}
func RunTokenMakerTest(t *testing.T, test TokenMakerTest) {
result, err := parsekit.NewMatcher(test.TokenHandler, "a match").Execute(test.Input)
if err != nil {
t.Errorf("Test %q failed with error: %s", test.Input, err)
} else {
if len(result.Tokens()) != len(test.Expected) {
t.Errorf("Unexpected number of tokens in output:\nexpected: %d\nactual: %d", len(test.Expected), len(result.Tokens()))
}
for i, expected := range test.Expected {
actual := result.Token(i)
if expected.Type != actual.Type {
t.Errorf("Unexpected Type in result.Tokens[%d]:\nexpected: (%T) %s\nactual: (%T) %s", i, expected.Type, expected.Type, actual.Type, actual.Type)
}
if string(expected.Runes) != string(actual.Runes) {
t.Errorf("Unexpected Runes in result.Tokens[%d]:\nexpected: %q\nactual: %q", i, expected.Runes, actual.Runes)
}
if expected.Value != actual.Value {
t.Errorf("Unexpected Value in result.Tokens[%d]:\nexpected: (%T) %s\nactual: (%T) %s", i, expected.Value, expected.Value, actual.Value, actual.Value)
}
}
}
}
func RunTokenMakerTests(t *testing.T, testSet []TokenMakerTest) {
for _, test := range testSet {
RunTokenMakerTest(t, test)
}
}
type PanicTest struct {
function func()
expected string
}
func RunPanicTest(t *testing.T, p PanicTest) {
defer func() {
if r := recover(); r != nil {
if !regexp.MustCompile(p.expected).MatchString(r.(string)) {
t.Errorf("Function did panic, but unexpected panic message received:\nexpected: %q\nactual: %q\n", p.expected, r)
}
} else {
t.Errorf("Function did not panic (expected panic message: %s)", p.expected)
}
}()
p.function()
}
func RunPanicTests(t *testing.T, testSet []PanicTest) {
for _, test := range testSet {
RunPanicTest(t, test)
}
}