forked from msazurestackworkloads/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
276 lines (251 loc) · 7.12 KB
/
main.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// list all unit and ginkgo test names that will be run
package main
import (
"encoding/json"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
var (
dumpTree = flag.Bool("dump", false, "print AST")
dumpJson = flag.Bool("json", false, "output test list as JSON")
warn = flag.Bool("warn", false, "print warnings")
)
type Test struct {
Loc string
Name string
TestName string
}
// collect extracts test metadata from a file.
// If src is nil, it reads filename for the code, otherwise it
// uses src (which may be a string, byte[], or io.Reader).
func collect(filename string, src interface{}) []Test {
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, filename, src, parser.ParseComments)
if err != nil {
panic(err)
}
if *dumpTree {
ast.Print(fset, f)
}
tests := make([]Test, 0)
ast.Walk(makeWalker("[k8s.io]", fset, &tests), f)
// Unit tests are much simpler to enumerate!
if strings.HasSuffix(filename, "_test.go") {
packageName := f.Name.Name
dirName, _ := filepath.Split(filename)
if filepath.Base(dirName) != packageName && *warn {
log.Printf("Warning: strange path/package mismatch %s %s\n", filename, packageName)
}
testPath := "k8s.io/kubernetes/" + dirName[:len(dirName)-1]
for _, decl := range f.Decls {
funcdecl, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
name := funcdecl.Name.Name
if strings.HasPrefix(name, "Test") {
tests = append(tests, Test{fset.Position(funcdecl.Pos()).String(), testPath, name})
}
}
}
return tests
}
// funcName converts a selectorExpr with two idents into a string,
// x.y -> "x.y"
func funcName(n ast.Expr) string {
if sel, ok := n.(*ast.SelectorExpr); ok {
if x, ok := sel.X.(*ast.Ident); ok {
return x.String() + "." + sel.Sel.String()
}
}
return ""
}
// isSprintf returns whether the given node is a call to fmt.Sprintf
func isSprintf(n ast.Expr) bool {
call, ok := n.(*ast.CallExpr)
return ok && funcName(call.Fun) == "fmt.Sprintf" && len(call.Args) != 0
}
type walker struct {
path string
fset *token.FileSet
tests *[]Test
vals map[string]string
}
func makeWalker(path string, fset *token.FileSet, tests *[]Test) *walker {
return &walker{path, fset, tests, make(map[string]string)}
}
// clone creates a new walker with the given string extending the path.
func (w *walker) clone(ext string) *walker {
return &walker{w.path + " " + ext, w.fset, w.tests, w.vals}
}
// firstArg attempts to statically determine the value of the first
// argument. It only handles strings, and converts any unknown values
// (fmt.Sprintf interpolations) into *.
func (w *walker) firstArg(n *ast.CallExpr) string {
if len(n.Args) == 0 {
return ""
}
var lit *ast.BasicLit
if isSprintf(n.Args[0]) {
return w.firstArg(n.Args[0].(*ast.CallExpr))
}
lit, ok := n.Args[0].(*ast.BasicLit)
if ok && lit.Kind == token.STRING {
v, err := strconv.Unquote(lit.Value)
if err != nil {
panic(err)
}
if strings.Contains(v, "%") {
v = strings.Replace(v, "%d", "*", -1)
v = strings.Replace(v, "%v", "*", -1)
v = strings.Replace(v, "%s", "*", -1)
}
return v
}
if ident, ok := n.Args[0].(*ast.Ident); ok {
if val, ok := w.vals[ident.String()]; ok {
return val
}
}
if *warn {
log.Printf("Warning: dynamic arg value: %v\n", w.fset.Position(n.Args[0].Pos()))
}
return "*"
}
// describeName returns the first argument of a function if it's
// a Ginkgo-relevant function (Describe/KubeDescribe/Context),
// and the empty string otherwise.
func (w *walker) describeName(n *ast.CallExpr) string {
switch x := n.Fun.(type) {
case *ast.SelectorExpr:
if x.Sel.Name != "KubeDescribe" {
return ""
}
case *ast.Ident:
if x.Name != "Describe" && x.Name != "Context" {
return ""
}
default:
return ""
}
return w.firstArg(n)
}
// itName returns the first argument if it's a call to It(), else "".
func (w *walker) itName(n *ast.CallExpr) string {
if fun, ok := n.Fun.(*ast.Ident); ok && fun.Name == "It" {
return w.firstArg(n)
}
return ""
}
// Visit walks the AST, following Ginkgo context and collecting tests.
// See the documentation for ast.Walk for more details.
func (w *walker) Visit(n ast.Node) ast.Visitor {
switch x := n.(type) {
case *ast.CallExpr:
name := w.describeName(x)
if name != "" && len(x.Args) >= 2 {
// If calling (Kube)Describe/Context, make a new
// walker to recurse with the description added.
return w.clone(name)
}
name = w.itName(x)
if name != "" {
// We've found an It() call, the full test name
// can be determined now.
if w.path == "[k8s.io]" && *warn {
log.Printf("It without matching Describe: %s\n", w.fset.Position(n.Pos()))
}
*w.tests = append(*w.tests, Test{w.fset.Position(n.Pos()).String(), w.path, name})
return nil // Stop walking
}
case *ast.AssignStmt:
// Attempt to track literals that might be used as
// arguments. This analysis is very unsound, and ignores
// both scope and program flow, but is sufficient for
// our minor use case.
ident, ok := x.Lhs[0].(*ast.Ident)
if ok {
if isSprintf(x.Rhs[0]) {
// x := fmt.Sprintf("something", args)
w.vals[ident.String()] = w.firstArg(x.Rhs[0].(*ast.CallExpr))
}
if lit, ok := x.Rhs[0].(*ast.BasicLit); ok && lit.Kind == token.STRING {
// x := "a literal string"
v, err := strconv.Unquote(lit.Value)
if err != nil {
panic(err)
}
w.vals[ident.String()] = v
}
}
}
return w // Continue walking
}
type testList struct {
tests []Test
}
// handlePath walks the filesystem recursively, collecting tests
// from files with paths *e2e*.go and *_test.go, ignoring third_party
// and staging directories.
func (t *testList) handlePath(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.Contains(path, "third_party") ||
strings.Contains(path, "staging") ||
strings.Contains(path, "_output") {
return filepath.SkipDir
}
if strings.HasSuffix(path, ".go") && strings.Contains(path, "e2e") ||
strings.HasSuffix(path, "_test.go") {
tests := collect(path, nil)
t.tests = append(t.tests, tests...)
}
return nil
}
func main() {
flag.Parse()
args := flag.Args()
if len(args) == 0 {
args = append(args, ".")
}
tests := testList{}
for _, arg := range args {
err := filepath.Walk(arg, tests.handlePath)
if err != nil {
log.Fatalf("Error walking: %v", err)
}
}
if *dumpJson {
json, err := json.Marshal(tests.tests)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(json))
} else {
for _, t := range tests.tests {
fmt.Println(t)
}
}
}