package tokenize_test // This file contains some tools that are used for writing tests. import ( "regexp" "testing" tokenize "git.makaay.nl/mauricem/go-parsekit/tokenize" ) func AssertEqual(t *testing.T, expected interface{}, actual interface{}, forWhat string) { if expected != actual { t.Errorf( "Unexpected value for %s:\nexpected: %q\nactual: %q", forWhat, expected, actual) } } func AssertTrue(t *testing.T, b bool, assertion string) { if !b { t.Errorf("Assertion %s is false", assertion) } } type PanicT struct { Function func() Regexp bool Expect string } func AssertPanics(t *testing.T, testSet []PanicT) { for _, test := range testSet { AssertPanic(t, test) } } func AssertPanic(t *testing.T, p PanicT) { defer func() { if r := recover(); r != nil { mismatch := false if p.Regexp && !regexp.MustCompile(p.Expect).MatchString(r.(string)) { mismatch = true } if !p.Regexp && p.Expect != r.(string) { mismatch = true } if mismatch { t.Errorf( "Code did panic, but unexpected panic message received:\nexpected: %q\nactual: %q", p.Expect, r) } } else { t.Errorf("Function did not panic (expected panic message: %s)", p.Expect) } }() p.Function() } type HandlerT struct { Input string Handler tokenize.Handler MustMatch bool Expected string } func AssertHandlers(t *testing.T, testSet []HandlerT) { for _, test := range testSet { AssertHandler(t, test) } } func AssertHandler(t *testing.T, test HandlerT) { result, err := tokenize.New(test.Handler)(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 TokenMakerT struct { Input string Handler tokenize.Handler Expected []tokenize.Token } func AssertTokenMakers(t *testing.T, testSet []TokenMakerT) { for _, test := range testSet { AssertTokenMaker(t, test) } } func AssertTokenMaker(t *testing.T, test TokenMakerT) { result, err := tokenize.New(test.Handler)(test.Input) if err != nil { t.Errorf("Test %q failed with error: %s", test.Input, err) } else { tokens := result.Tokens() if len(tokens) != len(test.Expected) { t.Errorf("Unexpected number of tokens in output:\nexpected: %d\nactual: %d", len(test.Expected), len(tokens)) } for i, expected := range test.Expected { actual := tokens[i] if expected.Type != actual.Type { t.Errorf("Unexpected Type in result.Tokens, idx %d:\nexpected: (%T) %s\nactual: (%T) %s", i, expected.Type, expected.Type, actual.Type, actual.Type) } if expected.Value != actual.Value { t.Errorf("Unexpected Value in result.Tokens, idx %d:\nexpected: (%T) %s\nactual: (%T) %s", i, expected.Value, expected.Value, actual.Value, actual.Value) } } } }