/
analyzer.go
639 lines (543 loc) · 15.6 KB
/
analyzer.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
package analyzer
import (
"flag"
"fmt"
"go/ast"
"go/token"
"go/types"
"sort"
"strings"
"github.com/gostaticanalysis/analysisutil"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
const (
doc = "thelper detects tests helpers which is not start with t.Helper() method."
checksDoc = `coma separated list of enabled checks
Available checks
` + checkTBegin + ` - check t.Helper() begins helper function
` + checkTFirst + ` - check *testing.T is first param of helper function
` + checkTName + ` - check *testing.T param has t name
Also available similar checks for benchmark and TB helpers: ` +
checkFBegin + `, ` + checkFFirst + `, ` + checkFName + `,` +
checkBBegin + `, ` + checkBFirst + `, ` + checkBName + `,` +
checkTBBegin + `, ` + checkTBFirst + `, ` + checkTBName + `
`
)
type enabledChecksValue map[string]struct{}
func (m enabledChecksValue) Enabled(c string) bool {
_, ok := m[c]
return ok
}
func (m enabledChecksValue) String() string {
ss := make([]string, 0, len(m))
for s := range m {
ss = append(ss, s)
}
sort.Strings(ss)
return strings.Join(ss, ",")
}
func (m enabledChecksValue) Set(s string) error {
ss := strings.FieldsFunc(s, func(c rune) bool { return c == ',' })
if len(ss) == 0 {
return nil
}
for k := range m {
delete(m, k)
}
for _, v := range ss {
switch v {
case checkTBegin, checkTFirst, checkTName,
checkFBegin, checkFFirst, checkFName,
checkBBegin, checkBFirst, checkBName,
checkTBBegin, checkTBFirst, checkTBName:
m[v] = struct{}{}
default:
return fmt.Errorf("unknown check name %q (see help for full list)", v)
}
}
return nil
}
const (
checkTBegin = "t_begin"
checkTFirst = "t_first"
checkTName = "t_name"
checkFBegin = "f_begin"
checkFFirst = "f_first"
checkFName = "f_name"
checkBBegin = "b_begin"
checkBFirst = "b_first"
checkBName = "b_name"
checkTBBegin = "tb_begin"
checkTBFirst = "tb_first"
checkTBName = "tb_name"
)
type thelper struct {
enabledChecks enabledChecksValue
}
// NewAnalyzer return a new thelper analyzer.
// thelper analyzes Go test codes how they use t.Helper() method.
func NewAnalyzer() *analysis.Analyzer {
thelper := thelper{}
thelper.enabledChecks = enabledChecksValue{
checkTBegin: struct{}{},
checkTFirst: struct{}{},
checkTName: struct{}{},
checkFBegin: struct{}{},
checkFFirst: struct{}{},
checkFName: struct{}{},
checkBBegin: struct{}{},
checkBFirst: struct{}{},
checkBName: struct{}{},
checkTBBegin: struct{}{},
checkTBFirst: struct{}{},
checkTBName: struct{}{},
}
a := &analysis.Analyzer{
Name: "thelper",
Doc: doc,
Run: thelper.run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
},
}
a.Flags.Init("thelper", flag.ExitOnError)
a.Flags.Var(&thelper.enabledChecks, "checks", checksDoc)
return a
}
func (t thelper) run(pass *analysis.Pass) (interface{}, error) {
tCheckOpts, fCheckOpts, bCheckOpts, tbCheckOpts, ok := t.buildCheckFuncOpts(pass)
if !ok {
return nil, nil
}
inspect, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
if !ok {
return nil, nil
}
var reports reports
nodeFilter := []ast.Node{
(*ast.FuncDecl)(nil),
(*ast.FuncLit)(nil),
(*ast.CallExpr)(nil),
}
inspect.Preorder(nodeFilter, func(node ast.Node) {
var fd funcDecl
switch n := node.(type) {
case *ast.FuncLit:
fd.Pos = n.Pos()
fd.Type = n.Type
fd.Body = n.Body
fd.Name = ast.NewIdent("")
case *ast.FuncDecl:
fd.Pos = n.Name.NamePos
fd.Type = n.Type
fd.Body = n.Body
fd.Name = n.Name
case *ast.CallExpr:
runSubtestExprs := extractSubtestExp(pass, n, tCheckOpts.subRun, tCheckOpts.subTestFuncType)
if len(runSubtestExprs) == 0 {
runSubtestExprs = extractSubtestExp(pass, n, bCheckOpts.subRun, bCheckOpts.subTestFuncType)
}
if len(runSubtestExprs) == 0 {
runSubtestExprs = extractSubtestFuzzExp(pass, n, fCheckOpts.subRun)
}
if len(runSubtestExprs) > 0 {
for _, expr := range runSubtestExprs {
reports.Filter(funcDefPosition(pass, expr))
}
} else {
reports.NoFilter(funcDefPosition(pass, n.Fun))
}
return
default:
return
}
checkFunc(pass, &reports, fd, tCheckOpts)
checkFunc(pass, &reports, fd, fCheckOpts)
checkFunc(pass, &reports, fd, bCheckOpts)
checkFunc(pass, &reports, fd, tbCheckOpts)
})
reports.Flush(pass)
return nil, nil
}
type checkFuncOpts struct {
skipPrefix string
varName string
fnHelper types.Object
subRun types.Object
subTestFuncType types.Type
hpType types.Type
ctxType types.Type
checkBegin bool
checkFirst bool
checkName bool
}
func (t thelper) buildCheckFuncOpts(pass *analysis.Pass) (checkFuncOpts, checkFuncOpts, checkFuncOpts, checkFuncOpts, bool) {
var ctxType types.Type
ctxObj := analysisutil.ObjectOf(pass, "context", "Context")
if ctxObj != nil {
ctxType = ctxObj.Type()
}
tCheckOpts, ok := t.buildTestCheckFuncOpts(pass, ctxType)
if !ok {
return checkFuncOpts{}, checkFuncOpts{}, checkFuncOpts{}, checkFuncOpts{}, false
}
fCheckOpts, ok := t.buildFuzzCheckFuncOpts(pass, ctxType)
if !ok {
return checkFuncOpts{}, checkFuncOpts{}, checkFuncOpts{}, checkFuncOpts{}, false
}
bCheckOpts, ok := t.buildBenchmarkCheckFuncOpts(pass, ctxType)
if !ok {
return checkFuncOpts{}, checkFuncOpts{}, checkFuncOpts{}, checkFuncOpts{}, false
}
tbCheckOpts, ok := t.buildTBCheckFuncOpts(pass, ctxType)
if !ok {
return checkFuncOpts{}, checkFuncOpts{}, checkFuncOpts{}, checkFuncOpts{}, false
}
return tCheckOpts, fCheckOpts, bCheckOpts, tbCheckOpts, true
}
func (t thelper) buildTestCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) (checkFuncOpts, bool) {
tObj := analysisutil.ObjectOf(pass, "testing", "T")
if tObj == nil {
return checkFuncOpts{}, false
}
tHelper, _, _ := types.LookupFieldOrMethod(tObj.Type(), true, tObj.Pkg(), "Helper")
if tHelper == nil {
return checkFuncOpts{}, false
}
tRun, _, _ := types.LookupFieldOrMethod(tObj.Type(), true, tObj.Pkg(), "Run")
if tRun == nil {
return checkFuncOpts{}, false
}
tType := types.NewPointer(tObj.Type())
tVar := types.NewVar(token.NoPos, nil, "t", tType)
return checkFuncOpts{
skipPrefix: "Test",
varName: "t",
fnHelper: tHelper,
subRun: tRun,
hpType: tType,
subTestFuncType: types.NewSignature(nil, types.NewTuple(tVar), nil, false),
ctxType: ctxType,
checkBegin: t.enabledChecks.Enabled(checkTBegin),
checkFirst: t.enabledChecks.Enabled(checkTFirst),
checkName: t.enabledChecks.Enabled(checkTName),
}, true
}
func (t thelper) buildFuzzCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) (checkFuncOpts, bool) {
fObj := analysisutil.ObjectOf(pass, "testing", "F")
if fObj == nil {
return checkFuncOpts{}, true // fuzzing supports since go1.18, it's ok, that testig.F is missed.
}
fHelper, _, _ := types.LookupFieldOrMethod(fObj.Type(), true, fObj.Pkg(), "Helper")
if fHelper == nil {
return checkFuncOpts{}, false
}
tFuzz, _, _ := types.LookupFieldOrMethod(fObj.Type(), true, fObj.Pkg(), "Fuzz")
if tFuzz == nil {
return checkFuncOpts{}, false
}
return checkFuncOpts{
skipPrefix: "Fuzz",
varName: "f",
fnHelper: fHelper,
subRun: tFuzz,
hpType: types.NewPointer(fObj.Type()),
ctxType: ctxType,
checkBegin: t.enabledChecks.Enabled(checkFBegin),
checkFirst: t.enabledChecks.Enabled(checkFFirst),
checkName: t.enabledChecks.Enabled(checkFName),
}, true
}
func (t thelper) buildBenchmarkCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) (checkFuncOpts, bool) {
bObj := analysisutil.ObjectOf(pass, "testing", "B")
if bObj == nil {
return checkFuncOpts{}, false
}
bHelper, _, _ := types.LookupFieldOrMethod(bObj.Type(), true, bObj.Pkg(), "Helper")
if bHelper == nil {
return checkFuncOpts{}, false
}
bRun, _, _ := types.LookupFieldOrMethod(bObj.Type(), true, bObj.Pkg(), "Run")
if bRun == nil {
return checkFuncOpts{}, false
}
bType := types.NewPointer(bObj.Type())
bVar := types.NewVar(token.NoPos, nil, "b", bType)
return checkFuncOpts{
skipPrefix: "Benchmark",
varName: "b",
fnHelper: bHelper,
subRun: bRun,
hpType: types.NewPointer(bObj.Type()),
subTestFuncType: types.NewSignature(nil, types.NewTuple(bVar), nil, false),
ctxType: ctxType,
checkBegin: t.enabledChecks.Enabled(checkBBegin),
checkFirst: t.enabledChecks.Enabled(checkBFirst),
checkName: t.enabledChecks.Enabled(checkBName),
}, true
}
func (t thelper) buildTBCheckFuncOpts(pass *analysis.Pass, ctxType types.Type) (checkFuncOpts, bool) {
tbObj := analysisutil.ObjectOf(pass, "testing", "TB")
if tbObj == nil {
return checkFuncOpts{}, false
}
tbHelper, _, _ := types.LookupFieldOrMethod(tbObj.Type(), true, tbObj.Pkg(), "Helper")
if tbHelper == nil {
return checkFuncOpts{}, false
}
return checkFuncOpts{
skipPrefix: "",
varName: "tb",
fnHelper: tbHelper,
hpType: tbObj.Type(),
ctxType: ctxType,
checkBegin: t.enabledChecks.Enabled(checkTBBegin),
checkFirst: t.enabledChecks.Enabled(checkTBFirst),
checkName: t.enabledChecks.Enabled(checkTBName),
}, true
}
type funcDecl struct {
Pos token.Pos
Name *ast.Ident
Type *ast.FuncType
Body *ast.BlockStmt
}
func checkFunc(pass *analysis.Pass, reports *reports, funcDecl funcDecl, opts checkFuncOpts) {
if !opts.checkFirst && !opts.checkBegin && !opts.checkName {
return
}
if opts.skipPrefix != "" && strings.HasPrefix(funcDecl.Name.Name, opts.skipPrefix) {
return
}
p, pos, ok := searchFuncParam(pass, funcDecl, opts.hpType)
if !ok {
return
}
if opts.checkFirst {
if pos != 0 {
checkFirstPassed := false
if pos == 1 && opts.ctxType != nil {
_, pos, ok := searchFuncParam(pass, funcDecl, opts.ctxType)
checkFirstPassed = ok && (pos == 0)
}
if !checkFirstPassed {
reports.Reportf(funcDecl.Pos, "parameter %s should be the first or after context.Context", opts.hpType)
}
}
}
if len(p.Names) > 0 && p.Names[0].Name != "_" {
if opts.checkName {
if p.Names[0].Name != opts.varName {
reports.Reportf(funcDecl.Pos, "parameter %s should have name %s", opts.hpType, opts.varName)
}
}
if opts.checkBegin {
if len(funcDecl.Body.List) == 0 || !isTHelperCall(pass, funcDecl.Body.List[0], opts.fnHelper) {
reports.Reportf(funcDecl.Pos, "test helper function should start from %s.Helper()", opts.varName)
}
}
}
}
// searchFuncParam search a function param with desired type.
// It returns the param field, its position, and true if something is found.
func searchFuncParam(pass *analysis.Pass, f funcDecl, p types.Type) (*ast.Field, int, bool) {
for i, f := range f.Type.Params.List {
if isExprHasType(pass, f.Type, p) {
return f, i, true
}
}
return nil, 0, false
}
// isTHelperCall returns true if provided statement 's' is t.Helper() or b.Helper() call.
func isTHelperCall(pass *analysis.Pass, s ast.Stmt, tHelper types.Object) bool {
exprStmt, ok := s.(*ast.ExprStmt)
if !ok {
return false
}
callExpr, ok := exprStmt.X.(*ast.CallExpr)
if !ok {
return false
}
selExpr, ok := callExpr.Fun.(*ast.SelectorExpr)
if !ok {
return false
}
return isSelectorCall(pass, selExpr, tHelper)
}
// extractSubtestExp analyzes that call expresion 'e' is t.Run or b.Run
// and returns subtest function.
func extractSubtestExp(
pass *analysis.Pass, e *ast.CallExpr, tbRun types.Object, testFuncType types.Type,
) []ast.Expr {
selExpr, ok := e.Fun.(*ast.SelectorExpr)
if !ok {
return nil
}
if !isSelectorCall(pass, selExpr, tbRun) {
return nil
}
if len(e.Args) != 2 {
return nil
}
if funcs := unwrapTestingFunctionBuilding(pass, e.Args[1], testFuncType); funcs != nil {
return funcs
}
return []ast.Expr{e.Args[1]}
}
// extractSubtestFuzzExp analyzes that call expresion 'e' is f.Fuzz
// and returns subtest function.
func extractSubtestFuzzExp(
pass *analysis.Pass, e *ast.CallExpr, fuzzRun types.Object,
) []ast.Expr {
selExpr, ok := e.Fun.(*ast.SelectorExpr)
if !ok {
return nil
}
if !isSelectorCall(pass, selExpr, fuzzRun) {
return nil
}
if len(e.Args) != 1 {
return nil
}
return []ast.Expr{e.Args[0]}
}
// unwrapTestingFunctionConstruction checks that expresion is build testing functions
// and returns the result of building.
func unwrapTestingFunctionBuilding(pass *analysis.Pass, expr ast.Expr, testFuncType types.Type) []ast.Expr {
callExpr, ok := expr.(*ast.CallExpr)
if !ok {
return nil
}
var funcDecl funcDecl
switch f := callExpr.Fun.(type) {
case *ast.FuncLit:
funcDecl.Body = f.Body
funcDecl.Type = f.Type
case *ast.Ident:
funObjDecl := findFunctionDeclaration(pass, f)
if funObjDecl == nil {
return nil
}
funcDecl.Body = funObjDecl.Body
funcDecl.Type = funObjDecl.Type
case *ast.SelectorExpr:
fd := findSelectorDeclaration(pass, f)
if fd == nil {
return nil
}
funcDecl.Body = fd.Body
funcDecl.Type = fd.Type
default:
return nil
}
results := funcDecl.Type.Results.List
if len(results) != 1 || !isExprHasType(pass, results[0].Type, testFuncType) {
return nil
}
var funcs []ast.Expr
ast.Inspect(funcDecl.Body, func(n ast.Node) bool {
if n == nil {
return false
}
if retStmt, ok := n.(*ast.ReturnStmt); ok {
if len(retStmt.Results) == 1 {
funcs = append(funcs, retStmt.Results[0])
}
}
return true
})
return funcs
}
// funcDefPosition returns a function's position.
// It works with anonymous functions as well with function names.
func funcDefPosition(pass *analysis.Pass, e ast.Expr) token.Pos {
anonFunLit, ok := e.(*ast.FuncLit)
if ok {
return anonFunLit.Pos()
}
funIdent, ok := e.(*ast.Ident)
if !ok {
selExpr, ok := e.(*ast.SelectorExpr)
if !ok {
return token.NoPos
}
funIdent = selExpr.Sel
}
funDef, ok := pass.TypesInfo.Uses[funIdent]
if !ok {
return token.NoPos
}
return funDef.Pos()
}
// isSelectorCall checks is selExpr is a call expresion on specific callObj.
// Useful to check Run() call for t.Run or b.Run.
func isSelectorCall(pass *analysis.Pass, selExpr *ast.SelectorExpr, callObj types.Object) bool {
sel, ok := pass.TypesInfo.Selections[selExpr]
if !ok {
return false
}
return sel.Obj() == callObj
}
// isExprHasType returns true if expr has expected type.
func isExprHasType(pass *analysis.Pass, expr ast.Expr, expType types.Type) bool {
typeInfo, ok := pass.TypesInfo.Types[expr]
if !ok {
return false
}
return types.Identical(typeInfo.Type, expType)
}
// findSelectorDeclaration returns function declaration called by selector expression.
func findSelectorDeclaration(pass *analysis.Pass, expr *ast.SelectorExpr) *ast.FuncDecl {
xsel, ok := pass.TypesInfo.Selections[expr]
if !ok {
return nil
}
for _, file := range pass.Files {
for _, decl := range file.Decls {
fd, ok := decl.(*ast.FuncDecl)
if ok && fd.Recv != nil && len(fd.Recv.List) == 1 {
recvType, ok := fd.Recv.List[0].Type.(*ast.Ident)
if !ok {
continue
}
recvObj, ok := pass.TypesInfo.Uses[recvType]
if !ok {
continue
}
if !(types.Identical(recvObj.Type(), xsel.Recv())) {
continue
}
if fd.Name.Name == expr.Sel.Name {
return fd
}
}
}
}
return nil
}
// findFunctionDeclaration returns function declaration called by identity.
func findFunctionDeclaration(pass *analysis.Pass, ident *ast.Ident) *ast.FuncDecl {
if ident.Obj != nil {
if funObjDecl, ok := ident.Obj.Decl.(*ast.FuncDecl); ok {
return funObjDecl
}
}
obj := pass.TypesInfo.ObjectOf(ident)
if obj == nil {
return nil
}
for _, file := range pass.Files {
for _, decl := range file.Decls {
funcDecl, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
if funcDecl.Name.Pos() == obj.Pos() {
return funcDecl
}
}
}
return nil
}