| 1 | // Copyright 2020 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package testinggoroutine |
| 6 | |
| 7 | import ( |
| 8 | _ "embed" |
| 9 | "fmt" |
| 10 | "go/ast" |
| 11 | "go/token" |
| 12 | "go/types" |
| 13 | |
| 14 | "golang.org/x/tools/go/analysis" |
| 15 | "golang.org/x/tools/go/analysis/passes/inspect" |
| 16 | "golang.org/x/tools/go/ast/inspector" |
| 17 | "golang.org/x/tools/go/types/typeutil" |
| 18 | "golang.org/x/tools/internal/analysis/analyzerutil" |
| 19 | "golang.org/x/tools/internal/typesinternal" |
| 20 | ) |
| 21 | |
| 22 | //go:embed doc.go |
| 23 | var doc string |
| 24 | |
| 25 | var reportSubtest bool |
| 26 | |
| 27 | func init() { |
| 28 | Analyzer.Flags.BoolVar(&reportSubtest, "subtest", false, "whether to check if t.Run subtest is terminated correctly; experimental") |
| 29 | } |
| 30 | |
| 31 | var Analyzer = &analysis.Analyzer{ |
| 32 | Name: "testinggoroutine", |
| 33 | Doc: analyzerutil.MustExtractDoc(doc, "testinggoroutine"), |
| 34 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/testinggoroutine", |
| 35 | Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 36 | Run: run, |
| 37 | } |
| 38 | |
| 39 | func run(pass *analysis.Pass) (any, error) { |
| 40 | inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 41 | |
| 42 | if !typesinternal.Imports(pass.Pkg, "testing") { |
| 43 | return nil, nil |
| 44 | } |
| 45 | |
| 46 | toDecl := localFunctionDecls(pass.TypesInfo, pass.Files) |
| 47 | |
| 48 | // asyncs maps nodes whose statements will be executed concurrently |
| 49 | // with respect to some test function, to the call sites where they |
| 50 | // are invoked asynchronously. There may be multiple such call sites |
| 51 | // for e.g. test helpers. |
| 52 | asyncs := make(map[ast.Node][]*asyncCall) |
| 53 | var regions []ast.Node |
| 54 | addCall := func(c *asyncCall) { |
| 55 | if c != nil { |
| 56 | r := c.region |
| 57 | if asyncs[r] == nil { |
| 58 | regions = append(regions, r) |
| 59 | } |
| 60 | asyncs[r] = append(asyncs[r], c) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | // Collect all of the go callee() and t.Run(name, callee) extents. |
| 65 | inspect.Nodes([]ast.Node{ |
| 66 | (*ast.FuncDecl)(nil), |
| 67 | (*ast.GoStmt)(nil), |
| 68 | (*ast.CallExpr)(nil), |
| 69 | }, func(node ast.Node, push bool) bool { |
| 70 | if !push { |
| 71 | return false |
| 72 | } |
| 73 | switch node := node.(type) { |
| 74 | case *ast.FuncDecl: |
| 75 | return hasBenchmarkOrTestParams(node) |
| 76 | |
| 77 | case *ast.GoStmt: |
| 78 | c := goAsyncCall(pass.TypesInfo, node, toDecl) |
| 79 | addCall(c) |
| 80 | |
| 81 | case *ast.CallExpr: |
| 82 | c := tRunAsyncCall(pass.TypesInfo, node) |
| 83 | addCall(c) |
| 84 | } |
| 85 | return true |
| 86 | }) |
| 87 | |
| 88 | // Check for t.Forbidden() calls within each region r that is a |
| 89 | // callee in some go r() or a t.Run("name", r). |
| 90 | // |
| 91 | // Also considers a special case when r is a go t.Forbidden() call. |
| 92 | for _, region := range regions { |
| 93 | ast.Inspect(region, func(n ast.Node) bool { |
| 94 | if n == region { |
| 95 | return true // always descend into the region itself. |
| 96 | } else if asyncs[n] != nil { |
| 97 | return false // will be visited by another region. |
| 98 | } |
| 99 | |
| 100 | call, ok := n.(*ast.CallExpr) |
| 101 | if !ok { |
| 102 | return true |
| 103 | } |
| 104 | x, sel, fn := forbiddenMethod(pass.TypesInfo, call) |
| 105 | if x == nil { |
| 106 | return true |
| 107 | } |
| 108 | |
| 109 | for _, e := range asyncs[region] { |
| 110 | if !withinScope(e.scope, x) { |
| 111 | forbidden := formatMethod(sel, fn) // e.g. "(*testing.T).Forbidden |
| 112 | |
| 113 | var context string |
| 114 | var where analysis.Range = e.async // Put the report at the go fun() or t.Run(name, fun). |
| 115 | if _, local := e.fun.(*ast.FuncLit); local { |
| 116 | where = call // Put the report at the t.Forbidden() call. |
| 117 | } else if id, ok := e.fun.(*ast.Ident); ok { |
| 118 | context = fmt.Sprintf(" (%s calls %s)", id.Name, forbidden) |
| 119 | } |
| 120 | if _, ok := e.async.(*ast.GoStmt); ok { |
| 121 | pass.ReportRangef(where, "call to %s from a non-test goroutine%s", forbidden, context) |
| 122 | } else if reportSubtest { |
| 123 | pass.ReportRangef(where, "call to %s on %s defined outside of the subtest%s", forbidden, x.Name(), context) |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | return true |
| 128 | }) |
| 129 | } |
| 130 | |
| 131 | return nil, nil |
| 132 | } |
| 133 | |
| 134 | func hasBenchmarkOrTestParams(fnDecl *ast.FuncDecl) bool { |
| 135 | // Check that the function's arguments include "*testing.T" or "*testing.B". |
| 136 | params := fnDecl.Type.Params.List |
| 137 | |
| 138 | for _, param := range params { |
| 139 | if _, ok := typeIsTestingDotTOrB(param.Type); ok { |
| 140 | return true |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | return false |
| 145 | } |
| 146 | |
| 147 | func typeIsTestingDotTOrB(expr ast.Expr) (string, bool) { |
| 148 | starExpr, ok := expr.(*ast.StarExpr) |
| 149 | if !ok { |
| 150 | return "", false |
| 151 | } |
| 152 | selExpr, ok := starExpr.X.(*ast.SelectorExpr) |
| 153 | if !ok { |
| 154 | return "", false |
| 155 | } |
| 156 | varPkg := selExpr.X.(*ast.Ident) |
| 157 | if varPkg.Name != "testing" { |
| 158 | return "", false |
| 159 | } |
| 160 | |
| 161 | varTypeName := selExpr.Sel.Name |
| 162 | ok = varTypeName == "B" || varTypeName == "T" |
| 163 | return varTypeName, ok |
| 164 | } |
| 165 | |
| 166 | // asyncCall describes a region of code that needs to be checked for |
| 167 | // t.Forbidden() calls as it is started asynchronously from an async |
| 168 | // node go fun() or t.Run(name, fun). |
| 169 | type asyncCall struct { |
| 170 | region ast.Node // region of code to check for t.Forbidden() calls. |
| 171 | async ast.Node // *ast.GoStmt or *ast.CallExpr (for t.Run) |
| 172 | scope ast.Node // Report t.Forbidden() if t is not declared within scope. |
| 173 | fun ast.Expr // fun in go fun() or t.Run(name, fun) |
| 174 | } |
| 175 | |
| 176 | // withinScope returns true if x.Pos() is in [scope.Pos(), scope.End()]. |
| 177 | func withinScope(scope ast.Node, x *types.Var) bool { |
| 178 | if scope != nil { |
| 179 | return x.Pos() != token.NoPos && scope.Pos() <= x.Pos() && x.Pos() <= scope.End() |
| 180 | } |
| 181 | return false |
| 182 | } |
| 183 | |
| 184 | // goAsyncCall returns the extent of a call from a go fun() statement. |
| 185 | func goAsyncCall(info *types.Info, goStmt *ast.GoStmt, toDecl func(*types.Func) *ast.FuncDecl) *asyncCall { |
| 186 | call := goStmt.Call |
| 187 | |
| 188 | fun := ast.Unparen(call.Fun) |
| 189 | if id := typesinternal.UsedIdent(info, fun); id != nil { |
| 190 | if lit := funcLitInScope(id); lit != nil { |
| 191 | return &asyncCall{region: lit, async: goStmt, scope: nil, fun: fun} |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | if fn := typeutil.StaticCallee(info, call); fn != nil { // static call or method in the package? |
| 196 | if decl := toDecl(fn); decl != nil { |
| 197 | return &asyncCall{region: decl, async: goStmt, scope: nil, fun: fun} |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // Check go statement for go t.Forbidden() or go func(){t.Forbidden()}(). |
| 202 | return &asyncCall{region: goStmt, async: goStmt, scope: nil, fun: fun} |
| 203 | } |
| 204 | |
| 205 | // tRunAsyncCall returns the extent of a call from a t.Run("name", fun) expression. |
| 206 | func tRunAsyncCall(info *types.Info, call *ast.CallExpr) *asyncCall { |
| 207 | if len(call.Args) != 2 { |
| 208 | return nil |
| 209 | } |
| 210 | run := typeutil.Callee(info, call) |
| 211 | if run, ok := run.(*types.Func); !ok || !isMethodNamed(run, "testing", "Run") { |
| 212 | return nil |
| 213 | } |
| 214 | |
| 215 | fun := ast.Unparen(call.Args[1]) |
| 216 | if lit, ok := fun.(*ast.FuncLit); ok { // function lit? |
| 217 | return &asyncCall{region: lit, async: call, scope: lit, fun: fun} |
| 218 | } |
| 219 | |
| 220 | if id := typesinternal.UsedIdent(info, fun); id != nil { |
| 221 | if lit := funcLitInScope(id); lit != nil { // function lit in variable? |
| 222 | return &asyncCall{region: lit, async: call, scope: lit, fun: fun} |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | // Check within t.Run(name, fun) for calls to t.Forbidden, |
| 227 | // e.g. t.Run(name, func(t *testing.T){ t.Forbidden() }) |
| 228 | return &asyncCall{region: call, async: call, scope: fun, fun: fun} |
| 229 | } |
| 230 | |
| 231 | var forbidden = []string{ |
| 232 | "FailNow", |
| 233 | "Fatal", |
| 234 | "Fatalf", |
| 235 | "Skip", |
| 236 | "Skipf", |
| 237 | "SkipNow", |
| 238 | } |
| 239 | |
| 240 | // forbiddenMethod decomposes a call x.m() into (x, x.m, m) where |
| 241 | // x is a variable, x.m is a selection, and m is the static callee m. |
| 242 | // Returns (nil, nil, nil) if call is not of this form. |
| 243 | func forbiddenMethod(info *types.Info, call *ast.CallExpr) (*types.Var, *types.Selection, *types.Func) { |
| 244 | // Compare to typeutil.StaticCallee. |
| 245 | fun := ast.Unparen(call.Fun) |
| 246 | selExpr, ok := fun.(*ast.SelectorExpr) |
| 247 | if !ok { |
| 248 | return nil, nil, nil |
| 249 | } |
| 250 | sel := info.Selections[selExpr] |
| 251 | if sel == nil { |
| 252 | return nil, nil, nil |
| 253 | } |
| 254 | |
| 255 | var x *types.Var |
| 256 | if id, ok := ast.Unparen(selExpr.X).(*ast.Ident); ok { |
| 257 | x, _ = info.Uses[id].(*types.Var) |
| 258 | } |
| 259 | if x == nil { |
| 260 | return nil, nil, nil |
| 261 | } |
| 262 | |
| 263 | fn, _ := sel.Obj().(*types.Func) |
| 264 | if fn == nil || !isMethodNamed(fn, "testing", forbidden...) { |
| 265 | return nil, nil, nil |
| 266 | } |
| 267 | return x, sel, fn |
| 268 | } |
| 269 | |
| 270 | func formatMethod(sel *types.Selection, fn *types.Func) string { |
| 271 | var ptr string |
| 272 | rtype := sel.Recv() |
| 273 | if p, ok := types.Unalias(rtype).(*types.Pointer); ok { |
| 274 | ptr = "*" |
| 275 | rtype = p.Elem() |
| 276 | } |
| 277 | return fmt.Sprintf("(%s%s).%s", ptr, rtype.String(), fn.Name()) |
| 278 | } |