forked from mbergin/controlflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controlflow_test.go
91 lines (85 loc) · 1.99 KB
/
controlflow_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package controlflow
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"strings"
"testing"
)
func Test(t *testing.T) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, "./testdata", nil, 0)
if err != nil {
t.Fatal(err)
}
pkg := pkgs["testdata"]
tests := map[string]struct {
input []ast.Stmt
expected []ast.Stmt
}{}
for _, file := range pkg.Files {
for _, decl := range file.Decls {
if decl, ok := decl.(*ast.FuncDecl); ok {
name := decl.Name.Name
if strings.HasSuffix(name, "Input") {
k := strings.TrimSuffix(name, "Input")
test := tests[k]
test.input = decl.Body.List
tests[k] = test
} else if strings.HasSuffix(name, "Expected") {
k := strings.TrimSuffix(name, "Expected")
test := tests[k]
test.expected = decl.Body.List
tests[k] = test
}
}
}
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
gotAST := ElimGotos(test.input)
want := astString(test.expected, token.NewFileSet())
got := astString(gotAST, token.NewFileSet())
if want != got {
t.Error("\n" + sideBySide("want:", "got:", lines(want), lines(got)))
}
})
}
}
func sideBySide(titleX, titleY string, xs, ys []string) string {
n := len(xs)
if len(ys) > n {
n = len(ys)
}
var w bytes.Buffer
fmt.Fprintf(&w, "%-40s %-40s\n", titleX, titleY)
for i := 0; i < n; i++ {
x := ""
y := ""
if i < len(xs) {
x = strings.TrimRight(xs[i], " \r\n\t")
}
if i < len(ys) {
y = strings.TrimRight(ys[i], " \r\n\t")
}
fmt.Fprintf(&w, "| %-40s | %-40s\n", x, y)
}
return w.String()
}
func astString(node interface{}, fset *token.FileSet) string {
var buf bytes.Buffer
// Tabs screw up the side-by-side alignment
config := printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}
config.Fprint(&buf, fset, node)
return buf.String()
}
func lines(s string) []string {
lines := strings.Split(s, "\n")
for i := range lines {
lines[i] = strings.TrimRight(lines[i], " \t") + "\n"
}
return lines
}