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 277 278 279
|
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package testinggoroutine
import (
_ "embed"
"fmt"
"go/ast"
"go/token"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/analysis/passes/internal/analysisutil"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
"golang.org/x/tools/internal/aliases"
)
//go:embed doc.go
var doc string
var reportSubtest bool
func init() {
Analyzer.Flags.BoolVar(&reportSubtest, "subtest", false, "whether to check if t.Run subtest is terminated correctly; experimental")
}
var Analyzer = &analysis.Analyzer{
Name: "testinggoroutine",
Doc: analysisutil.MustExtractDoc(doc, "testinggoroutine"),
URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/testinggoroutine",
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: run,
}
func run(pass *analysis.Pass) (interface{}, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
if !analysisutil.Imports(pass.Pkg, "testing") {
return nil, nil
}
toDecl := localFunctionDecls(pass.TypesInfo, pass.Files)
// asyncs maps nodes whose statements will be executed concurrently
// with respect to some test function, to the call sites where they
// are invoked asynchronously. There may be multiple such call sites
// for e.g. test helpers.
asyncs := make(map[ast.Node][]*asyncCall)
var regions []ast.Node
addCall := func(c *asyncCall) {
if c != nil {
r := c.region
if asyncs[r] == nil {
regions = append(regions, r)
}
asyncs[r] = append(asyncs[r], c)
}
}
// Collect all of the go callee() and t.Run(name, callee) extents.
inspect.Nodes([]ast.Node{
(*ast.FuncDecl)(nil),
(*ast.GoStmt)(nil),
(*ast.CallExpr)(nil),
}, func(node ast.Node, push bool) bool {
if !push {
return false
}
switch node := node.(type) {
case *ast.FuncDecl:
return hasBenchmarkOrTestParams(node)
case *ast.GoStmt:
c := goAsyncCall(pass.TypesInfo, node, toDecl)
addCall(c)
case *ast.CallExpr:
c := tRunAsyncCall(pass.TypesInfo, node)
addCall(c)
}
return true
})
// Check for t.Forbidden() calls within each region r that is a
// callee in some go r() or a t.Run("name", r).
//
// Also considers a special case when r is a go t.Forbidden() call.
for _, region := range regions {
ast.Inspect(region, func(n ast.Node) bool {
if n == region {
return true // always descend into the region itself.
} else if asyncs[n] != nil {
return false // will be visited by another region.
}
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
x, sel, fn := forbiddenMethod(pass.TypesInfo, call)
if x == nil {
return true
}
for _, e := range asyncs[region] {
if !withinScope(e.scope, x) {
forbidden := formatMethod(sel, fn) // e.g. "(*testing.T).Forbidden
var context string
var where analysis.Range = e.async // Put the report at the go fun() or t.Run(name, fun).
if _, local := e.fun.(*ast.FuncLit); local {
where = call // Put the report at the t.Forbidden() call.
} else if id, ok := e.fun.(*ast.Ident); ok {
context = fmt.Sprintf(" (%s calls %s)", id.Name, forbidden)
}
if _, ok := e.async.(*ast.GoStmt); ok {
pass.ReportRangef(where, "call to %s from a non-test goroutine%s", forbidden, context)
} else if reportSubtest {
pass.ReportRangef(where, "call to %s on %s defined outside of the subtest%s", forbidden, x.Name(), context)
}
}
}
return true
})
}
return nil, nil
}
func hasBenchmarkOrTestParams(fnDecl *ast.FuncDecl) bool {
// Check that the function's arguments include "*testing.T" or "*testing.B".
params := fnDecl.Type.Params.List
for _, param := range params {
if _, ok := typeIsTestingDotTOrB(param.Type); ok {
return true
}
}
return false
}
func typeIsTestingDotTOrB(expr ast.Expr) (string, bool) {
starExpr, ok := expr.(*ast.StarExpr)
if !ok {
return "", false
}
selExpr, ok := starExpr.X.(*ast.SelectorExpr)
if !ok {
return "", false
}
varPkg := selExpr.X.(*ast.Ident)
if varPkg.Name != "testing" {
return "", false
}
varTypeName := selExpr.Sel.Name
ok = varTypeName == "B" || varTypeName == "T"
return varTypeName, ok
}
// asyncCall describes a region of code that needs to be checked for
// t.Forbidden() calls as it is started asynchronously from an async
// node go fun() or t.Run(name, fun).
type asyncCall struct {
region ast.Node // region of code to check for t.Forbidden() calls.
async ast.Node // *ast.GoStmt or *ast.CallExpr (for t.Run)
scope ast.Node // Report t.Forbidden() if t is not declared within scope.
fun ast.Expr // fun in go fun() or t.Run(name, fun)
}
// withinScope returns true if x.Pos() is in [scope.Pos(), scope.End()].
func withinScope(scope ast.Node, x *types.Var) bool {
if scope != nil {
return x.Pos() != token.NoPos && scope.Pos() <= x.Pos() && x.Pos() <= scope.End()
}
return false
}
// goAsyncCall returns the extent of a call from a go fun() statement.
func goAsyncCall(info *types.Info, goStmt *ast.GoStmt, toDecl func(*types.Func) *ast.FuncDecl) *asyncCall {
call := goStmt.Call
fun := astutil.Unparen(call.Fun)
if id := funcIdent(fun); id != nil {
if lit := funcLitInScope(id); lit != nil {
return &asyncCall{region: lit, async: goStmt, scope: nil, fun: fun}
}
}
if fn := typeutil.StaticCallee(info, call); fn != nil { // static call or method in the package?
if decl := toDecl(fn); decl != nil {
return &asyncCall{region: decl, async: goStmt, scope: nil, fun: fun}
}
}
// Check go statement for go t.Forbidden() or go func(){t.Forbidden()}().
return &asyncCall{region: goStmt, async: goStmt, scope: nil, fun: fun}
}
// tRunAsyncCall returns the extent of a call from a t.Run("name", fun) expression.
func tRunAsyncCall(info *types.Info, call *ast.CallExpr) *asyncCall {
if len(call.Args) != 2 {
return nil
}
run := typeutil.Callee(info, call)
if run, ok := run.(*types.Func); !ok || !isMethodNamed(run, "testing", "Run") {
return nil
}
fun := astutil.Unparen(call.Args[1])
if lit, ok := fun.(*ast.FuncLit); ok { // function lit?
return &asyncCall{region: lit, async: call, scope: lit, fun: fun}
}
if id := funcIdent(fun); id != nil {
if lit := funcLitInScope(id); lit != nil { // function lit in variable?
return &asyncCall{region: lit, async: call, scope: lit, fun: fun}
}
}
// Check within t.Run(name, fun) for calls to t.Forbidden,
// e.g. t.Run(name, func(t *testing.T){ t.Forbidden() })
return &asyncCall{region: call, async: call, scope: fun, fun: fun}
}
var forbidden = []string{
"FailNow",
"Fatal",
"Fatalf",
"Skip",
"Skipf",
"SkipNow",
}
// forbiddenMethod decomposes a call x.m() into (x, x.m, m) where
// x is a variable, x.m is a selection, and m is the static callee m.
// Returns (nil, nil, nil) if call is not of this form.
func forbiddenMethod(info *types.Info, call *ast.CallExpr) (*types.Var, *types.Selection, *types.Func) {
// Compare to typeutil.StaticCallee.
fun := astutil.Unparen(call.Fun)
selExpr, ok := fun.(*ast.SelectorExpr)
if !ok {
return nil, nil, nil
}
sel := info.Selections[selExpr]
if sel == nil {
return nil, nil, nil
}
var x *types.Var
if id, ok := astutil.Unparen(selExpr.X).(*ast.Ident); ok {
x, _ = info.Uses[id].(*types.Var)
}
if x == nil {
return nil, nil, nil
}
fn, _ := sel.Obj().(*types.Func)
if fn == nil || !isMethodNamed(fn, "testing", forbidden...) {
return nil, nil, nil
}
return x, sel, fn
}
func formatMethod(sel *types.Selection, fn *types.Func) string {
var ptr string
rtype := sel.Recv()
if p, ok := aliases.Unalias(rtype).(*types.Pointer); ok {
ptr = "*"
rtype = p.Elem()
}
return fmt.Sprintf("(%s%s).%s", ptr, rtype.String(), fn.Name())
}
|