如何检查*testing.T
是否已设置为并行运行?
理想的解决方案可能是:
func isParellelT(t *testing.T) bool {
// return some means to figure t has called t.Parallel().
}
testing.T
不提供此信息。你的测试不应该依赖于它。如果你想这样做,你几乎肯定应该做别的事情。
然而,可以使用反射访问私有数据,或者通过检查testing.T.SetEnv
是否恐慌来推导私有数据😈:
package para
import (
"reflect"
"strings"
"testing"
)
func TestParallelTrue(t *testing.T) {
t.Parallel()
if !isParallel(t) {
t.Errorf("isParallel: got = false; want = true")
}
if !isParallel2(t) {
t.Errorf("isParallel2: got = false; want = true")
}
}
func TestParallelFalse(t *testing.T) {
if isParallel(t) {
t.Errorf("isParallel: got = true; want = false")
}
if isParallel2(t) {
t.Errorf("isParallel2: got = true; want = false")
}
}
// WARNING: This is terrible and should never be used.
// It will likely break on old or future versions of Go.
func isParallel(t *testing.T) (b bool) {
v := reflect.ValueOf(t).Elem()
// Check testing.T.isParallel first.
isPara := v.FieldByName("isParallel")
if isPara.IsValid() {
return isPara.Bool()
}
// Otherwise try testing.T.common.isParallel.
common := v.FieldByName("common")
if !common.IsValid() {
t.Fatal("isParallel: unsupported testing.T implementation")
}
isPara = common.FieldByName("isParallel")
if !isPara.IsValid() {
t.Fatal("isParallel: unsupported testing.T implementation")
}
return isPara.Bool()
}
// WARNING: This is terrible and should never be used.
// Requires Go1.17+.
func isParallel2(t *testing.T) (b bool) {
defer func() {
v := recover()
if v == nil {
return
}
if s, ok := v.(string); ok && strings.Contains(s, "parallel tests") {
b = true
return
}
panic(v)
}()
t.Setenv("_dummy", "value")
return false
}