go-toml/lexer/helpers_test.go

76 lines
1.9 KiB
Go

package lexer_test
import (
"fmt"
"strings"
"testing"
"github.com/mmakaay/toml/lexer"
"github.com/mmakaay/toml/parser"
)
type statesT struct {
name string
in string
out interface{}
err string
}
func runStatesTs(t *testing.T, tests []statesT) {
for _, c := range tests {
runStatesT(t, c)
}
}
func runStatesT(t *testing.T, c statesT) {
l, err := lexer.NewParser(c.in).ToArray()
if err == nil && c.err != "" {
t.Errorf("[%s] Expected error '%s', but no error occurred", c.name, c.err)
}
if err != nil && c.err == "" {
t.Errorf("[%s] Expected no error, but got error '%s'", c.name, err)
}
if err != nil && c.err != "" && err.Error() != c.err {
t.Errorf("[%s] Got an unexpected error:\nexpected: %s\nactual: %s\n", c.name, c.err, err)
}
switch expected := c.out.(type) {
case []string:
if len(expected) != len(l) {
t.Errorf("[%s] Unexpected number of lexer items:\nexpected: %d\nactual: %d\n", c.name, len(expected), len(l))
}
for i, e := range expected {
v := ParserItemToString(l[i])
if v != e {
t.Errorf("[%s] Unexpected lexer item at index %d:\nexpected: %s\nactual: %s\n", c.name, i, e, v)
}
}
case string:
a := make([]string, len(l))
for _, v := range l {
a = append(a, ParserItemToString(v))
}
actual := strings.Join(a, "")
if actual != expected {
t.Errorf("[%s] Unexpected lexer output:\nexpected: %s\nactual: %s\n", c.name, expected, actual)
}
}
}
// ParserItemToString returns a string representation of the parser.Item.
func ParserItemToString(i parser.Item) string {
switch i.Type {
case lexer.ItemComment:
return fmt.Sprintf("#(%s)", i.Value)
case lexer.ItemKey:
return fmt.Sprintf("[%s]", i.Value)
case lexer.ItemString:
return fmt.Sprintf("STR(%s)", i.Value)
case lexer.ItemKeyDot:
return "."
case lexer.ItemAssignment:
return "="
default:
panic(fmt.Sprintf("No string representation available for parser.Item id %d", i.Type))
}
}