go-parsekit/parsehandler_test.go

76 lines
2.4 KiB
Go

package parsekit_test
import (
"testing"
"git.makaay.nl/mauricem/go-parsekit"
)
func TestGivenNilTokenHandler_WhenCallingOn_ParsekitPanics(t *testing.T) {
p := parsekit.NewParser(func(p *parsekit.ParseAPI) {
p.On(nil)
})
RunPanicTest(t, PanicTest{
func() { p.Execute("") },
"internal parser error: tokenHandler argument for On() is nil"})
}
func TestGivenStoppedParser_WhenCallingHandle_ParsekitPanics(t *testing.T) {
otherHandler := func(p *parsekit.ParseAPI) {
panic("This is not the handler you're looking for")
}
p := parsekit.NewParser(func(p *parsekit.ParseAPI) {
p.Stop()
p.Handle(otherHandler)
})
RunPanicTest(t, PanicTest{
func() { p.Execute("") },
"Illegal call to ParseAPI.Handle() from git.makaay.nl/mauricem/go-parsekit_test." +
"TestGivenStoppedParser_WhenCallingHandle_ParsekitPanics.func2: " +
"no calls allowed after ParseAPI.Stop()"})
}
func TestGivenParserWithError_WhenCallingHandle_ParsekitPanics(t *testing.T) {
otherHandler := func(p *parsekit.ParseAPI) {
panic("This is not the handler you're looking for")
}
p := parsekit.NewParser(func(p *parsekit.ParseAPI) {
p.Error("It ends here")
p.Handle(otherHandler)
})
RunPanicTest(t, PanicTest{
func() { p.Execute("") },
"Illegal call to ParseAPI.Handle() from git.makaay.nl/mauricem/go-parsekit_test." +
"TestGivenParserWithError_WhenCallingHandle_ParsekitPanics.func2: " +
"no calls allowed after ParseAPI.Error()"})
}
func TestGivenFilledStringBuffer_BufInterpreted_ReturnsInterpretedString(t *testing.T) {
var interpreted string
var literal string
p := parsekit.NewParser(func(p *parsekit.ParseAPI) {
p.On(parsekit.C.OneOrMore(parsekit.A.AnyRune)).Accept()
literal = p.BufLiteral()
interpreted, _ = p.BufInterpreted()
})
p.Execute(`This\tis\ta\tcool\tstring`)
if literal != `This\tis\ta\tcool\tstring` {
t.Fatal("literal string is incorrect")
}
if interpreted != "This\tis\ta\tcool\tstring" {
t.Fatal("interpreted string is incorrect")
}
}
func TestGivenInputInvalidForStringInterpretation_BufInterpreted_SetsError(t *testing.T) {
p := parsekit.NewParser(func(p *parsekit.ParseAPI) {
p.On(parsekit.C.OneOrMore(parsekit.A.AnyRune)).Accept()
p.BufInterpreted()
})
err := p.Execute(`This \is wrongly escaped`)
if err.Error() != `invalid string: This \is wrongly escaped (invalid syntax, forgot to escape a double quote or backslash maybe?)` {
t.Fatalf("Got unexpected error: %s", err.Error())
}
}