main.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // list all unit and ginkgo test names that will be run
  14. package main
  15. import (
  16. "encoding/json"
  17. "flag"
  18. "fmt"
  19. "go/ast"
  20. "go/parser"
  21. "go/token"
  22. "log"
  23. "os"
  24. "path/filepath"
  25. "strconv"
  26. "strings"
  27. )
  28. var (
  29. dumpTree = flag.Bool("dump", false, "print AST")
  30. dumpJSON = flag.Bool("json", false, "output test list as JSON")
  31. warn = flag.Bool("warn", false, "print warnings")
  32. )
  33. // Test holds test locations, package names, and test names.
  34. type Test struct {
  35. Loc string
  36. Name string
  37. TestName string
  38. }
  39. // collect extracts test metadata from a file.
  40. // If src is nil, it reads filename for the code, otherwise it
  41. // uses src (which may be a string, byte[], or io.Reader).
  42. func collect(filename string, src interface{}) []Test {
  43. // Create the AST by parsing src.
  44. fset := token.NewFileSet() // positions are relative to fset
  45. f, err := parser.ParseFile(fset, filename, src, parser.ParseComments)
  46. if err != nil {
  47. panic(err)
  48. }
  49. if *dumpTree {
  50. ast.Print(fset, f)
  51. }
  52. tests := make([]Test, 0)
  53. ast.Walk(makeWalker("[k8s.io]", fset, &tests), f)
  54. // Unit tests are much simpler to enumerate!
  55. if strings.HasSuffix(filename, "_test.go") {
  56. packageName := f.Name.Name
  57. dirName, _ := filepath.Split(filename)
  58. if filepath.Base(dirName) != packageName && *warn {
  59. log.Printf("Warning: strange path/package mismatch %s %s\n", filename, packageName)
  60. }
  61. testPath := "k8s.io/kubernetes/" + dirName[:len(dirName)-1]
  62. for _, decl := range f.Decls {
  63. funcdecl, ok := decl.(*ast.FuncDecl)
  64. if !ok {
  65. continue
  66. }
  67. name := funcdecl.Name.Name
  68. if strings.HasPrefix(name, "Test") {
  69. tests = append(tests, Test{fset.Position(funcdecl.Pos()).String(), testPath, name})
  70. }
  71. }
  72. }
  73. return tests
  74. }
  75. // funcName converts a selectorExpr with two idents into a string,
  76. // x.y -> "x.y"
  77. func funcName(n ast.Expr) string {
  78. if sel, ok := n.(*ast.SelectorExpr); ok {
  79. if x, ok := sel.X.(*ast.Ident); ok {
  80. return x.String() + "." + sel.Sel.String()
  81. }
  82. }
  83. return ""
  84. }
  85. // isSprintf returns whether the given node is a call to fmt.Sprintf
  86. func isSprintf(n ast.Expr) bool {
  87. call, ok := n.(*ast.CallExpr)
  88. return ok && funcName(call.Fun) == "fmt.Sprintf" && len(call.Args) != 0
  89. }
  90. type walker struct {
  91. path string
  92. fset *token.FileSet
  93. tests *[]Test
  94. vals map[string]string
  95. }
  96. func makeWalker(path string, fset *token.FileSet, tests *[]Test) *walker {
  97. return &walker{path, fset, tests, make(map[string]string)}
  98. }
  99. // clone creates a new walker with the given string extending the path.
  100. func (w *walker) clone(ext string) *walker {
  101. return &walker{w.path + " " + ext, w.fset, w.tests, w.vals}
  102. }
  103. // firstArg attempts to statically determine the value of the first
  104. // argument. It only handles strings, and converts any unknown values
  105. // (fmt.Sprintf interpolations) into *.
  106. func (w *walker) firstArg(n *ast.CallExpr) string {
  107. if len(n.Args) == 0 {
  108. return ""
  109. }
  110. var lit *ast.BasicLit
  111. if isSprintf(n.Args[0]) {
  112. return w.firstArg(n.Args[0].(*ast.CallExpr))
  113. }
  114. lit, ok := n.Args[0].(*ast.BasicLit)
  115. if ok && lit.Kind == token.STRING {
  116. v, err := strconv.Unquote(lit.Value)
  117. if err != nil {
  118. panic(err)
  119. }
  120. if strings.Contains(v, "%") {
  121. v = strings.Replace(v, "%d", "*", -1)
  122. v = strings.Replace(v, "%v", "*", -1)
  123. v = strings.Replace(v, "%s", "*", -1)
  124. }
  125. return v
  126. }
  127. if ident, ok := n.Args[0].(*ast.Ident); ok {
  128. if val, ok := w.vals[ident.String()]; ok {
  129. return val
  130. }
  131. }
  132. if *warn {
  133. log.Printf("Warning: dynamic arg value: %v\n", w.fset.Position(n.Args[0].Pos()))
  134. }
  135. return "*"
  136. }
  137. // describeName returns the first argument of a function if it's
  138. // a Ginkgo-relevant function (Describe/KubeDescribe/Context),
  139. // and the empty string otherwise.
  140. func (w *walker) describeName(n *ast.CallExpr) string {
  141. switch x := n.Fun.(type) {
  142. case *ast.SelectorExpr:
  143. if x.Sel.Name != "KubeDescribe" {
  144. return ""
  145. }
  146. case *ast.Ident:
  147. if x.Name != "Describe" && x.Name != "Context" {
  148. return ""
  149. }
  150. default:
  151. return ""
  152. }
  153. return w.firstArg(n)
  154. }
  155. // itName returns the first argument if it's a call to It(), else "".
  156. func (w *walker) itName(n *ast.CallExpr) string {
  157. if fun, ok := n.Fun.(*ast.Ident); ok && fun.Name == "It" {
  158. return w.firstArg(n)
  159. }
  160. return ""
  161. }
  162. // Visit walks the AST, following Ginkgo context and collecting tests.
  163. // See the documentation for ast.Walk for more details.
  164. func (w *walker) Visit(n ast.Node) ast.Visitor {
  165. switch x := n.(type) {
  166. case *ast.CallExpr:
  167. name := w.describeName(x)
  168. if name != "" && len(x.Args) >= 2 {
  169. // If calling (Kube)Describe/Context, make a new
  170. // walker to recurse with the description added.
  171. return w.clone(name)
  172. }
  173. name = w.itName(x)
  174. if name != "" {
  175. // We've found an It() call, the full test name
  176. // can be determined now.
  177. if w.path == "[k8s.io]" && *warn {
  178. log.Printf("It without matching Describe: %s\n", w.fset.Position(n.Pos()))
  179. }
  180. *w.tests = append(*w.tests, Test{w.fset.Position(n.Pos()).String(), w.path, name})
  181. return nil // Stop walking
  182. }
  183. case *ast.AssignStmt:
  184. // Attempt to track literals that might be used as
  185. // arguments. This analysis is very unsound, and ignores
  186. // both scope and program flow, but is sufficient for
  187. // our minor use case.
  188. ident, ok := x.Lhs[0].(*ast.Ident)
  189. if ok {
  190. if isSprintf(x.Rhs[0]) {
  191. // x := fmt.Sprintf("something", args)
  192. w.vals[ident.String()] = w.firstArg(x.Rhs[0].(*ast.CallExpr))
  193. }
  194. if lit, ok := x.Rhs[0].(*ast.BasicLit); ok && lit.Kind == token.STRING {
  195. // x := "a literal string"
  196. v, err := strconv.Unquote(lit.Value)
  197. if err != nil {
  198. panic(err)
  199. }
  200. w.vals[ident.String()] = v
  201. }
  202. }
  203. }
  204. return w // Continue walking
  205. }
  206. type testList struct {
  207. tests []Test
  208. }
  209. // handlePath walks the filesystem recursively, collecting tests
  210. // from files with paths *e2e*.go and *_test.go, ignoring third_party
  211. // and staging directories.
  212. func (t *testList) handlePath(path string, info os.FileInfo, err error) error {
  213. if err != nil {
  214. return err
  215. }
  216. if strings.Contains(path, "third_party") ||
  217. strings.Contains(path, "staging") ||
  218. strings.Contains(path, "_output") {
  219. return filepath.SkipDir
  220. }
  221. if strings.HasSuffix(path, ".go") && strings.Contains(path, "e2e") ||
  222. strings.HasSuffix(path, "_test.go") {
  223. tests := collect(path, nil)
  224. t.tests = append(t.tests, tests...)
  225. }
  226. return nil
  227. }
  228. func main() {
  229. flag.Parse()
  230. args := flag.Args()
  231. if len(args) == 0 {
  232. args = append(args, ".")
  233. }
  234. tests := testList{}
  235. for _, arg := range args {
  236. err := filepath.Walk(arg, tests.handlePath)
  237. if err != nil {
  238. log.Fatalf("Error walking: %v", err)
  239. }
  240. }
  241. if *dumpJSON {
  242. json, err := json.Marshal(tests.tests)
  243. if err != nil {
  244. log.Fatal(err)
  245. }
  246. fmt.Println(string(json))
  247. } else {
  248. for _, t := range tests.tests {
  249. fmt.Println(t)
  250. }
  251. }
  252. }