| 1 |
package testingcontext |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
|
| 6 |
"testing" |
| 7 |
) |
| 8 |
|
| 9 |
func Test(t *testing.T) { |
| 10 |
ctx := t.Context() |
| 11 |
_ = ctx |
| 12 |
|
| 13 |
func() { |
| 14 |
ctx, cancel := context.WithCancel(context.Background()) // Nope. scope of defer is not the testing func. |
| 15 |
defer cancel() |
| 16 |
_ = ctx |
| 17 |
}() |
| 18 |
|
| 19 |
{ |
| 20 |
ctx := t.Context() |
| 21 |
_ = ctx |
| 22 |
var t int // not in scope of the call to WithCancel |
| 23 |
_ = t |
| 24 |
} |
| 25 |
|
| 26 |
{ |
| 27 |
ctx := context.Background() |
| 28 |
ctx, cancel := context.WithCancel(context.Background()) // Nope. ctx is redeclared. |
| 29 |
defer cancel() |
| 30 |
_ = ctx |
| 31 |
} |
| 32 |
|
| 33 |
{ |
| 34 |
var t int |
| 35 |
ctx, cancel := context.WithCancel(context.Background()) // Nope. t is shadowed. |
| 36 |
defer cancel() |
| 37 |
_ = ctx |
| 38 |
_ = t |
| 39 |
} |
| 40 |
|
| 41 |
t.Run("subtest", func(t2 *testing.T) { |
| 42 |
ctx := t2.Context() |
| 43 |
_ = ctx |
| 44 |
}) |
| 45 |
} |
| 46 |
|
| 47 |
func TestAlt(t2 *testing.T) { |
| 48 |
ctx := t2.Context() |
| 49 |
_ = ctx |
| 50 |
} |
| 51 |
|
| 52 |
func Testnot(t *testing.T) { |
| 53 |
ctx, cancel := context.WithCancel(context.Background()) // Nope. Not a test func. |
| 54 |
defer cancel() |
| 55 |
_ = ctx |
| 56 |
} |
| 57 |
|
| 58 |
func Benchmark(b *testing.B) { |
| 59 |
ctx := b.Context() |
| 60 |
_ = ctx |
| 61 |
|
| 62 |
b.Run("subtest", func(b2 *testing.B) { |
| 63 |
ctx := b2.Context() |
| 64 |
_ = ctx |
| 65 |
}) |
| 66 |
} |
| 67 |
|
| 68 |
func Fuzz(f *testing.F) { |
| 69 |
ctx := f.Context() |
| 70 |
_ = ctx |
| 71 |
} |