package parser_test import ( "fmt" "strings" "testing" "git.makaay.nl/mauricem/go-parsekit" "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.P) ([]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: %s\nactual: %s\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("No string representation available for parsekit.Item id %d", i.Type)) } }