nswrap/ast/ast_test.go

109 lines
2.4 KiB
Go
Raw Normal View History

2019-04-09 11:52:21 -04:00
package ast
import (
"fmt"
"reflect"
"strings"
"testing"
"git.wow.st/gmp/nswrap/util"
2019-04-09 11:52:21 -04:00
)
2019-06-04 00:14:04 -04:00
type testNode struct {
n Node
addr Address
pos Position
2019-06-04 00:14:04 -04:00
children []Node
}
2019-05-31 10:21:04 -04:00
func init() {
TrackPositions = true
}
2019-04-09 11:52:21 -04:00
func formatMultiLine(o interface{}) string {
s := fmt.Sprintf("%#v", o)
s = strings.Replace(s, "{", "{\n", -1)
s = strings.Replace(s, ", ", "\n", -1)
return s
}
2019-06-04 00:14:04 -04:00
func runNodeTest(t *testing.T, actual Node, expected testNode, i *int) {
testName := fmt.Sprintf("Example%d", *i)
t.Run(testName+"a", func(t *testing.T) {
2019-06-04 00:14:04 -04:00
if !reflect.DeepEqual(expected.n, actual) {
t.Errorf("%s", util.ShowDiff(formatMultiLine(expected.n),
2019-05-31 10:21:04 -04:00
formatMultiLine(actual)))
}
})
2019-06-04 00:14:04 -04:00
t.Run(testName+"b", func(t *testing.T) {
if !reflect.DeepEqual(actual.Address(), expected.addr) {
2019-06-04 00:14:04 -04:00
t.Errorf("Address mismatch")
}
})
t.Run(testName+"c", func(t *testing.T) {
if !reflect.DeepEqual(actual.Position(), expected.pos) {
2019-06-04 00:14:04 -04:00
t.Errorf("Position mismatch")
}
})
t.Run(testName+"d", func(t *testing.T) {
if !reflect.DeepEqual(actual.Children(), expected.children) {
2019-06-04 00:14:04 -04:00
t.Errorf("Children mismatch")
}
})
t.Run(testName+"e", func(t *testing.T) {
cs := expected.children
node := &Unknown{}
actual.AddChild(node)
cs = append(cs, node)
if !reflect.DeepEqual(actual.Children(), cs) {
2019-06-04 00:14:04 -04:00
t.Errorf("Children mismatch")
}
})
(*i)++
2019-05-31 10:21:04 -04:00
}
2019-06-04 00:14:04 -04:00
func runNodeTests(t *testing.T, tests map[string]testNode) {
2019-04-09 11:52:21 -04:00
i := 1
for line, expected := range tests {
2019-05-31 10:21:04 -04:00
// Append the name of the struct onto the front. This would
// make the complete line it would normally be parsing.
2019-06-04 00:14:04 -04:00
name := reflect.TypeOf(expected.n).Elem().Name()
2019-05-31 10:21:04 -04:00
actual := Parse(name + " " + line)
2019-04-09 11:52:21 -04:00
runNodeTest(t, actual, expected, &i)
2019-04-09 11:52:21 -04:00
}
}
func TestPrint(t *testing.T) {
cond := &ConditionalOperator{}
cond.AddChild(&ImplicitCastExpr{})
cond.AddChild(&ImplicitCastExpr{})
s := Atos(cond)
if len(s) == 0 {
t.Fatalf("Cannot convert AST tree : %#v", cond)
}
lines := strings.Split(s, "\n")
var amount int
for _, l := range lines {
if strings.Contains(l, "ImplicitCastExpr") {
amount++
}
}
if amount != 2 {
t.Error("Not correct design of output")
}
}
var lines = []string{
// c2go ast sqlite3.c | head -5000 | sed 's/^[ |`-]*//' | sed 's/<<<NULL>>>/NullStmt/g' | gawk 'length > 0 {print "`" $0 "`,"}'
2019-04-09 11:52:21 -04:00
}
func BenchmarkParse(b *testing.B) {
for n := 0; n < b.N; n++ {
for _, line := range lines {
Parse(line)
}
}
}