github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/testing/helperfuncs_test.go (about) 1 // Copyright 2017 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 testing 6 7 import "sync" 8 9 // The line numbering of this file is important for TestTBHelper. 10 11 func notHelper(t *T, msg string) { 12 t.Error(msg) 13 } 14 15 func helper(t *T, msg string) { 16 t.Helper() 17 t.Error(msg) 18 } 19 20 func notHelperCallingHelper(t *T, msg string) { 21 helper(t, msg) 22 } 23 24 func helperCallingHelper(t *T, msg string) { 25 t.Helper() 26 helper(t, msg) 27 } 28 29 func genericHelper[G any](t *T, msg string) { 30 t.Helper() 31 t.Error(msg) 32 } 33 34 var genericIntHelper = genericHelper[int] 35 36 func testHelper(t *T) { 37 // Check combinations of directly and indirectly 38 // calling helper functions. 39 notHelper(t, "0") 40 helper(t, "1") 41 notHelperCallingHelper(t, "2") 42 helperCallingHelper(t, "3") 43 44 // Check a function literal closing over t that uses Helper. 45 fn := func(msg string) { 46 t.Helper() 47 t.Error(msg) 48 } 49 fn("4") 50 51 t.Run("sub", func(t *T) { 52 helper(t, "5") 53 notHelperCallingHelper(t, "6") 54 // Check that calling Helper from inside a subtest entry function 55 // works as if it were in an ordinary function call. 56 t.Helper() 57 t.Error("7") 58 }) 59 60 // Check that calling Helper from inside a top-level test function 61 // has no effect. 62 t.Helper() 63 t.Error("8") 64 65 // Check that right caller is reported for func passed to Cleanup when 66 // multiple cleanup functions have been registered. 67 t.Cleanup(func() { 68 t.Helper() 69 t.Error("10") 70 }) 71 t.Cleanup(func() { 72 t.Helper() 73 t.Error("9") 74 }) 75 76 // Check that helper-ness propagates up through subtests 77 // to helpers above. See https://golang.org/issue/44887. 78 helperSubCallingHelper(t, "11") 79 80 // Check that helper-ness propagates up through panic/recover. 81 // See https://golang.org/issue/31154. 82 recoverHelper(t, "12") 83 84 genericHelper[float64](t, "GenericFloat64") 85 genericIntHelper(t, "GenericInt") 86 } 87 88 func parallelTestHelper(t *T) { 89 var wg sync.WaitGroup 90 for i := 0; i < 5; i++ { 91 wg.Add(1) 92 go func() { 93 notHelperCallingHelper(t, "parallel") 94 wg.Done() 95 }() 96 } 97 wg.Wait() 98 } 99 100 func helperSubCallingHelper(t *T, msg string) { 101 t.Helper() 102 t.Run("sub2", func(t *T) { 103 t.Helper() 104 t.Fatal(msg) 105 }) 106 } 107 108 func recoverHelper(t *T, msg string) { 109 t.Helper() 110 defer func() { 111 t.Helper() 112 if err := recover(); err != nil { 113 t.Errorf("recover %s", err) 114 } 115 }() 116 doPanic(t, msg) 117 } 118 119 func doPanic(t *T, msg string) { 120 t.Helper() 121 panic(msg) 122 }