testing: add T.Context method

From the doc comment:

Context returns the context for the current test or benchmark.
The context is cancelled when the test or benchmark finishes.
A goroutine started during a test or benchmark can wait for the
context's Done channel to become readable as a signal that the
test or benchmark is over, so that the goroutine can exit.

Fixes #16221.
Fixes #17552.

Change-Id: I657df946be2c90048cc74615436c77c7d9d1226c
Reviewed-on: https://go-review.googlesource.com/31724
Reviewed-by: Rob Pike <r@golang.org>
This commit is contained in:
Brad Fitzpatrick 2016-10-22 07:25:21 -07:00 committed by Russ Cox
parent 606f81eef3
commit 26827bc2fe
5 changed files with 96 additions and 34 deletions

View file

@ -6,6 +6,7 @@ package testing
import (
"bytes"
"context"
"regexp"
"strings"
"sync/atomic"
@ -277,28 +278,33 @@ func TestTRun(t *T) {
ok: true,
maxPar: 4,
f: func(t *T) {
t.Parallel()
for i := 0; i < 12; i++ {
t.Run("a", func(t *T) {
t.Parallel()
time.Sleep(time.Nanosecond)
for i := 0; i < 12; i++ {
t.Run("b", func(t *T) {
time.Sleep(time.Nanosecond)
for i := 0; i < 12; i++ {
t.Run("c", func(t *T) {
t.Parallel()
time.Sleep(time.Nanosecond)
t.Run("d1", func(t *T) {})
t.Run("d2", func(t *T) {})
t.Run("d3", func(t *T) {})
t.Run("d4", func(t *T) {})
})
}
})
}
})
}
// t.Parallel doesn't work in the pseudo-T we start with:
// it leaks a goroutine.
// Call t.Run to get a real one.
t.Run("X", func(t *T) {
t.Parallel()
for i := 0; i < 12; i++ {
t.Run("a", func(t *T) {
t.Parallel()
time.Sleep(time.Nanosecond)
for i := 0; i < 12; i++ {
t.Run("b", func(t *T) {
time.Sleep(time.Nanosecond)
for i := 0; i < 12; i++ {
t.Run("c", func(t *T) {
t.Parallel()
time.Sleep(time.Nanosecond)
t.Run("d1", func(t *T) {})
t.Run("d2", func(t *T) {})
t.Run("d3", func(t *T) {})
t.Run("d4", func(t *T) {})
})
}
})
}
})
}
})
},
}, {
desc: "skip output",
@ -341,6 +347,7 @@ func TestTRun(t *T) {
},
context: ctx,
}
root.ctx, root.cancel = context.WithCancel(context.Background())
ok := root.Run(tc.desc, tc.f)
ctx.release()