go-toml/helpers_test.go

91 lines
2.3 KiB
Go

package parser_test
import (
"fmt"
"strings"
"testing"
"git.makaay.nl/mauricem/go-parsekit"
parser "git.makaay.nl/mauricem/go-toml"
)
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)
}
}
// ToArray returns Parser items as an array.
// When an error occurs during scanning, a partial result will be
// returned, accompanied by the error that occurred.
func parseItemsToArray(p *parsekit.Run) ([]parsekit.Item, *parsekit.Error) {
var items []parsekit.Item
for {
item, err, more := p.Next()
if !more {
return items, err
}
items = append(items, item)
}
}
func runStatesT(t *testing.T, c statesT) {
p := parser.NewParser(c.in)
l, err := parseItemsToArray(p)
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 parser 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 parser 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 parser output:\nexpected: %q\nactual: %q\n", c.name, expected, actual)
}
}
}
// parserItemToString returns a string representation of the parsekit.Item.
func parserItemToString(i parsekit.Item) string {
switch i.Type {
case parser.ItemComment:
return fmt.Sprintf("#(%s)", i.Value)
case parser.ItemKey:
return fmt.Sprintf("[%s]", i.Value)
case parser.ItemString:
return fmt.Sprintf("STR(%s)", i.Value)
case parser.ItemKeyDot:
return "."
case parser.ItemAssignment:
return "="
default:
panic(fmt.Sprintf("parsekit bug: no string formatting exists for parsekit.Item id %d", i.Type))
}
}