Skip to content

Commit

Permalink
detect defer statement
Browse files Browse the repository at this point in the history
  • Loading branch information
moricho committed Sep 4, 2020
1 parent 5745406 commit 8853808
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
17 changes: 16 additions & 1 deletion testdata/src/sample/cleanup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ func Test_Cleanup1(t *testing.T) { // want "Test_Cleanup1 should use t.Cleanup"
t.Parallel()

t.Run("Cleanup1_Sub1", func(t *testing.T) {
call("Cleanup1_Sub1")
t.Parallel()
call("Cleanup1_Sub1")
})

t.Run("Cleanup1_Sub2", func(t *testing.T) {
Expand All @@ -30,3 +30,18 @@ func Test_Cleanup2(t *testing.T) { // OK
call("Cleanup2_Sub2")
})
}

func Test_Cleanup3(t *testing.T) { // OK
t.Parallel()
call("Test_Cleanup3")

t.Run("Cleanup3_Sub1", func(t *testing.T) {
t.Parallel()
call("Cleanup3_Sub1")
})

t.Run("Cleanup3_Sub2", func(t *testing.T) {
t.Parallel()
call("Cleanup3_Sub2")
})
}
20 changes: 17 additions & 3 deletions tparallel.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,11 @@ func run(pass *analysis.Pass) (interface{}, error) {
}
}

useCleanup := isCalled(top, cleanup)
if isPararellSub && !useCleanup {
pass.Reportf(top.Pos(), "%s should use t.Cleanup", top.Name())
if isDeferCalled(top) {
useCleanup := isCalled(top, cleanup)
if isPararellSub && !useCleanup {
pass.Reportf(top.Pos(), "%s should use t.Cleanup instead of defer", top.Name())
}
}

if isParallelTop == isPararellSub {
Expand All @@ -71,6 +73,18 @@ func run(pass *analysis.Pass) (interface{}, error) {
return nil, nil
}

func isDeferCalled(f *ssa.Function) bool {
for _, block := range f.Blocks {
for _, instr := range block.Instrs {
switch instr.(type) {
case *ssa.Defer:
return true
}
}
}
return false
}

func isCalled(f *ssa.Function, typ *types.Func) bool {
for _, block := range f.Blocks {
for _, instr := range block.Instrs {
Expand Down

0 comments on commit 8853808

Please sign in to comment.